Merge branch 'devel' of github:foosel/OctoPrint into dev/permission

This commit is contained in:
Marc Hannappel committed 2017-07-05 11:44:24 +02:00
commit 120406d115
180 files changed
+16327 -4363

No files matched your search

+24 -31
View File
@@ -12,12 +12,13 @@ import hashlib
import os
import yaml
import uuid
import wrapt
import logging
from builtins import range, bytes
from octoprint.settings import settings
from octoprint.util import atomic_write, deprecated
from octoprint.util import atomic_write, to_str, deprecated
from octoprint.access.permissions import Permissions
@@ -57,13 +58,13 @@ class UserManager(object):
if not isinstance(user, SessionUser):
user = SessionUser(user)
self._session_users_by_session[user.get_session()] = user
self._session_users_by_session[user.session] = user
userid = user.get_id()
if not userid in self._sessionids_by_userid:
self._sessionids_by_userid[userid] = set()
self._sessionids_by_userid[userid].add(user.get_session())
self._sessionids_by_userid[userid].add(user.session)
self._logger.debug("Logged in user: %r" % user)
@@ -80,7 +81,7 @@ class UserManager(object):
return
userid = user.get_id()
sessionid = user.get_session()
sessionid = user.session
if userid in self._sessionids_by_userid:
try:
@@ -98,7 +99,7 @@ class UserManager(object):
for session, user in self._session_users_by_session.items():
if not isinstance(user, SessionUser):
continue
if user._created + (24 * 60 * 60) < time.time():
if user.created + (24 * 60 * 60) < time.time():
self.logout_user(user)
@staticmethod
@@ -113,7 +114,7 @@ class UserManager(object):
settings().set(["accessControl", "salt"], salt)
settings().save()
return hashlib.sha512(password + salt).hexdigest()
return hashlib.sha512(to_str(password, encoding="utf-8", errors="replace") + to_str(salt)).hexdigest()
def checkPassword(self, username, password):
user = self.findUser(username)
@@ -501,7 +502,7 @@ class FilebasedUserManager(UserManager):
return None
def getAllUsers(self):
return self._users.values()
return map(lambda x: x.asDict(), self._users.values())
def hasBeenCustomized(self):
return self._customized
@@ -650,7 +651,7 @@ class User(UserMixin):
@property
@deprecated("is_user is deprecated, please use has_permissions", since="now")
def is_user(self):
return True
return OctoPrintUserMethodReplacedByBooleanProperty("is_user", lambda: "user" in self._roles)
@property
@deprecated("is_admin is deprecated, please use has_permissions", since="now")
@@ -821,10 +822,7 @@ class User(UserMixin):
return "User(id=%s,name=%s,active=%r,user=True,admin=%r,permissions=%s,groups=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._permissions, self._groups)
class AnonymousUser(User, AnonymousUserMixin):
def __init__(self):
from octoprint.server import groupManager
User.__init__(self, "Guest", "", True, [], [groupManager.guests_group])
class AnonymousUser(AnonymousUserMixin):
@property
def is_anonymous(self):
@@ -841,39 +839,34 @@ class AnonymousUser(User, AnonymousUserMixin):
def check_password(self, passwordHash):
return True
class SessionUser(User):
class SessionUser(wrapt.ObjectProxy):
def __init__(self, user):
self._user = user
wrapt.ObjectProxy.__init__(self, user)
import string
import random
import time
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
self._session = "".join(random.choice(chars) for _ in range(10))
self._created = time.time()
self._self_session = "".join(random.choice(chars) for _ in range(10))
self._self_created = time.time()
def __getattribute__(self, item):
if item in ("get_session", "update_user", "_user", "_session", "_created"):
return object.__getattribute__(self, item)
else:
return getattr(object.__getattribute__(self, "_user"), item)
@property
def session(self):
return self._self_session
def __setattr__(self, item, value):
if item in ("_user", "_session", "_created"):
return object.__setattr__(self, item, value)
else:
return setattr(self._user, item, value)
@property
def created(self):
return self._self_created
@deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5")
def get_session(self):
return self._session
return self.session
def update_user(self, user):
self._user = user
self.__wrapped__ = user
def __repr__(self):
return "SessionUser(id=%s,name=%s,active=%r,user=True,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._session, self._created)
return "SessionUser({!r},session={},created={})".format(self.__wrapped__, self.session, self.created)
##~~ DummyUser object to use when accessControl is disabled
+3 -3
View File
@@ -160,11 +160,11 @@ def octo(ctx, **kwargs):
"start|stop|restart\" is deprecated, please use "
"\"octoprint daemon start|stop|restart\" from now on")
if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
if sys.platform == "win32" or sys.platform == "darwin":
click.echo("Sorry, daemon mode is not supported under your operating system right now")
else:
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo("Sorry, daemon mode is not supported under your operating system right now")
else:
click.echo("Starting the server via \"octoprint\" is deprecated, "
"please use \"octoprint serve\" from now on.")
+24 -16
View File
@@ -79,30 +79,33 @@ def log_response(response, status_code=True, body=True, headers=False):
@client.command("get")
@click.argument("path")
@click.option("--timeout", type=float, default=None)
@click.pass_context
def get(ctx, path):
def get(ctx, path, timeout):
"""Performs a GET request against the specified server path."""
r = ctx.obj.client.get(path)
r = ctx.obj.client.get(path, timeout=timeout)
log_response(r)
@client.command("post_json")
@click.argument("path")
@click.argument("data", type=JsonStringParamType())
@click.option("--timeout", type=float, default=None)
@click.pass_context
def post_json(ctx, path, data):
def post_json(ctx, path, data, timeout):
"""POSTs JSON data to the specified server path."""
r = ctx.obj.client.post_json(path, data)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
log_response(r)
@client.command("patch_json")
@click.argument("path")
@click.argument("data", type=JsonStringParamType())
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def patch_json(ctx, path, data):
def patch_json(ctx, path, data, timeout):
"""PATCHes JSON data to the specified server path."""
r = ctx.obj.client.patch(path, data, encoding="json")
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
log_response(r)
@@ -111,9 +114,10 @@ def patch_json(ctx, path, data):
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.option("--json", is_flag=True)
@click.option("--yaml", is_flag=True)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def post_from_file(ctx, path, file_path, json_flag, yaml_flag):
"""POSTs JSON data to the specified server path."""
def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with open(file_path, "rb") as fp:
@@ -123,12 +127,12 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag):
with open(file_path, "rb") as fp:
data = yaml.safe_load(fp)
r = ctx.obj.client.post_json(path, data)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with open(file_path, "rb") as fp:
data = fp.read()
r = ctx.obj.client.post(path, data)
r = ctx.obj.client.post(path, data, timeout=timeout)
log_response(r)
@@ -140,14 +144,15 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag):
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def command(ctx, path, command, str_params, int_params, float_params, bool_params):
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
"""Sends a JSON command to the specified server path."""
data = dict()
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.post_command(path, command, additional=data)
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
log_response(r, body=False)
@@ -157,23 +162,26 @@ def command(ctx, path, command, str_params, int_params, float_params, bool_param
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
@click.option("--file-name", type=click.STRING)
@click.option("--content-type", type=click.STRING)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def upload(ctx, path, file_path, params, file_name, content_type):
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
"""Uploads the specified file to the specified server path."""
data = dict()
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type)
r = ctx.obj.client.upload(path, file_path,
additional=data, file_name=file_name, content_type=content_type, timeout=timeout)
log_response(r)
@client.command("delete")
@click.argument("path")
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def delete(ctx, path):
def delete(ctx, path, timeout):
"""Sends a DELETE request to the specified server path."""
r = ctx.obj.client.delete(path)
r = ctx.obj.client.delete(path, timeout=timeout)
log_response(r)
+3 -1
View File
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import click
from past.builtins import basestring
class OctoPrintDevelCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
@@ -204,7 +206,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
click.echo("This doesn't look like an OctoPrint plugin folder")
sys.exit(1)
self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path)
self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path)
return command
+2 -2
View File
@@ -150,8 +150,8 @@ def serve_command(ctx, **kwargs):
allow_root, logging, verbosity, safe_mode)
if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
# we only support daemon mode under Linux and FreeBSD for now
if sys.platform != "win32" and sys.platform != "darwin":
# we do not support daemon mode under windows or macosx
@server_commands.command(name="daemon")
@server_options
+2 -1
View File
@@ -84,6 +84,7 @@ class Events(object):
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# Timelapse
@@ -376,7 +377,7 @@ class CommandTrigger(GenericEventListener):
def _processCommand(self, command, payload):
"""
Performs string substitutions in the command string based on a couple of current parameters.
Performs string substitutions in the command string based on a few current parameters.
The following substitutions are currently supported:
+2
View File
@@ -20,6 +20,8 @@ from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
from collections import namedtuple
from past.builtins import basestring
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
+81 -27
View File
@@ -19,8 +19,6 @@ import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
import octoprint.util.gcodeInterpreter as gcodeInterpreter
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
"""
@@ -305,39 +303,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
* The extruded volume in cm³
"""
def _do_analysis(self, high_priority=False):
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
if throttle > 0:
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every 100 lines
time.sleep(throttle)
else:
throttle_callback = None
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
self._gcode = gcodeInterpreter.gcode()
self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback)
self._aborted = False
self._reenqueue = False
def _do_analysis(self, high_priority=False):
import sarge
import sys
import yaml
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py"))
command = [sys.executable, interpreter, "--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines)]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
self._aborted = False
p = sarge.run(command, async=True, stdout=sarge.Capture())
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command)))
try:
# let's wait for stuff to finish
while p.returncode is None:
if self._aborted:
# oh, we shall abort, let's do so!
p.commands[0].terminate()
raise AnalysisAborted(reenqueue=self._reenqueue)
# else continue
p.commands[0].poll()
finally:
p.close()
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
if not "RESULTS:" in output:
raise RuntimeError("No analysis result found")
_, output = output.split("RESULTS:")
analysis = yaml.safe_load(output)
result = dict()
result["printingArea"] = self._gcode.printing_area
result["dimensions"] = self._gcode.dimensions
if self._gcode.totalMoveTimeMinute:
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
if self._gcode.extrusionAmount:
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = dict()
for i in range(len(self._gcode.extrusionAmount)):
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": self._gcode.extrusionAmount[i],
"volume": self._gcode.extrusionVolume[i]
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i]
}
return result
except gcodeInterpreter.AnalysisAborted as ex:
raise AnalysisAborted(reenqueue=ex.reenqueue)
finally:
self._gcode = None
def _do_abort(self, reenqueue=True):
if self._gcode:
self._gcode.abort(reenqueue=reenqueue)
self._aborted = True
self._reenqueue = reenqueue
+4 -9
View File
@@ -20,6 +20,8 @@ from octoprint.util import atomic_write
from contextlib import contextmanager
from copy import deepcopy
from past.builtins import basestring
import octoprint.filemanager
from octoprint.util import is_hidden_path
@@ -669,16 +671,9 @@ class LocalFileStorage(StorageInterface):
# save the file's hash to the metadata of the folder
file_hash = self._create_hash(file_path)
metadata = self._get_metadata_entry(path, name, default=dict())
metadata_dirty = False
if not "hash" in metadata or metadata["hash"] != file_hash:
metadata["hash"] = file_hash
metadata_dirty = True
if "analysis" in metadata:
del metadata["analysis"]
metadata_dirty = True
if metadata_dirty:
self._update_metadata_entry(path, name, metadata)
# hash changed -> throw away old metadata
self._update_metadata_entry(path, name, dict(hash=file_hash))
# process any links that were also provided for adding to the file
if not links:
+19 -8
View File
@@ -104,7 +104,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
UiPlugin]
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = ["octoprint.server.http"]
plugin_restart_needing_hooks = ["octoprint.server.http.*",
"octoprint.printer.factory"]
if plugin_obsolete_hooks is None:
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
@@ -239,7 +240,7 @@ class PluginSettings(object):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
It provides a couple of convenience methods for directly accessing plugin settings via the regular
It provides some convenience methods for directly accessing plugin settings via the regular
:class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations.
All getter and setter methods will ensure that plugin settings are stored in their correct location within the
@@ -263,13 +264,17 @@ class PluginSettings(object):
:returns: The retrieved settings value.
:rtype: object
.. method:: get_int(path)
.. method:: get_int(path, min=None, max=None)
Like :func:`get` but tries to convert the retrieved value to ``int``.
Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
the value is greater than it.
.. method:: get_float(path)
.. method:: get_float(path, min=None, max=None)
Like :func:`get` but tries to convert the retrieved value to ``float``.
Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
the value is greater than it.
.. method:: get_boolean(path)
@@ -285,13 +290,19 @@ class PluginSettings(object):
:param boolean force: If set to True, the modified configuration will even be written back to disk if
the value didn't change.
.. method:: set_int(path, value, force=False)
.. method:: set_int(path, value, force=False, min=None, max=None)
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
that, ``max`` if greater than that) will be set instead.
.. method:: set_float(path, value, force=False)
.. method:: set_float(path, value, force=False, min=None, max=None)
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
that, ``max`` if greater than that) will be set instead.
.. method:: set_boolean(path, value, force=False)
+97 -30
View File
@@ -31,6 +31,7 @@ import os
import imp
from collections import defaultdict, namedtuple, OrderedDict
import logging
import fnmatch
import pkg_resources
import pkginfo
@@ -571,6 +572,10 @@ class PluginManager(object):
key = entry.name
elif entry.is_file() and entry.name.endswith(".py"):
key = entry.name[:-3] # strip off the .py extension
if key.startswith("__"):
# might be an __init__.py in our plugins folder, or something else we don't want
# to handle
continue
else:
continue
@@ -942,45 +947,107 @@ class PluginManager(object):
return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin)
def has_restart_needing_implementation(self, plugin):
if not plugin.implementation:
return False
return isinstance(plugin.implementation, RestartNeedingPlugin)
return self.has_any_of_mixins(plugin, RestartNeedingPlugin)
def has_restart_needing_hooks(self, plugin):
if not plugin.hooks:
return False
hooks = plugin.hooks.keys()
for hook in hooks:
if self.is_restart_needing_hook(hook):
return True
return False
return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks)
def has_obsolete_hooks(self, plugin):
if not plugin.hooks:
return False
hooks = plugin.hooks.keys()
for hook in hooks:
if self.is_obsolete_hook(hook):
return True
return False
return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks)
def is_restart_needing_hook(self, hook):
if self.plugin_restart_needing_hooks is None:
return False
for h in self.plugin_restart_needing_hooks:
if hook.startswith(h):
return True
return False
return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks)
def is_obsolete_hook(self, hook):
if self.plugin_obsolete_hooks is None:
return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks)
@staticmethod
def has_any_of_hooks(plugin, *hooks):
"""
Tests if the ``plugin`` contains any of the provided ``hooks``.
Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`.
Args:
plugin: plugin to test hooks for
*hooks: hooks to test against
Returns:
(bool): True if any of the plugin's hooks match the provided hooks,
False otherwise.
"""
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
hooks = hooks[0]
hooks = filter(lambda hook: hook is not None, hooks)
if not hooks:
return False
return hook in self.plugin_obsolete_hooks
if not plugin or not plugin.hooks:
return False
plugin_hooks = plugin.hooks.keys()
return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks),
plugin_hooks))
@staticmethod
def hook_matches_hooks(hook, *hooks):
"""
Tests if ``hook`` matches any of the provided ``hooks`` to test for.
``hook`` is expected to be an exact hook name.
``hooks`` is expected to be a list containing one or more hook names or
patterns. That can be either an exact hook name or an
:func:`fnmatch.fnmatch` pattern.
Args:
hook: the hook to test
hooks: the hook name patterns to test against
Returns:
(bool): True if the ``hook`` matches any of the ``hooks``, False otherwise.
"""
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
hooks = hooks[0]
hooks = filter(lambda hook: hook is not None, hooks)
if not hooks:
return False
if not hook:
return False
return any(map(lambda h: fnmatch.fnmatch(hook, h),
hooks))
@staticmethod
def has_any_of_mixins(plugin, *mixins):
"""
Tests if the ``plugin`` has an implementation implementing any
of the provided ``mixins``.
Args:
plugin: plugin for which to check the implementation
*mixins: mixins to test against
Returns:
(bool): True if the plugin's implementation implements any of the
provided mixins, False otherwise.
"""
if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)):
mixins = mixins[0]
mixins = filter(lambda mixin: mixin is not None, mixins)
if not mixins:
return False
if not plugin or not plugin.implementation:
return False
return isinstance(plugin.implementation, tuple(mixins))
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
for name, plugin in self.enabled_plugins.items():
+15 -6
View File
@@ -23,6 +23,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
from past.builtins import basestring
class OctoPrintPlugin(Plugin):
"""
@@ -531,7 +532,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
`Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object as
parameter. If you plugin returns `True` here, OctoPrint will next call
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like
- again - the Flask Request object and the render keyword arguments as
used by the default OctoPrint web interface. For more information see below.
@@ -582,7 +583,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
it only gets re-rendered if the request demands that (by having no-cache headers set) or if
the cache gets invalidated otherwise.
In order to be able to do that, the ``UiPlugin`` offers overriding a couple of cache specific
In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific
methods used for figuring out the source files whose modification time to use for cache invalidation
as well as override possibilities for ETag and LastModified calculation. Additionally there are
methods to allow persisting call parameters to allow for preemptively caching your UI during
@@ -742,7 +743,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
Returns:
basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
"""
return None
@@ -1038,7 +1039,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
mixin offers.
Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend
and/or want to react to simple commands which boil down to a type of command and a couple of flat parameters
and/or want to react to simple commands which boil down to a type of command and a few flat parameters
supplied with it.
The simple API constructed by OctoPrint for you will be made available under ``/api/plugin/<plugin identifier>/``.
@@ -1377,6 +1378,14 @@ class SettingsPlugin(OctoPrintPlugin):
Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the
default implementations do not fit your requirements.
.. warning::
Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users)
should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will
return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted,
therefore you **must** make sure that you specify sensitive information accordingly to limit access as required!
.. attribute:: _settings
The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
@@ -1548,8 +1557,8 @@ class SettingsPlugin(OctoPrintPlugin):
field="field"),
path=dict(to=dict(never=dict(return="return"))))
def get_settings_restricted_path(self):
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],
def get_settings_restricted_paths(self):
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],],
user=[["some", "user_only", "path"],],
never=[["path", "to", "never", "return"],])
+1
View File
@@ -0,0 +1 @@
# make our plugins testable
@@ -41,7 +41,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
# StartupPlugin
def on_after_startup(self):
self._fetch_all_channels()
# decouple channel fetching from server startup
def fetch_data():
self._fetch_all_channels()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
# SettingsPlugin
@@ -324,7 +330,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
url = config["url"]
try:
start = time.time()
r = requests.get(url)
r = requests.get(url, timeout=30)
r.raise_for_status()
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
except Exception as e:
self._logger.exception(
@@ -359,7 +366,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
return dict(title=entry["title"],
title_without_tags=_strip_tags(entry["title"]),
summary=entry["summary"],
summary=_lazy_images(entry["summary"]),
summary_without_images=_strip_images(entry["summary"]),
published=published,
link=entry["link"],
@@ -374,8 +381,57 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
_image_tag_re = re.compile(r'<img.*?/?>')
def _strip_images(text):
"""
>>> _strip_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
u"<a href='test.html'>I'm a link</a> and this is an image: "
>>> _strip_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">")
u'One and two and three and four '
>>> _strip_images(u"No images here")
u'No images here'
"""
return _image_tag_re.sub('', text)
def _replace_images(text, callback):
"""
>>> callback = lambda img: "foobar"
>>> _replace_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback)
u"<a href='test.html'>I'm a link</a> and this is an image: foobar"
>>> _replace_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback)
u'One foobar and two foobar and three foobar and four foobar'
"""
result = text
for match in _image_tag_re.finditer(text):
tag = match.group(0)
replaced = callback(tag)
result = result.replace(tag, replaced)
return result
_image_src_re = re.compile(r'src=(?P<quote>[\'"]*)(?P<src>.*?)(?P=quote)(?=\s+|>)')
def _lazy_images(text, placeholder=None):
"""
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png")
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
>>> _lazy_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png")
u'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="four">'
>>> _lazy_images(u"No images here")
u'No images here'
"""
if placeholder is None:
# 1px transparent gif
placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
def callback(img_tag):
match = _image_src_re.search(img_tag)
if match is not None:
src = match.group("src")
quote = match.group("quote")
quoted_src = quote + src + quote
img_tag = img_tag.replace(match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src))
return img_tag
return _replace_images(text, callback)
def _strip_tags(text):
"""
@@ -40,7 +40,7 @@ $(function() {
};
self.toggleButtonCss = function(data) {
var icon = data.enabled ? "icon-circle" : "icon-circle-blank";
var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -143,6 +143,9 @@ $(function() {
self.showAnnouncementDialog = function(channel) {
if (!self.loginState.isAdmin()) return;
// lazy load images that still need lazy-loading
$("#plugin_announcements_dialog_content article img").lazyload();
self.announcementDialogContent.scrollTop(0);
if (!self.announcementDialog.hasClass("in")) {
@@ -255,22 +258,22 @@ $(function() {
buttons: [{
text: gettext("Later"),
click: function(notice) {
self.hiddenChannels.push(key);
notice.remove();
self.hiddenChannels.push(key);
}
}, {
text: gettext("Mark read"),
click: function(notice) {
self.markRead(key, value.last);
notice.remove();
self.markRead(key, value.last);
}
}, {
text: gettext("Read..."),
addClass: "btn-primary",
click: function(notice) {
notice.remove();
self.showAnnouncementDialog(key);
self.markRead(key, value.last);
notice.remove();
}
}]
},
@@ -28,7 +28,7 @@
<div class="content" data-bind="html: $data.summary"></div>
<div class="actions">
<span class="articlelink"><small><a data-bind="text: $data.link, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="icon-eye-open"></i> {{ _('Mark as last read') }}</a></small></span>
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="fa fa-eye"></i> {{ _('Mark as last read') }}</a></small></span>
</div>
</article>
<!-- /ko -->
@@ -40,7 +40,7 @@
</div>
</div>
<div class="modal-footer">
<button class="btn configurelink" data-bind="click: configureAnnouncements"><i class="icon-wrench"></i></button>
<button class="btn configurelink" data-bind="click: configureAnnouncements"><i class="fa fa-wrench"></i></button>
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -1,3 +1,3 @@
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
<i data-bind="css: {'icon-bell': !unread(), 'icon-bell-alt': unread()}"></i>
<i class="fa" data-bind="css: {'fa-bell-o': !unread(), 'fa-bell': unread()}"></i>
</a>
@@ -32,4 +32,4 @@
</ul>
</div>
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="icon-refresh"></i> {{ _('Refresh Announcements') }}</button>
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="fa fa-refresh"></i> {{ _('Refresh Announcements') }}</button>
+10 -7
View File
@@ -49,9 +49,12 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ AssetPlugin API
def get_assets(self):
return dict(
js=["js/corewizard.js"]
)
if self.is_wizard_required():
return dict(
js=["js/corewizard.js"]
)
else:
return dict()
#~~ WizardPlugin API
@@ -74,7 +77,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
def _get_acl_wizard_details(self):
return dict()
return dict(required=self._is_acl_wizard_required())
def _get_acl_wizard_name(self):
return gettext("Access Control")
@@ -120,7 +123,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
def _get_webcam_wizard_details(self):
return dict()
return dict(required=self._is_webcam_wizard_required())
def _get_webcam_wizard_name(self):
return gettext("Webcam & Timelapse")
@@ -135,7 +138,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
return not (system_shutdown_command and system_restart_command and server_restart_command)
def _get_servercommands_wizard_details(self):
return dict()
return dict(required=self._is_servercommands_wizard_required())
def _get_servercommands_wizard_name(self):
return gettext("Server Commands")
@@ -146,7 +149,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
def _get_printerprofile_wizard_details(self):
return dict()
return dict(required=self._is_printerprofile_wizard_required())
def _get_printerprofile_wizard_name(self):
return gettext("Default Printer Profile")
@@ -11,6 +11,8 @@ $(function() {
self.setup = ko.observable(false);
self.decision = ko.observable();
self.required = false;
self.passwordMismatch = ko.pureComputed(function() {
return self.password() != self.confirmedPassword();
});
@@ -72,6 +74,8 @@ $(function() {
};
self.onBeforeWizardTabChange = function(next, current) {
if (!self.required) return true;
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
return true;
}
@@ -82,7 +86,13 @@ $(function() {
return false;
};
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required;
};
self.onWizardFinish = function() {
if (!self.required) return;
if (!self.decision()) {
return "reload";
}
@@ -94,7 +104,14 @@ $(function() {
self.settingsViewModel = parameters[0];
self.required = false;
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required;
};
self.onWizardFinish = function() {
if (!self.required) return;
if (self.settingsViewModel.webcam_streamUrl()
|| (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
return "reload";
@@ -113,18 +130,29 @@ $(function() {
self.printerProfiles = parameters[0];
self.required = false;
self.editor = self.printerProfiles.createProfileEditor();
self.editorLoaded = ko.observable(false);
self.onStartup = function() {
self.onWizardDetails = function(response) {
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required;
if (!self.required) return;
OctoPrint.printerprofiles.get("_default")
.done(function(data) {
self.editor.fromProfileData(data);
self.editorLoaded(true);
})
.fail(function() {
self.editor.fromProfileData();
self.editorLoaded(true);
});
};
self.onWizardFinish = function() {
if (!self.required) return;
OctoPrint.printerprofiles.update("_default", self.editor.toProfileData())
.done(function() {
self.printerProfiles.requestData();
+13 -5
View File
@@ -17,6 +17,7 @@ import octoprint.slicing
import octoprint.settings
from octoprint.util.paths import normalize as normalize_path
from octoprint.util import to_unicode
from .profile import Profile
from .profile import GcodeFlavors
@@ -236,7 +237,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None,
on_progress=None, on_progress_args=None, on_progress_kwargs=None):
try:
with self._job_mutex:
if not profile_path:
@@ -258,7 +260,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
if not on_progress_kwargs:
on_progress_kwargs = dict()
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}"
.format(to_unicode(model_path, errors="replace"),
to_unicode(machinecode_path, errors="replace"),
to_unicode(profile_path, errors="replace")))
executable = normalize_path(self._settings.get(["cura_engine"]))
if not executable:
@@ -293,7 +298,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
args += ["-s", "%s=%s" % (k, str(v))]
args += ["-o", machinecode_path, model_path]
self._logger.info(u"Running %r in %s" % (" ".join(args), working_dir))
self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"),
args)),
working_dir))
import sarge
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
@@ -314,7 +321,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
p.commands[0].poll()
continue
line = octoprint.util.to_unicode(line, errors="replace")
line = to_unicode(line, errors="replace")
self._cura_logger.debug(line.strip())
if on_progress is not None:
@@ -437,7 +444,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
command = self._slicing_commands[machinecode_path]
if command is not None:
command.terminate()
self._logger.info(u"Cancelled slicing of %s" % machinecode_path)
self._logger.info(u"Cancelled slicing of {}"
.format(to_unicode(machinecode_path, errors="replace")))
def _load_profile(self, path):
import yaml
+2
View File
@@ -7,7 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import re
from builtins import range
from past.builtins import basestring
class SupportLocationTypes(object):
NONE = "none"
+104 -39
View File
@@ -25,11 +25,35 @@ $(function() {
self.profileAllowOverwrite = ko.observable(true);
self.profileMakeDefault = ko.observable(false);
// make sure to update form data if any of the metadata changes
self.profileName.subscribe(function() { self.copyProfileMetadata(); });
self.profileDisplayName.subscribe(function() {
if (self.profileDisplayName()) {
self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase());
}
self.copyProfileMetadata();
});
self.profileDescription.subscribe(function() { self.copyProfileMetadata(); });
self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); });
self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); });
self.unconfiguredCuraEngine = ko.observable();
self.unconfiguredSlicingProfile = ko.observable();
self.uploadDialog = $("#settings_plugin_cura_import");
self.uploadElement = $("#settings-cura-import");
self.uploadButton = $("#settings-cura-import-start");
self.uploadData = ko.observable(undefined);
self.uploadBusy = ko.observable(false);
self.uploadEnabled = ko.pureComputed(function() {
return self.fieldsEnabled();
});
self.fieldsEnabled = ko.pureComputed(function() {
return self.uploadData() && !self.uploadBusy()
&& (self.profileName() || self.placeholderName())
&& (self.profileDisplayName() || self.placeholderDisplayName())
&& (self.profileDescription() || self.placeholderDescription());
});
self.profiles = new ItemListHelper(
"plugin_cura_profiles",
@@ -66,6 +90,53 @@ $(function() {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
self.performUpload = function() {
if (self.uploadData()) {
self.uploadData().submit();
}
};
self.copyProfileMetadata = function(form) {
form = form || (self.uploadData() ? self.uploadData().formData : {});
if (self.profileName() !== undefined) {
form["name"] = self.profileName();
} else if (self.placeholderName() !== undefined) {
form["name"] = self.placeholderName();
}
if (self.profileDisplayName() !== undefined) {
form["displayName"] = self.profileDisplayName();
} else if (self.placeholderDisplayName() !== undefined) {
form["displayName"] = self.placeholderDisplayName();
}
if (self.profileDescription() !== undefined) {
form["description"] = self.profileDescription();
} else if (self.placeholderDescription() !== undefined) {
form["description"] = self.placeholderDescription();
}
if (self.profileMakeDefault()) {
form["default"] = true;
}
return form;
};
self.clearUpload = function() {
self.uploadData(undefined);
self.fileName(undefined);
self.placeholderName(undefined);
self.placeholderDisplayName(undefined);
self.placeholderDescription(undefined);
self.profileName(undefined);
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
self.profileMakeDefault(false);
};
self.uploadElement.fileupload({
dataType: "json",
maxNumberOfFiles: 1,
@@ -73,6 +144,11 @@ $(function() {
headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
if (data.files.length == 0) {
// no files? ignore
return false;
}
if (self.uploadData()) {
// data already defined? ignore (should never happen)
return false;
}
@@ -83,41 +159,22 @@ $(function() {
self.placeholderDisplayName(name);
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
self.uploadButton.unbind("click");
self.uploadButton.on("click", function() {
var form = {
allowOverwrite: self.profileAllowOverwrite()
};
var form = {
allowOverwrite: self.profileAllowOverwrite()
};
data.formData = self.copyProfileMetadata(form);
if (self.profileName() !== undefined) {
form["name"] = self.profileName();
}
if (self.profileDisplayName() !== undefined) {
form["displayName"] = self.profileDisplayName();
}
if (self.profileDescription() !== undefined) {
form["description"] = self.profileDescription();
}
if (self.profileMakeDefault()) {
form["default"] = true;
}
data.formData = form;
data.submit();
});
self.uploadData(data);
},
submit: function(e, data) {
self.copyProfileMetadata();
self.uploadBusy(true);
},
done: function(e, data) {
self.fileName(undefined);
self.placeholderName(undefined);
self.placeholderDisplayName(undefined);
self.placeholderDescription(undefined);
self.profileName(undefined);
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
self.profileMakeDefault(false);
self.uploadBusy(false);
self.clearUpload();
$("#settings_plugin_cura_import").modal("hide");
self.uploadDialog.modal("hide");
self.requestData();
self.slicingViewModel.requestData();
}
@@ -160,12 +217,9 @@ $(function() {
});
};
self.showImportProfileDialog = function(makeDefault) {
if (makeDefault == undefined) {
makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0;
}
self.profileMakeDefault(makeDefault);
$("#settings_plugin_cura_import").modal("show");
self.showImportProfileDialog = function() {
self.clearUpload();
self.uploadDialog.modal("show");
};
self.testEnginePath = function() {
@@ -207,7 +261,18 @@ $(function() {
self.onBeforeBinding = function () {
self.settings = self.settingsViewModel.settings;
//self.requestData();
};
self.onAllBound = function() {
self.uploadDialog.on("hidden", function(event) {
if (event.target.id == "settings_plugin_cura_import") {
self.clearUpload();
}
});
};
self.onSettingsShown = function() {
self.requestData();
};
self.onSettingsHidden = function() {
@@ -20,31 +20,31 @@
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, valueUpdate: 'afterkeydown', attr: {placeholder: placeholderDisplayName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Description') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<label class="checkbox" data-bind="enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
<input type="checkbox" data-bind="checked: profileMakeDefault"> {{ _('Make default profile') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<label class="checkbox" data-bind="enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
</label>
</div>
@@ -59,6 +59,6 @@
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
<button class="btn btn-primary" data-bind="click: performUpload, enable: uploadEnabled, css: {disabled: !uploadEnabled()}" id="settings-cura-import-start"><i class="fa fa-spinner fa-spin" data-bind="visible: uploadBusy"></i> {{ _('Confirm') }}</button>
</div>
</div>
@@ -12,10 +12,10 @@
</thead>
<tbody data-bind="foreach: profiles.paginatedItems">
<tr data-bind="attr: {title: description}">
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
<td class="settings_plugin_cura_profiles_key"><span class="fa fa-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
<td class="settings_plugin_cura_profiles_actions">
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
<a href="#" class="fa fa-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-trash-o" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
</td>
</tr>
</tbody>
+77 -17
View File
@@ -5,6 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
from past.builtins import basestring
import octoprint.plugin
import octoprint.plugin.core
@@ -29,6 +30,7 @@ import pkg_resources
import copy
import dateutil.parser
import time
import threading
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
@@ -40,10 +42,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
OPERATING_SYSTEMS = dict(windows=["win32"],
linux=["linux2"],
macos=["darwin"])
linux=lambda x: x.startswith("linux"),
macos=["darwin"],
freebsd=lambda x: x.startswith("freebsd"))
pip_inapplicable_arguments = dict(uninstall=["--user"])
PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"])
RECONNECT_HOOKS = ["octoprint.comm.protocol.*",]
def __init__(self):
self._pending_enable = set()
@@ -85,7 +90,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
##~~ StartupPlugin
def on_startup(self, host, port):
def on_after_startup(self):
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3)
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
@@ -95,8 +100,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
self._repository_available = self._fetch_repository_from_disk()
self._notices_available = self._fetch_notices_from_disk()
# decouple repository fetching from server startup
def fetch_data():
self._repository_available = self._fetch_repository_from_disk()
self._notices_available = self._fetch_notices_from_disk()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
##~~ SettingsPlugin
@@ -408,6 +419,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
source_type=source_type,
needs_restart=True,
needs_refresh=True,
needs_reconnect=True,
was_reinstalled=False,
plugin="unknown")
self._send_result_notification("install", result)
@@ -419,6 +431,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
or reinstall is not None
needs_refresh = new_plugin.implementation \
and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational()
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled")
self._plugin_manager.mark_plugin(new_plugin.key,
@@ -433,6 +446,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
source_type=source_type,
needs_restart=needs_restart,
needs_refresh=needs_refresh,
needs_reconnect=needs_reconnect,
was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None,
plugin=self._to_external_plugin(new_plugin))
self._send_result_notification("install", result)
@@ -489,6 +503,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed")
self._plugin_manager.mark_plugin(plugin.key,
@@ -514,7 +529,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._plugin_manager.reload_plugins()
result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_plugin(plugin))
result = dict(result=True,
needs_restart=needs_restart,
needs_refresh=needs_refresh,
needs_reconnect=needs_reconnect,
plugin=self._to_external_plugin(plugin))
self._send_result_notification("uninstall", result)
return jsonify(result)
@@ -524,11 +543,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
needs_restart_api = (needs_restart or safe_mode_victim) and not pending
needs_refresh_api = needs_refresh and not pending
needs_reconnect_api = needs_reconnect and not pending
try:
if command == "disable":
@@ -542,11 +563,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
result = dict(result=True,
needs_restart=True,
needs_refresh=True,
needs_reconnect=True,
plugin=self._to_external_plugin(plugin))
else:
result = dict(result=True,
needs_restart=needs_restart_api,
needs_refresh=needs_refresh_api,
needs_reconnect=needs_reconnect_api,
plugin=self._to_external_plugin(plugin))
self._send_result_notification(command, result)
@@ -598,7 +621,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if additional_args is not None:
inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list())
inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list())
for inapplicable_argument in inapplicable_arguments:
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
@@ -676,7 +699,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def _fetch_repository_from_url(self):
repository_url = self._settings.get(["repository"])
try:
r = requests.get(repository_url)
r = requests.get(repository_url, timeout=30)
r.raise_for_status()
self._logger.info("Loaded plugin repository data from {}".format(repository_url))
except Exception as e:
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
@@ -744,7 +768,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def _fetch_notices_from_url(self):
notices_url = self._settings.get(["notices"])
try:
r = requests.get(notices_url)
r = requests.get(notices_url, timeout=30)
r.raise_for_status()
self._logger.info("Loaded plugin notices data from {}".format(notices_url))
except Exception as e:
self._logger.exception("Could not fetch notices from {notices_url}: {message}".format(notices_url=notices_url, message=str(e)))
@@ -808,18 +833,37 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return True
def _is_os_compatible(self, current_os, compatibility_entries):
@staticmethod
def _is_os_compatible(current_os, compatibility_entries):
"""
Tests if the ``current_os`` matches any of the provided ``compatibility_entries``.
Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries``
"""
return current_os in filter(lambda x: x in self.__class__.OPERATING_SYSTEMS.keys(), compatibility_entries)
if len(compatibility_entries) == 0:
# shortcut - no compatibility info means we are compatible
return True
def _get_os(self):
for identifier, platforms in self.__class__.OPERATING_SYSTEMS.items():
if sys.platform in platforms:
negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries))
positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries)
negative_match = False
if negative_entries:
# check if we are blacklisted
negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries))
positive_match = True
if positive_entries:
# check if we are whitelisted
positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries))
return positive_match and not negative_match
@classmethod
def _get_os(cls):
for identifier, platforms in cls.OPERATING_SYSTEMS.items():
if (callable(platforms) and platforms(sys.platform)) or (isinstance(platforms, list) and sys.platform in platforms):
return identifier
else:
return "unknown"
return "unmapped"
def _get_octoprint_version_string(self):
return VERSION
@@ -853,6 +897,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
return octoprint_version
@property
def _reconnect_hooks(self):
reconnect_hooks = self.__class__.RECONNECT_HOOKS
reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks")
for name, hook in reconnect_hook_provider_hooks.items():
try:
result = hook()
if isinstance(result, (list, tuple)):
reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result))
except:
self._logger.exception("Error while retrieving additional hooks for which a "
"reconnect is required from plugin {name}".format(**locals()))
return reconnect_hooks
def _get_plugins(self):
plugins = self._plugin_manager.plugins
@@ -527,13 +527,11 @@ $(function() {
if (reinstall) {
OctoPrint.plugins.pluginmanager.reinstall(reinstall, url, followDependencyLinks)
.done(onSuccess)
.fail(onError)
.always(onAlways);
.fail(onError);
} else {
OctoPrint.plugins.pluginmanager.install(url, followDependencyLinks)
.done(onSuccess)
.fail(onError)
.always(onAlways);
.fail(onError);
}
};
@@ -666,7 +664,7 @@ $(function() {
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible"));
};
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) {
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) {
var notification;
var beforeClose = function(notification) {
@@ -688,17 +686,21 @@ $(function() {
hide: false
};
var restartClicked = false;
if (self.restartCommandSpec) {
options.confirm = {
confirm: true,
buttons: [{
text: gettext("Restart now"),
click: function () {
click: function (notice) {
if (restartClicked) return;
restartClicked = true;
showConfirmationDialog({
message: gettext("This will restart your OctoPrint server."),
onproceed: function() {
OctoPrint.system.executeCommand("core", "restart")
.done(function() {
notice.remove();
new PNotify({
title: gettext("Restart in progress"),
text: gettext("The server is now being restarted in the background")
@@ -710,6 +712,9 @@ $(function() {
text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")
})
});
},
onclose: function() {
restartClicked = false;
}
});
}
@@ -719,6 +724,7 @@ $(function() {
notification = PNotify.singleButtonNotify(options);
} else if (response.needs_refresh) {
var refreshClicked = false;
notification = PNotify.singleButtonNotify({
title: titleSuccess,
text: textReload,
@@ -727,6 +733,8 @@ $(function() {
buttons: [{
text: gettext("Reload now"),
click: function () {
if (refreshClicked) return;
refreshClicked = true;
location.reload(true);
}
}]
@@ -740,6 +748,15 @@ $(function() {
},
hide: false
})
} else if (response.needs_reconnect) {
notification = new PNotify({
title: titleSuccess,
text: textReconnect,
callbacks: {
before_close: beforeClose
},
hide: false
})
} else {
notification = new PNotify({
title: titleSuccess,
@@ -798,7 +815,7 @@ $(function() {
};
self.toggleButtonCss = function(data) {
var icon = self._getToggleCommand(data) == "enable" ? "icon-circle-blank" : "icon-circle";
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -1053,7 +1070,7 @@ $(function() {
});
self._scrollWorkingOutputToEnd();
} else if (messageType == "result") {
var titleSuccess, textSuccess, textRestart, textReload, titleError, textError;
var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError;
var action = data.action;
var name = "Unknown";
@@ -1073,16 +1090,19 @@ $(function() {
textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly");
textRestart = textSuccess;
textReload = textSuccess;
textReconnect = textSuccess;
} else if (data.was_reinstalled) {
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
textSuccess = gettext("The plugin was reinstalled successfully");
textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect.");
} else {
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
textSuccess = gettext("The plugin was installed successfully");
textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect.");
}
titleError = gettext("Something went wrong");
@@ -1134,6 +1154,7 @@ $(function() {
textSuccess = gettext("The plugin was uninstalled successfully");
textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
@@ -1151,6 +1172,7 @@ $(function() {
textSuccess = gettext("The plugin was enabled successfully.");
textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
@@ -1168,6 +1190,7 @@ $(function() {
textSuccess = gettext("The plugin was disabled successfully.");
textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
@@ -1180,7 +1203,7 @@ $(function() {
return;
}
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError);
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError);
self.requestData();
}
};
@@ -25,7 +25,7 @@
{{ pluginmanager_safemode() }}
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
</div>
<h3>{{ _('Installed Plugins') }}</h3>
@@ -40,18 +40,18 @@
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="icon-medkit" data-bind="visible: safe_mode_victim"></i> <i class="icon-exclamation-sign" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i></div>
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i></div>
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
</div>
</td>
<td class="settings_plugin_plugin_manager_plugins_actions">
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
</td>
</tr>
</tbody>
@@ -73,8 +73,8 @@
<div class="muted" data-bind="visible: pipAvailable()">
<div>
<small>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="toggle-arrow icon-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="fa toggle-arrow fa-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
</a>
</small>
</div>
@@ -90,8 +90,8 @@
<div class="muted">
<div>
<small>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="toggle-arrow icon-caret-right"></i> <span data-bind="text: noticeCountText"></span>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
</a>
</small>
</div>
@@ -108,7 +108,7 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span><br></pre>
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
@@ -128,16 +128,16 @@
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
<div class="dropdown pull-right">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<span class="icon-wrench"></span>
<span class="fa fa-wrench"></span>
</a>
<ul class="dropdown-menu pull-right">
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="fa fa-check" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="fa fa-check" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="fa fa-check" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="fa fa-check" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="icon-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="fa fa-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
</ul>
</div>
</h4>
@@ -154,15 +154,15 @@
<div><span data-bind="text: title"></span></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div>
<small data-bind="visible: page"><i class="icon-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
<small data-bind="visible: homepage"><i class="icon-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
<small data-bind="visible: page"><i class="fa fa-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
<small data-bind="visible: homepage"><i class="fa fa-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
</div>
</div>
<div class="span3">
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="icon-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="fa fa-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
<div data-bind="visible: $data.disabled !== undefined" style="text-align: center"><small><a data-bind="attr: {href: page}" target="_blank">{{ _('"Why?"') }}</a></small></div>
</div>
</div>
@@ -209,7 +209,7 @@
</form>
<div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<form class="form-horizontal">
<div class="control-group">
@@ -36,6 +36,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin):
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
def __init__(self):
self._update_in_progress = False
self._configured_checks_mutex = threading.Lock()
@@ -48,6 +51,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache_ttl = 0
self._version_cache_path = None
self._version_cache_dirty = False
self._version_cache_timestamp = None
self._console_logger = None
@@ -75,8 +79,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._console_logger.propagate = False
def on_after_startup(self):
# refresh cache now if necessary so it's faster once the user connects to the instance
self.get_current_versions()
# refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from
# the server startup
def fetch_data():
self.get_current_versions()
thread = threading.Thread(target=fetch_data)
thread.daemon = True
thread.start()
def _get_configured_checks(self):
with self._configured_checks_mutex:
@@ -115,7 +125,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# This used to be part of the settings migration (version 2) due to a bug - it can't
# stay there though since it interferes with manual entries to the checks not
# originating from within a plugin. Hence we do that step now here.
if "type" not in effective_config or effective_config["type"] != "github_commit":
if "type" not in effective_config or effective_config["type"] not in self.COMMIT_TRACKING_TYPES:
deletables = ["current", "displayVersion"]
else:
deletables = []
@@ -154,6 +164,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
try:
with open(self._version_cache_path) as f:
data = yaml.safe_load(f)
timestamp = os.stat(self._version_cache_path).st_mtime
except:
self._logger.exception("Error while loading version cache from disk")
else:
@@ -176,6 +187,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache = data
self._version_cache_dirty = False
self._version_cache_timestamp = timestamp
self._logger.info("Loaded version cache from disk")
except:
self._logger.exception("Error parsing in version cache data")
@@ -192,6 +204,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
self._version_cache_dirty = False
self._version_cache_timestamp = time.time()
self._logger.info("Saved version cache to disk")
#~~ SettingsPlugin API
@@ -206,9 +219,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
"repo": "OctoPrint",
"update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script),
"restart": "octoprint",
"stable_branch": dict(branch="master", name="Stable"),
"prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"),
dict(branch="rc/devel", name="Devel RCs")]
"stable_branch": dict(branch="master", commitish=["master"], name="Stable"),
"prerelease_branches": [dict(branch="rc/maintenance",
commitish=["rc/maintenance"], # maintenance RCs
name="Maintenance RCs"),
dict(branch="rc/devel",
commitish=["rc/maintenance", "rc/devel"], # devel & maintenance RCs
name="Devel RCs")]
},
},
"pip_command": None,
@@ -385,7 +402,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is not None and "octoprint" in configured_checks:
octoprint_check = dict(configured_checks["octoprint"])
if "type" not in octoprint_check or octoprint_check["type"] != "github_commit":
if "type" not in octoprint_check or octoprint_check["type"] not in self.COMMIT_TRACKING_TYPES:
deletables=["current", "displayName", "displayVersion"]
else:
deletables=[]
@@ -461,7 +478,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
data["check"]["python_updater"] = True
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
information=information))
information=information,
timestamp=self._version_cache_timestamp))
except exceptions.ConfigurationInvalid as e:
return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
@@ -487,6 +505,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
hash.update(str(data["possible"]))
hash.update(",".join(targets))
hash.update(str(self._version_cache_timestamp))
return hash.hexdigest()
def condition():
@@ -834,7 +853,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.load()
# persist the new version if necessary for check type
if check["type"] == "github_commit":
if check["type"] in self.COMMIT_TRACKING_TYPES:
dummy_default = dict(plugins=dict())
dummy_default["plugins"][self._identifier] = dict(checks=dict())
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
@@ -856,7 +875,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._logger.info("Restarting...")
try:
util.execute(restart_command)
util.execute(restart_command, evaluate_returncode=False, async=True)
except exceptions.ScriptError as e:
self._logger.exception("Error while restarting via command {}".format(restart_command))
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
@@ -891,7 +910,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
release_branches += [x["branch"] for x in check["prerelease_branches"]]
result["released_version"] = not release_branches or BRANCH in release_branches
if check["type"] == "github_commit":
if check["type"] in self.COMMIT_TRACKING_TYPES:
result["current"] = REVISION if REVISION else "unknown"
else:
result["current"] = VERSION
@@ -905,8 +924,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
result["force_base"] = False
if check.get("update_script", None):
# if we are using the update_script, we need to set our update_branch and force
# to install the exact version we requested
# if we are using the update_script, we need to set our update_branch
if check.get("prerelease", None):
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
@@ -916,14 +934,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# in case it's not already set
result["update_branch"] = check.get("update_branch", channel)
# we also force our target version in the update
result["force_exact_version"] = True
else:
# we are not tracking prereleases, but aren't on the stable branch either => switch back
# to stable branch on update
result["update_branch"] = check.get("update_branch", stable_branch)
# we also force an exact version
result["force_exact_version"] = True
if BRANCH != result.get("prerelease_channel"):
# we force python unequality check here because that will also allow us to
@@ -945,7 +962,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# displayVersion AND current missing or None
result["displayVersion"] = u"unknown"
if check["type"] in ("github_commit",):
if check["type"] in self.COMMIT_TRACKING_TYPES:
result["current"] = check.get("current", None)
else:
result["current"] = check.get("current", check.get("displayVersion", None))
@@ -977,18 +994,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
raise exceptions.ConfigurationInvalid("no check type defined")
check_type = check["type"]
if check_type == "github_release":
return version_checks.github_release
elif check_type == "github_commit":
return version_checks.github_commit
elif check_type == "git_commit":
return version_checks.git_commit
elif check_type == "commandline":
return version_checks.commandline
elif check_type == "python_checker":
return version_checks.python_checker
else:
method = getattr(version_checks, check_type)
if method is None:
raise exceptions.UnknownCheckType()
else:
return method
def _get_update_method(self, target, check, valid_methods=None):
"""
@@ -1 +1 @@
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -112,6 +112,11 @@ $(function() {
self.octoprintUnconfigured = ko.observable();
self.octoprintUnreleased = ko.observable();
self.cacheTimestamp = ko.observable();
self.cacheTimestampText = ko.pureComputed(function() {
return formatDate(self.cacheTimestamp());
});
self.config_cacheTtl = ko.observable();
self.config_notifyUsers = ko.observable();
self.config_checkoutFolder = ko.observable();
@@ -119,8 +124,9 @@ $(function() {
self.config_updateMethod = ko.observable();
self.config_releaseChannel = ko.observable();
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
self.configurationDialog = undefined;
self.confirmationDialog = undefined;
self._updateClicked = false;
self.config_availableCheckTypes = ko.observableArray([]);
self.config_availableReleaseChannels = ko.observableArray([]);
@@ -199,7 +205,7 @@ $(function() {
self.savePluginSettings = function(viewModel, event) {
var target = $(event.target);
target.prepend('<i class="icon-spinner icon-spin"></i> ');
target.prepend('<i class="fa fa-spinner fa-spin"></i> ');
var data = {
plugins: {
@@ -219,7 +225,7 @@ $(function() {
self.performCheck();
},
complete: function() {
$("i.icon-spinner", target).remove();
$("i.fa-spinner", target).remove();
},
sending: true
});
@@ -257,6 +263,8 @@ $(function() {
};
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
self.cacheTimestamp(data.timestamp);
var versions = [];
_.each(data.information, function(value, key) {
value["key"] = key;
@@ -308,11 +316,11 @@ $(function() {
if (data.status == "updateAvailable" || data.status == "updatePossible") {
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
text += "<ul class='icons-ul'>";
text += "<ul class='fa-ul'>";
_.each(self.versions.items(), function(update_info) {
if (update_info.updateAvailable) {
text += "<li>"
+ "<i class='icon-li " + (update_info.updatePossible ? "icon-ok" : "icon-remove")+ "'></i>"
+ "<i class='fa fa-li " + (update_info.updatePossible ? "fa-check" : "fa-remove")+ "'></i>"
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
+ "</li>";
@@ -320,7 +328,7 @@ $(function() {
});
text += "</ul>";
text += "<p><small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small></p>";
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
if (!self.loginState.isAdmin()) {
text += "<p><small>" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "</small></p>";
@@ -351,7 +359,11 @@ $(function() {
}, {
text: gettext("Update now"),
addClass: "btn-primary",
click: self.update
click: function() {
if (self._updateClicked) return;
self._updateClicked = true;
self.update();
}
}]
};
options["buttons"] = {
@@ -462,7 +474,7 @@ $(function() {
var options = {
title: gettext("Updating..."),
text: gettext("Now updating, please wait."),
icon: "icon-cog icon-spin",
icon: "fa fa-cog fa-spin",
hide: false,
buttons: {
closer: false,
@@ -491,8 +503,19 @@ $(function() {
};
self.update = function(force) {
<<<<<<< HEAD
if (self.updateInProgress) return;
if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) return;
=======
if (self.updateInProgress) {
self._updateClicked = false;
return;
}
if (!self.loginState.isAdmin()) {
self._updateClicked = false;
return;
}
>>>>>>> 2e6d65378f21ffa3f2ea00880188f632bac5e102
if (self.printerState.isPrinting()) {
self._showPopup({
@@ -500,6 +523,7 @@ $(function() {
text: gettext("A print job is currently in progress. Updating will be prevented until it is done."),
type: "error"
});
self._updateClicked = false;
} else {
self.forceUpdate = (force == true);
self.confirmationDialog.modal("show");
@@ -508,9 +532,13 @@ $(function() {
};
self.confirmUpdate = function() {
self.confirmationDialog.modal("hide");
self.performUpdate(self.forceUpdate,
_.map(self.availableAndPossible(), function(info) { return info.key }));
self.confirmationDialog.modal("hide");
};
self.confirmationHidden = function() {
self._updateClicked = false;
};
self._showWorkingDialog = function(title) {
@@ -568,6 +596,10 @@ $(function() {
self.onStartup = function() {
self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog");
self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output");
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
self.confirmationDialog.on("hidden", self.confirmationHidden);
};
self.onServerDisconnect = function() {
@@ -1,6 +1,6 @@
<div class="alert" data-bind="visible: octoprintUnconfigured()">{% trans %}
Please configure the <strong>checkout folder</strong> of OctoPrint, otherwise
this plugin won't be able to update it. Click on the <i class="icon-wrench"></i> button
this plugin won't be able to update it. Click on the <i class="fa fa-wrench"></i> button
to do this. Also refer to the <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
{% endtrans %}</div>
<div class="alert" data-bind="visible: !octoprintUnconfigured() && octoprintUnreleased()">{% trans %}
@@ -17,7 +17,7 @@
{% endtrans %}</div>
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
</div>
<h3>{{ _('Current versions') }}</h3>
@@ -26,10 +26,10 @@
<tbody data-bind="foreach: versions.paginatedItems">
<tr data-bind="attr: {title: displayName}">
<td class="settings_plugin_softwareupdate_column_update">
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="icon-exclamation-sign" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
<small class="muted">
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
@@ -57,13 +57,14 @@
</ul>
</div>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
<div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update now (even if no new versions are available)') }}</button>
</div>
</div>
@@ -107,7 +108,7 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span><br></pre>
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
+2 -2
View File
@@ -9,12 +9,12 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .exceptions import ScriptError
def execute(command, cwd=None, evaluate_returncode=True):
def execute(command, cwd=None, evaluate_returncode=True, async=False):
import sarge
p = None
try:
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture())
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async=async)
except:
returncode = p.returncode if p is not None else None
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
@@ -5,7 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import commandline, git_commit, github_commit, github_release, python_checker
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, python_checker
def log_github_ratelimit(logger, r):
ratelimit = r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
@@ -17,4 +17,4 @@ def log_github_ratelimit(logger, r):
except:
reset = "?"
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
@@ -0,0 +1,52 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__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 requests
import logging
from ..exceptions import ConfigurationInvalid
BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit")
def _get_latest_commit(user, repo, branch):
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch))
if not r.status_code == requests.codes.ok:
return None
reference = r.json()
if not "hash" in reference:
return None
return reference["hash"]
def get_latest(target, check):
if "user" not in check or "repo" not in check:
raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target)
branch = "master"
if "branch" in check:
branch = check["branch"]
current = None
if "current" in check:
current = check["current"]
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
information = dict(
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
)
is_current = (current is not None and current == remote_commit) or remote_commit is None
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
return information, is_current
@@ -15,7 +15,7 @@ BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{br
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
def _get_latest_commit(user, repo, branch):
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch))
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=30)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
@@ -15,7 +15,7 @@ logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.gith
def _filter_out_latest(releases,
sort_key=None,
include_prerelease=False,
prerelease_channel=None):
commitish=None):
"""
Filters out the newest of all matching releases.
@@ -26,31 +26,43 @@ def _filter_out_latest(releases,
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
>>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
>>> _filter_out_latest(releases, include_prerelease=False, prerelease_channel=None)
>>> _filter_out_latest(releases, include_prerelease=False, commitish=None)
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/maintenance")
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"])
('1.2.16rc2', '1.2.16rc2', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/devel")
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"])
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel=None)
>>> _filter_out_latest(releases, include_prerelease=True, commitish=None)
('1.4.0rc1', '1.4.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/doesntexist")
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"])
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest([release_1_2_17rc1])
(None, None, None)
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
(None, None, None)
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, prerelease_channel=None, sort_key=sort_key)
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/maintenance", sort_key=sort_key)
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/devel", sort_key=sort_key)
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key)
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.4.0rc1', '1.4.0rc1', 'some_url')
"""
nothing = None, None, None
@@ -61,9 +73,9 @@ def _filter_out_latest(releases,
# filter out prereleases and drafts
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
if include_prerelease:
if prerelease_channel:
filter_function = lambda rel: not rel["draft"] and (
not rel["prerelease"] or rel["target_commitish"] == prerelease_channel)
if commitish:
filter_function = lambda rel: not rel["draft"] and \
(not rel["prerelease"] or rel["target_commitish"] in commitish)
else:
filter_function = lambda rel: not rel["draft"]
@@ -82,10 +94,10 @@ def _filter_out_latest(releases,
def _get_latest_release(user, repo, compare_type,
include_prerelease=False,
prerelease_channel=None,
commitish=None,
force_base=True):
nothing = None, None, None
r = requests.get(RELEASE_URL.format(user=user, repo=repo))
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
@@ -107,7 +119,7 @@ def _get_latest_release(user, repo, compare_type,
return _filter_out_latest(releases,
sort_key=sort_key,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel)
commitish=commitish)
def _get_sanitized_version(version_string):
@@ -257,6 +269,16 @@ def get_latest(target, check, custom_compare=None):
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
# determine valid "commitish" values in case we track prereleases
commitish = None
if prerelease_channel:
prerelease_branches = check.get("prerelease_branches", None)
if prerelease_branches:
# fetch valid commitish list from configured prerelease_branches for selected channel
commitishes = dict((x["branch"], x.get("commitish", [x["branch"]])) for x in prerelease_branches)
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
force_base = check.get("force_base", True)
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
custom=custom_compare)
@@ -265,7 +287,7 @@ def get_latest(target, check, custom_compare=None):
check["repo"],
compare_type,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel,
commitish=commitish,
force_base=force_base)
information =dict(
@@ -18,6 +18,7 @@ from serial import SerialTimeoutException
from octoprint.settings import settings
from octoprint.plugin import plugin_manager
from octoprint.util import RepeatedTimer
class VirtualPrinter(object):
command_regex = re.compile("^([GMTF])(\d+)")
@@ -113,6 +114,10 @@ class VirtualPrinter(object):
self._okFormatString = settings().get(["devel", "virtualPrinter", "okFormatString"])
self._capabilities = settings().get(["devel", "virtualPrinter", "capabilities"])
self._temperature_reporter = None
self.currentLine = 0
self.lastN = 0
@@ -405,11 +410,26 @@ class VirtualPrinter(object):
output = self._m115FormatString.format(firmware_name=self._firmwareName)
self._send(output)
if settings().getBoolean(["devel", "virtualPrinter", "m115ReportCapabilities"]):
for cap, enabled in self._capabilities.items():
self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0"))
def _gcode_M117(self, data):
# we'll just use this to echo a message, to allow playing around with pause triggers
if self._echoOnM117:
self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1))
def _gcode_M155(self, data):
interval = int(re.search("S([0-9]+)", data).group(1))
if self._temperature_reporter is not None:
self._temperature_reporter.cancel()
if interval > 0:
self._temperature_reporter = RepeatedTimer(interval, lambda: self._send(self._generateTemperatureOutput()))
self._temperature_reporter.start()
else:
self._temperature_reporter = None
def _gcode_M220(self, data):
self._feedrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
@@ -675,9 +695,8 @@ class VirtualPrinter(object):
else:
self._send("Not SD printing")
def _processTemperatureQuery(self):
def _generateTemperatureOutput(self):
includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"])
includeOk = not self._okBeforeCommandOutput
# send simulated temperature data
if self.temperatureCount > 1:
@@ -709,6 +728,11 @@ class VirtualPrinter(object):
output = "T:%.2f B:%.2f" % (self.temp[0], self.bedTemp)
output += " @:64\n"
return output
def _processTemperatureQuery(self):
includeOk = not self._okBeforeCommandOutput
output = self._generateTemperatureOutput()
if includeOk:
output = "{} {}".format(self._ok(), output)
+6 -2
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``
@@ -299,6 +299,7 @@ class PrinterInterface(object):
after the file is selected.
Raises:
InvalidFileType: if the file is not a machinecode file and hence cannot be printed
InvalidFileLocation: if an absolute path was provided and not contained within local storage or
doesn't exist
"""
@@ -366,7 +367,7 @@ class PrinterInterface(object):
* CLOSED
* ERROR
* CLOSED_WITH_ERROR
* TRANFERING_FILE
* TRANSFERING_FILE
* OFFLINE
* UNKNOWN
* NONE
@@ -593,3 +594,6 @@ class UnknownScript(Exception):
class InvalidFileLocation(Exception):
pass
class InvalidFileType(Exception):
pass
+32 -4
View File
@@ -215,25 +215,42 @@ class PrinterProfileManager(object):
if self.exists("_default"):
return
if not isinstance(default_overrides, dict):
self._logger.warn("Existing default profile from settings is not a valid profile, refusing to migrate: {!r}".format(default_overrides))
return
default_overrides["id"] = "_default"
self.save(default_overrides)
settings().set(["printerProfiles", "defaultProfile"], None)
settings().save()
self._logger.info("Migrated default printer profile from settings to _default.profile: {!r}".format(default_overrides))
def _verify_default_available(self):
default_id = settings().get(["printerProfile", "default"])
default_id = settings().get(["printerProfiles", "default"])
if default_id is None:
default_id = "_default"
if not self.exists(default_id):
if not self.exists("_default"):
self._logger.error("Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(default_id))
if default_id == "_default":
self._logger.error("Profile _default does not exist, creating _default again and setting it as default")
else:
self._logger.error("Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(default_id))
self.save(self.__class__.default, allow_overwrite=True, make_default=True)
else:
self._logger.error("Selected default profile {} does not exists, resetting to _default".format(default_id))
settings().set(["printerProfiles", "default"], "_default")
settings().save()
default_id = "_default"
profile = self.get(default_id)
if profile is None:
self._logger.error("Selected default profile {} is invalid, resetting to default values".format(default_id))
profile = copy.deepcopy(self.__class__.default)
profile["id"] = default_id
self.save(self.__class__.default, allow_overwrite=True, make_default=True)
def select(self, identifier):
if identifier is None or not self.exists(identifier):
@@ -241,7 +258,12 @@ class PrinterProfileManager(object):
return False
else:
self._current = self.get(identifier)
return True
if self._current is None:
self._logger.error("Profile {} is invalid, cannot select, falling back to default".format(identifier))
self._current = self.get_default()
return False
else:
return True
def deselect(self):
self._current = None
@@ -310,6 +332,8 @@ class PrinterProfileManager(object):
profile = self.get(default)
if profile is not None:
return profile
else:
self._logger.warn("Default profile {} is invalid, falling back to built-in defaults".format(default))
return copy.deepcopy(self.__class__.default)
@@ -318,7 +342,7 @@ class PrinterProfileManager(object):
if identifier is not None and not identifier in all_identifiers:
return
settings().set(["printerProfile", "default"], identifier)
settings().set(["printerProfiles", "default"], identifier)
settings().save()
def get_current_or_default(self):
@@ -344,6 +368,7 @@ class PrinterProfileManager(object):
try:
profile = self._load_from_path(path)
except InvalidProfileError:
self._logger.warn("Profile {} is invalid, skipping".format(identifier))
continue
if profile is None:
@@ -373,6 +398,9 @@ class PrinterProfileManager(object):
with open(path) as f:
profile = yaml.safe_load(f)
if profile is None or not isinstance(profile, dict):
raise InvalidProfileError("Profile is None or not a dictionary")
if self._migrate_profile(profile):
try:
self._save_to_path(path, profile, allow_overwrite=True)
+28 -15
View File
@@ -15,11 +15,13 @@ import os
import threading
import time
from past.builtins import basestring
from octoprint import util as util
from octoprint.events import eventManager, Events
from octoprint.filemanager import FileDestinations, NoSuchStorage
from octoprint.filemanager import FileDestinations, NoSuchStorage, valid_file_type
from octoprint.plugin import plugin_manager, ProgressPlugin
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation, InvalidFileType
from octoprint.printer.estimation import TimeEstimationHelper
from octoprint.settings import settings
from octoprint.util import comm as comm
@@ -331,14 +333,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if heater.startswith("tool"):
printer_profile = self._printerProfileManager.get_current_or_default()
extruder_count = printer_profile["extruder"]["count"]
if extruder_count > 1:
shared_nozzle = printer_profile["extruder"]["sharedNozzle"]
if extruder_count > 1 and not shared_nozzle:
toolNum = int(heater[len("tool"):])
self.commands("M104 T%d S%f" % (toolNum, value))
self.commands("M104 T{} S{}".format(toolNum, value))
else:
self.commands("M104 S%f" % value)
self.commands("M104 S{}".format(value))
elif heater == "bed":
self.commands("M140 S%f" % value)
self.commands("M140 S{}".format(value))
def set_temperature_offset(self, offsets=None):
if offsets is None:
@@ -369,7 +372,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
factor = int(factor * 100.0)
if factor < min or factor > max:
raise ValueError("factor must be a value between %f and %f" % (min, max))
raise ValueError("factor must be a value between {} and {}".format(min, max))
return factor
@@ -845,6 +848,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.add_temperature(data)
def _validateJob(self, filename, sd):
if not valid_file_type(filename, type="machinecode"):
raise InvalidFileType("{} is not a machinecode file, cannot print".format(filename))
if sd:
return
@@ -1069,13 +1075,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
must_be_set=False)
def on_comm_print_job_done(self):
self._updateProgressData()
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
self._fileManager.delete_recovery_data()
payload = self._payload_for_print_job_event()
if payload:
payload["time"] = self._comm.getPrintTime()
self._updateProgressData(completion=1.0,
filepos=payload["size"],
printTime=payload["time"],
printTimeLeft=0)
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
eventManager().fire(Events.PRINT_DONE, payload)
self.script("afterPrintDone",
context=dict(event=payload),
@@ -1087,6 +1097,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload["time"],
True,
self._printerProfileManager.get_current_or_default()["id"])
else:
self._updateProgressData()
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
def on_comm_print_job_failed(self):
payload = self._payload_for_print_job_event()
@@ -1133,7 +1147,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._sdStreaming = True
self._setJobData(filename, filesize, True)
self._updateProgressData()
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
def on_comm_file_transfer_done(self, filename):
@@ -1160,7 +1174,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
except:
self._logger.exception("Error while trying to persist print recovery data")
def _payload_for_print_job_event(self, location=None, print_job_file=None, position=None):
def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, position=None):
if print_job_file is None:
with self._selectedFileMutex:
selected_file = self._selectedFile
@@ -1168,6 +1182,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return dict()
print_job_file = selected_file.get("filename", None)
print_job_size = selected_file.get("filesize", None)
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
if not print_job_file or not location:
@@ -1189,6 +1204,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
result= dict(name=name,
path=path,
origin=origin,
size=print_job_size,
# TODO deprecated, remove in 1.4.0
file=full_path,
@@ -1211,15 +1227,12 @@ class StateMonitor(object):
self._state = None
self._job_data = None
self._gcode_data = None
self._sd_upload_data = None
self._current_z = None
self._offsets = {}
self._progress = None
self._progress_dirty = False
self._offsets = {}
self._change_event = threading.Event()
self._state_lock = threading.Lock()
self._progress_lock = threading.Lock()
+80 -79
View File
@@ -16,7 +16,9 @@ from babel import Locale
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
from collections import defaultdict
from builtins import bytes, range
from past.builtins import basestring
from octoprint import util
@@ -268,7 +270,7 @@ class Server(object):
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError as e:
except:
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
userManager = octoprint.access.users.FilebasedUserManager()
finally:
@@ -391,7 +393,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()
@@ -406,7 +408,8 @@ class Server(object):
ioloop = IOLoop()
ioloop.install()
self._router = SockJSRouter(self._create_socket_connection, "/sockjs")
self._router = SockJSRouter(self._create_socket_connection, "/sockjs",
session_kls=util.sockjs.ThreadSafeSession)
upload_suffixes = dict(name=self._settings.get(["server", "uploads", "nameSuffix"]), path=self._settings.get(["server", "uploads", "pathSuffix"]))
@@ -490,9 +493,22 @@ class Server(object):
self._logger.debug("Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format(**locals()))
server_routes.append((route, handler, kwargs))
server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes)))
headers = {"X-Robots-Tag": "noindex, nofollow, noimageindex"}
removed_headers = ["Server"]
self._tornado_app = Application(server_routes)
server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app,
headers=headers,
removed_headers=removed_headers),
file_prefix="octoprint-file-upload-",
file_suffix=".tmp",
suffixes=upload_suffixes)))
transforms = [util.tornado.GlobalHeaderTransform.for_headers("OctoPrintGlobalHeaderTransform",
headers=headers,
removed_headers=removed_headers)]
self._tornado_app = Application(handlers=server_routes,
transforms=transforms)
max_body_sizes = [
("POST", r"/api/files/([^/]*)", self._settings.getInt(["server", "uploads", "maxSize"])),
("POST", r"/api/languages", 5 * 1024 * 1024)
@@ -530,11 +546,14 @@ class Server(object):
# auto connect
if self._settings.getBoolean(["serial", "autoconnect"]):
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
connectionOptions = printer.__class__.get_connection_options()
if port in connectionOptions["ports"]:
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
try:
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
connectionOptions = printer.__class__.get_connection_options()
if port in connectionOptions["ports"]:
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
except:
self._logger.exception("Something went wrong while attempting to automatically connect to the printer")
# start up watchdogs
if self._settings.getBoolean(["feature", "pollWatched"]):
@@ -605,7 +624,7 @@ class Server(object):
"on_shutdown",
sorting_context="ShutdownPlugin.on_shutdown")
# wait for shutdown even to be processed, but maximally for 15s
# wait for shutdown event to be processed, but maximally for 15s
event_timeout = 15.0
if eventManager.join(timeout=event_timeout):
self._logger.warn("Event loop was still busy processing after {}s, shutting down anyhow".format(event_timeout))
@@ -620,13 +639,16 @@ class Server(object):
def sigterm_handler(*args, **kwargs):
# will stop tornado on SIGTERM, making the program exit cleanly
def shutdown_tornado():
self._logger.debug("Shutting down tornado's IOLoop...")
ioloop.stop()
self._logger.debug("SIGTERM received...")
ioloop.add_callback_from_signal(shutdown_tornado)
signal.signal(signal.SIGTERM, sigterm_handler)
try:
# this is the main loop - as long as tornado is running, OctoPrint is running
ioloop.start()
self._logger.debug("Tornado's IOLoop stopped")
except (KeyboardInterrupt, SystemExit):
pass
except:
@@ -852,6 +874,8 @@ class Server(object):
return
def execute_caching():
logger = logging.getLogger(__name__ + ".preemptive_cache")
for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)):
entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0)))
for kwargs in entries:
@@ -860,18 +884,18 @@ class Server(object):
try:
plugin_info = pluginManager.get_plugin_info(plugin, require_enabled=True)
if plugin_info is None:
self._logger.info("About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format(plugin))
logger.info("About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format(plugin))
continue
implementation = plugin_info.implementation
if implementation is None or not isinstance(implementation, octoprint.plugin.UiPlugin):
self._logger.info("About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format(plugin))
logger.info("About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format(plugin))
continue
if not implementation.get_ui_preemptive_caching_enabled():
self._logger.info("About to preemptively cache plugin {} but it has disabled preemptive caching".format(plugin))
logger.info("About to preemptively cache plugin {} but it has disabled preemptive caching".format(plugin))
continue
except:
self._logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry")
logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry")
continue
additional_request_data = kwargs.get("_additional_request_data", dict())
@@ -879,10 +903,11 @@ class Server(object):
kwargs.update(additional_request_data)
try:
start = time.time()
if plugin:
self._logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs))
logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs))
else:
self._logger.info("Preemptively caching {} (ui _default) for {!r}".format(route, kwargs))
logger.info("Preemptively caching {} (ui _default) for {!r}".format(route, kwargs))
headers = kwargs.get("headers", dict())
headers["X-Force-View"] = plugin if plugin else "_default"
@@ -891,8 +916,10 @@ class Server(object):
builder = EnvironBuilder(**kwargs)
app(builder.get_environ(), lambda *a, **kw: None)
logger.info("... done in {:.2f}s".format(time.time() - start))
except:
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
# asynchronous caching
import threading
@@ -1073,7 +1100,6 @@ class Server(object):
enable_gcodeviewer = self._settings.getBoolean(["gcodeViewer", "enabled"])
preferred_stylesheet = self._settings.get(["devel", "stylesheet"])
minify = self._settings.getBoolean(["devel", "webassets", "minify"])
dynamic_core_assets = util.flask.collect_core_assets(enable_gcodeviewer=enable_gcodeviewer)
dynamic_plugin_assets = util.flask.collect_plugin_assets(
@@ -1082,7 +1108,7 @@ class Server(object):
)
js_libs = [
"js/lib/jquery/jquery.min.js" if minify else "js/lib/jquery/jquery.js",
"js/lib/jquery/jquery.js",
"js/lib/modernizr.custom.js",
"js/lib/lodash.min.js",
"js/lib/sprintf.min.js",
@@ -1099,6 +1125,9 @@ class Server(object):
"js/lib/jquery/jquery.ui.widget.js",
"js/lib/jquery/jquery.ui.mouse.js",
"js/lib/jquery/jquery.flot.js",
"js/lib/jquery/jquery.flot.time.js",
"js/lib/jquery/jquery.flot.crosshair.js",
"js/lib/jquery/jquery.flot.resize.js",
"js/lib/jquery/jquery.iframe-transport.js",
"js/lib/jquery/jquery.fileupload.js",
"js/lib/jquery/jquery.slimscroll.min.js",
@@ -1120,7 +1149,7 @@ class Server(object):
"js/lib/md5.min.js",
"js/lib/bootstrap-slider-knockout-binding.js",
"js/lib/loglevel.min.js",
"js/lib/sockjs.min.js" if minify else "js/lib/sockjs.js"
"js/lib/sockjs.js"
]
js_client = [
"js/app/client/base.js",
@@ -1149,14 +1178,14 @@ class Server(object):
"js/app/helpers.js",
"js/app/main.js"]
js_plugins = dynamic_plugin_assets["external"]["js"]
js_app = js_plugins + js_core
css_libs = [
"css/bootstrap.min.css",
"css/bootstrap-modal.css",
"css/bootstrap-slider.css",
"css/bootstrap-tabdrop.css",
"css/font-awesome.min.css",
"vendor/font-awesome-3.2.1/css/font-awesome.min.css",
"vendor/font-awesome-4.7.0/css/font-awesome.min.css",
"css/jquery.fileupload-ui.css",
"css/pnotify.core.min.css",
"css/pnotify.buttons.min.css",
@@ -1164,93 +1193,65 @@ class Server(object):
]
css_core = list(dynamic_core_assets["css"]) + list(dynamic_plugin_assets["bundled"]["css"])
css_plugins = list(dynamic_plugin_assets["external"]["css"])
css_app = css_core + css_plugins
less_core = list(dynamic_core_assets["less"]) + list(dynamic_plugin_assets["bundled"]["less"])
less_plugins = list(dynamic_plugin_assets["external"]["less"])
less_app = less_core + less_plugins
from webassets.filter import register_filter, Filter
from webassets.filter.cssrewrite.base import PatternRewriter
import re
class LessImportRewrite(PatternRewriter):
name = "less_importrewrite"
patterns = {
"import_rewrite": re.compile("(@import(\s+\(.*\))?\s+)\"(.*)\";")
}
def import_rewrite(self, m):
import_with_options = m.group(1)
import_url = m.group(3)
if not import_url.startswith("http:") and not import_url.startswith("https:") and not import_url.startswith("/"):
import_url = "../less/" + import_url
return "{import_with_options}\"{import_url}\";".format(**locals())
class JsDelimiterBundler(Filter):
name = "js_delimiter_bundler"
options = {}
def input(self, _in, out, **kwargs):
out.write(_in.read())
out.write("\n;\n")
# a couple of custom filters
from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, SourceMapRewrite, SourceMapRemove
from webassets.filter import register_filter
register_filter(LessImportRewrite)
register_filter(SourceMapRewrite)
register_filter(SourceMapRemove)
register_filter(JsDelimiterBundler)
# JS
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
if minify:
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="rjsmin, js_delimiter_bundler")
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="rjsmin, js_delimiter_bundler")
if len(js_plugins) == 0:
js_plugins_bundle = Bundle(*[])
else:
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="rjsmin, js_delimiter_bundler")
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler")
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters))
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters=",".join(js_filters))
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters=",".join(js_filters))
if len(js_plugins) == 0:
js_plugins_bundle = Bundle(*[])
else:
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="js_delimiter_bundler")
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="js_delimiter_bundler")
if len(js_plugins) == 0:
js_plugins_bundle = Bundle(*[])
else:
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="js_delimiter_bundler")
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler")
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters=",".join(js_filters))
js_app_bundle = Bundle(js_plugins_bundle, js_core_bundle, output="webassets/packed_app.js", filters=",".join(js_filters))
# CSS
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
css_filters = ["cssrewrite"]
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css", filters=",".join(css_filters))
if len(css_core) == 0:
css_core_bundle = Bundle(*[])
else:
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters="cssrewrite")
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters=",".join(css_filters))
if len(css_plugins) == 0:
css_plugins_bundle = Bundle(*[])
else:
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters="cssrewrite")
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters=",".join(css_filters))
if len(css_app) == 0:
css_app_bundle = Bundle(*[])
else:
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css", filters="cssrewrite")
css_app_bundle = Bundle(css_core, css_plugins, output="webassets/packed_app.css", filters=",".join(css_filters))
# LESS
less_filters = ["cssrewrite", "less_importrewrite"]
if len(less_core) == 0:
less_core_bundle = Bundle(*[])
else:
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters="cssrewrite, less_importrewrite")
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters=",".join(less_filters))
if len(less_plugins) == 0:
less_plugins_bundle = Bundle(*[])
else:
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters="cssrewrite, less_importrewrite")
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters=",".join(less_filters))
if len(less_app) == 0:
less_app_bundle = Bundle(*[])
else:
less_app_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
less_app_bundle = Bundle(less_core, less_plugins, output="webassets/packed_app.less", filters=",".join(less_filters))
# asset registration
assets.register("js_libs", js_libs_bundle)
+1 -1
View File
@@ -209,7 +209,7 @@ def login():
if octoprint.server.userManager.checkPassword(username, password):
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.login_user(user)
session["usersession.id"] = user.get_session()
session["usersession.id"] = user.session
g.user = user
login_user(user, remember=remember)
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
+2 -2
View File
@@ -80,8 +80,8 @@ def _get_options():
default_profile = printerProfileManager.get_default()
options = dict(
ports=connection_options["ports"],
baudrates=connection_options["baudrates"],
ports=sorted(connection_options["ports"]),
baudrates=sorted(connection_options["baudrates"], reverse=True),
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
portPreference=connection_options["portPreference"],
baudratePreference=connection_options["baudratePreference"],
+2 -1
View File
@@ -11,6 +11,8 @@ import copy
from flask import jsonify, make_response, request, url_for
from werkzeug.exceptions import BadRequest
from past.builtins import basestring
from octoprint.server.api import api, NO_CONTENT, valid_boolean_trues
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
from octoprint.util import dict_merge
@@ -19,7 +21,6 @@ from octoprint.server import printerProfileManager
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError
from octoprint.access.permissions import Permissions
def _lastmodified():
return printerProfileManager.last_modified
+20 -2
View File
@@ -99,6 +99,8 @@ def getSettings():
},
"webcam": {
"streamUrl": s.get(["webcam", "stream"]),
"streamRatio": s.get(["webcam", "streamRatio"]),
"streamTimeout": s.getInt(["webcam", "streamTimeout"]),
"snapshotUrl": s.get(["webcam", "snapshot"]),
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
"bitrate": s.get(["webcam", "bitrate"]),
@@ -128,7 +130,8 @@ def getSettings():
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
"firmwareDetection": s.getBoolean(["feature", "firmwareDetection"]),
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]),
"blockWhileDwelling": s.getBoolean(["feature", "blockWhileDwelling"])
"blockWhileDwelling": s.getBoolean(["feature", "blockWhileDwelling"]),
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -141,6 +144,7 @@ def getSettings():
"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
"timeoutTemperatureTargetSet": s.getFloat(["serial", "timeout", "temperatureTargetSet"]),
"timeoutTemperatureAutoreport": s.getFloat(["serial", "timeout", "temperatureAutoreport"]),
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
"log": s.getBoolean(["serial", "log"]),
"additionalPorts": s.get(["serial", "additionalPorts"]),
@@ -165,7 +169,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"]),
@@ -181,6 +187,8 @@ def getSettings():
"afterPrintDone": None,
"beforePrintPaused": None,
"afterPrintResumed": None,
"beforeToolChange": None,
"afterToolChange": None,
"snippets": dict()
}
},
@@ -259,6 +267,10 @@ def setSettings():
if data is None:
return make_response("Malformed JSON body in request", 400)
if not isinstance(data, dict):
return make_response("Malformed request, need settings dictionary, "
"got a {} instead: {!r}".format(type(data).__name__, data), 400)
_saveSettings(data)
return getSettings()
@@ -303,6 +315,8 @@ def _saveSettings(data):
if "webcam" in data.keys():
if "streamUrl" in data["webcam"]: s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "streamRatio" in data["webcam"] and data["webcam"]["streamRatio"] in ("16:9", "4:3"): s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"])
if "streamTimeout" in data["webcam"]: s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"])
if "snapshotUrl" in data["webcam"]: s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
if "ffmpegPath" in data["webcam"]: s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
if "bitrate" in data["webcam"]: s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
@@ -333,6 +347,7 @@ def _saveSettings(data):
if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"])
if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"])
if "blockWhileDwelling" in data["feature"]: s.setBoolean(["feature", "blockWhileDwelling"], data["feature"]["blockWhileDwelling"])
if "g90InfluencesExtruder" in data["feature"]: s.setBoolean(["feature", "g90InfluencesExtruder"], data["feature"]["g90InfluencesExtruder"])
if "serial" in data.keys():
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
@@ -343,6 +358,7 @@ def _saveSettings(data):
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"])
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
@@ -378,6 +394,8 @@ def _saveSettings(data):
if "temperature" in data.keys():
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "cutoff" in data["temperature"]: s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
if "sendAutomatically" in data["temperature"]: s.setBoolean(["temperature", "sendAutomatically"], data["temperature"]["sendAutomatically"])
if "sendAutomaticallyAfter" in data["temperature"]: s.setInt(["temperature", "sendAutomaticallyAfter"], data["temperature"]["sendAutomaticallyAfter"], min=0, max=30)
if "terminalFilters" in data.keys():
s.set(["terminalFilters"], data["terminalFilters"])
+7 -1
View File
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import threading
import logging
from flask import request, jsonify, url_for, make_response
@@ -131,7 +132,12 @@ def deleteTimelapse(filename):
timelapse_folder = settings().getBaseFolder("timelapse")
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
os.remove(full_path)
try:
os.remove(full_path)
except Exception as ex:
logging.getLogger(__file__).exception("Error deleting timelapse file {}".format(full_path))
return make_response("Unexpected error: {}".format(ex), 500)
return getTimelapseData()
+5 -3
View File
@@ -30,6 +30,8 @@ import octoprint.plugin
from werkzeug.contrib.cache import BaseCache
from past.builtins import basestring
try:
from os import scandir, walk
except ImportError:
@@ -507,8 +509,8 @@ def passive_login():
if user is not None and not user.is_anonymous:
flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id()))
if hasattr(user, "get_session"):
flask.session["usersession.id"] = user.get_session()
if hasattr(user, "session"):
flask.session["usersession.id"] = user.session
flask.g.user = user
return flask.jsonify(user)
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
@@ -526,7 +528,7 @@ def passive_login():
user = octoprint.server.userManager.findUser(autologinAs)
if user is not None:
user = octoprint.server.userManager.login_user(user)
flask.session["usersession.id"] = user.get_session()
flask.session["usersession.id"] = user.session
flask.g.user = user
flask_login.login_user(user)
+36 -10
View File
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import threading
import sockjs.tornado
import sockjs.tornado.session
import time
import octoprint.timelapse
@@ -21,6 +22,34 @@ from octoprint.settings import settings
import octoprint.printer
class ThreadSafeSession(sockjs.tornado.session.Session):
def __init__(self, conn, server, session_id, expiry=None):
sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry)
def set_handler(self, handler, start_heartbeat=True):
if getattr(handler, "__orig_send_pack", None) is None:
orig_send_pack = handler.send_pack
mutex = threading.RLock()
def send_pack(*args, **kwargs):
with mutex:
return orig_send_pack(*args, **kwargs)
handler.send_pack = send_pack
setattr(handler, "__orig_send_pack", orig_send_pack)
return sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat)
def remove_handler(self, handler):
result = sockjs.tornado.session.Session.remove_handler(self, handler)
if getattr(handler, "__orig_send_pack", None) is not None:
handler.send_pack = getattr(handler, "__orig_send_pack")
delattr(handler, "__orig_send_pack")
return result
class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
sockjs.tornado.SockJSConnection.__init__(self, session)
@@ -47,8 +76,6 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self._lastCurrent = 0
self._baseRateLimit = 0.5
self._emit_mutex = threading.RLock()
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
if forwardedFor is not None:
@@ -205,11 +232,10 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self.sendEvent(event, payload)
def _emit(self, type, payload):
with self._emit_mutex:
try:
self.send({type: payload})
except Exception as e:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
else:
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
try:
self.send({type: payload})
except Exception as e:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
else:
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
+53 -3
View File
@@ -497,9 +497,20 @@ class WsgiInputContainer(object):
methods have been adjusted to allow for an optionally supplied ``body`` argument which is then used for ``wsgi.input``.
"""
def __init__(self, wsgi_application):
def __init__(self, wsgi_application, headers=None, forced_headers=None, removed_headers=None):
self.wsgi_application = wsgi_application
if headers is None:
headers = dict()
if forced_headers is None:
forced_headers = dict()
if removed_headers is None:
removed_headers = []
self.headers = headers
self.forced_headers = forced_headers
self.removed_headers = removed_headers
def __call__(self, request, body=None):
"""
Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado ``HTTPServerRequest``.
@@ -536,8 +547,14 @@ class WsgiInputContainer(object):
headers.append(("Content-Length", str(len(body))))
if "content-type" not in header_set:
headers.append(("Content-Type", "text/html; charset=UTF-8"))
if "server" not in header_set:
headers.append(("Server", "TornadoServer/%s" % tornado.version))
header_set = set(k.lower() for (k, v) in headers)
for header, value in self.headers.items():
if header.lower() not in header_set:
headers.append((header, value))
for header, value in self.forced_headers.items():
headers.append((header, value))
headers = [(header, value) for header, value in headers if not header.lower() in self.removed_headers]
start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
header_obj = tornado.httputil.HTTPHeaders()
@@ -1000,6 +1017,39 @@ class StaticDataHandler(tornado.web.RequestHandler):
self.finish()
class GlobalHeaderTransform(tornado.web.OutputTransform):
HEADERS = dict()
FORCED_HEADERS = dict()
REMOVED_HEADERS = []
@classmethod
def for_headers(cls, name, headers=None, forced_headers=None, removed_headers=None):
if headers is None:
headers = dict()
if forced_headers is None:
forced_headers = dict()
if removed_headers is None:
removed_headers = []
return type(name, (GlobalHeaderTransform,), dict(HEADERS=headers,
FORCED_HEADERS=forced_headers,
REMOVED_HEADERS=removed_headers))
def __init__(self, request):
tornado.web.OutputTransform.__init__(self, request)
def transform_first_chunk(self, status_code, headers, chunk, finishing):
for header, value in self.HEADERS.items():
if not header in headers:
headers[header] = value
for header, value in self.FORCED_HEADERS.items():
headers[header] = value
for header in self.REMOVED_HEADERS:
del headers[header]
return status_code, headers, chunk
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
+100
View File
@@ -0,0 +1,100 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__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 re
try:
from urllib import parse as urlparse
except:
import urlparse
from webassets.filter import Filter
from webassets.filter.cssrewrite.base import PatternRewriter
import webassets.filter.cssrewrite.urlpath as urlpath
def replace_url(source_url, output_url, url):
# If path is an absolute one, keep it
parsed = urlparse.urlparse(url)
if not parsed.scheme and not parsed.path.startswith('/'):
abs_source_url = urlparse.urljoin(source_url, url)
# relpath() will not detect this case
if urlparse.urlparse(abs_source_url).scheme:
return abs_source_url
# rewritten url: relative path from new location (output)
# to location of referenced file (source + current url)
url = urlpath.relpath(output_url, abs_source_url)
return url
class UrlRewriter(PatternRewriter):
def input(self, _in, out, **kw):
source, source_path, output, output_path = \
kw['source'], kw['source_path'], kw['output'], kw['output_path']
self.source_path = source_path
self.output_path = output_path
self.source_url = self.ctx.resolver.resolve_source_to_url(
self.ctx, source_path, source)
self.output_url = self.ctx.resolver.resolve_output_to_url(
self.ctx, output)
return super(UrlRewriter, self).input(_in, out, **kw)
def replace_url(self, url):
return replace_url(self.source_url, self.output_url, url)
class LessImportRewrite(UrlRewriter):
name = "less_importrewrite"
patterns = {
"import_rewrite": re.compile("(@import(\s+\(.*\))?\s+)\"(.*)\";")
}
def import_rewrite(self, m):
import_with_options = m.group(1)
import_url = self.replace_url(m.group(3))
return "{import_with_options}\"{import_url}\";".format(**locals())
class SourceMapRewrite(UrlRewriter):
name = "sourcemap_urlrewrite"
patterns = {
"url_rewrite": re.compile("(//#\s+sourceMappingURL=)(.*)")
}
def url_rewrite(self, m):
mapping = m.group(1)
source_url = self.replace_url(m.group(2))
return "{mapping}{source_url}".format(**locals())
class SourceMapRemove(PatternRewriter):
name = "sourcemap_remove"
patterns = {
"sourcemap_remove": re.compile("(//#\s+sourceMappingURL=)(.*)")
}
def sourcemap_remove(self, m):
return ""
class JsDelimiterBundler(Filter):
name = "js_delimiter_bundler"
options = {}
def input(self, _in, out, **kwargs):
out.write(_in.read())
out.write("\n;\n")
+6 -8
View File
@@ -9,6 +9,8 @@ import os
import datetime
import codecs
from past.builtins import basestring
from collections import defaultdict
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
@@ -518,14 +520,10 @@ def _process_templates():
# sidebar
templates["sidebar"]["entries"]= dict(
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.CONNECTION)")),
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign", data_bind="visible: loginState.hasPermission(access.permissions.STATUS)")),
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2", data_bind="visible: loginState.hasPermission(access.permissions.DOWNLOAD)() || \
loginState.hasPermission(access.permissions.UPLOAD)() || \
loginState.hasPermission(access.permissions.DELETE)() || \
loginState.hasPermission(access.permissions.SELECT)() || \
loginState.hasPermission(access.permissions.PRINT)() || \
loginState.hasPermission(access.permissions.SLICE)()"))
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], permission_test="access.permissions.CONNECTION")),
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-circle", permission_test="access.permissions.STATUS")),
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2",
permission_test="access.permissions.DOWNLOAD, access.permissions.UPLOAD, access.permissions.DELETE, access.permissions.SELECT, access.permissions.PRINT, access.permissions.SLICE]"))
)
# tabs
+58 -9
View File
@@ -34,6 +34,7 @@ import copy
import time
from builtins import bytes
from past.builtins import basestring
try:
from collections import ChainMap
@@ -93,6 +94,7 @@ default_settings = {
"communication": 30,
"temperature": 5,
"temperatureTargetSet": 2,
"temperatureAutoreport": 2,
"sdStatus": 1
},
"maxCommunicationTimeouts": {
@@ -155,6 +157,8 @@ default_settings = {
},
"webcam": {
"stream": None,
"streamRatio": "16:9",
"streamTimeout": 5,
"snapshot": None,
"ffmpeg": None,
"ffmpegThreads": 1,
@@ -204,7 +208,8 @@ default_settings = {
"modelSizeDetection": True,
"firmwareDetection": True,
"printCancelConfirmation": True,
"blockWhileDwelling": False
"blockWhileDwelling": False,
"g90InfluencesExtruder": False
},
"folder": {
"uploads": None,
@@ -226,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
@@ -298,7 +305,7 @@ default_settings = {
"apps": {}
},
"terminalFilters": [
{ "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)" },
{ "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?(B|T\d*):)" },
{ "name": "Suppress SD status messages", "regex": "(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)" },
{ "name": "Suppress wait responses", "regex": "Recv: wait"}
],
@@ -330,7 +337,6 @@ default_settings = {
"preemptive": True
},
"webassets": {
"minify": False,
"bundle": True,
"clean_on_startup": True
},
@@ -364,7 +370,11 @@ default_settings = {
"simulateReset": True,
"preparedOks": [],
"okFormatString": "ok",
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0"
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0",
"m115ReportCapabilities": False,
"capabilities": {
"AUTOREPORT_TEMP": True
}
}
}
}
@@ -1270,23 +1280,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
@@ -1314,11 +1344,14 @@ class Settings(object):
if folder is None:
folder = self._get_default_folder(type)
if not os.path.isdir(folder):
if not os.path.exists(folder):
if create:
os.makedirs(folder)
else:
raise IOError("No such folder: {folder}".format(folder=folder))
raise IOError("No such folder: {}".format(folder))
elif os.path.isfile(folder):
# hardening against misconfiguration, see #1953
raise IOError("Expected a folder at {} but found a file instead".format(folder))
return folder
@@ -1439,8 +1472,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
@@ -1452,8 +1493,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
-403
View File
@@ -1,403 +0,0 @@
@font-face{font-family:'FontAwesome';src:url('../font/fontawesome-webfont.eot?v=3.2.1');src:url('../font/fontawesome-webfont.eot?#iefix&v=3.2.1') format('embedded-opentype'),url('../font/fontawesome-webfont.woff?v=3.2.1') format('woff'),url('../font/fontawesome-webfont.ttf?v=3.2.1') format('truetype'),url('../font/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1') format('svg');font-weight:normal;font-style:normal;}[class^="icon-"],[class*=" icon-"]{font-family:FontAwesome;font-weight:normal;font-style:normal;text-decoration:inherit;-webkit-font-smoothing:antialiased;*margin-right:.3em;}
[class^="icon-"]:before,[class*=" icon-"]:before{text-decoration:inherit;display:inline-block;speak:none;}
.icon-large:before{vertical-align:-10%;font-size:1.3333333333333333em;}
a [class^="icon-"],a [class*=" icon-"]{display:inline;}
[class^="icon-"].icon-fixed-width,[class*=" icon-"].icon-fixed-width{display:inline-block;width:1.1428571428571428em;text-align:right;padding-right:0.2857142857142857em;}[class^="icon-"].icon-fixed-width.icon-large,[class*=" icon-"].icon-fixed-width.icon-large{width:1.4285714285714286em;}
.icons-ul{margin-left:2.142857142857143em;list-style-type:none;}.icons-ul>li{position:relative;}
.icons-ul .icon-li{position:absolute;left:-2.142857142857143em;width:2.142857142857143em;text-align:center;line-height:inherit;}
[class^="icon-"].hide,[class*=" icon-"].hide{display:none;}
.icon-muted{color:#eeeeee;}
.icon-light{color:#ffffff;}
.icon-dark{color:#333333;}
.icon-border{border:solid 1px #eeeeee;padding:.2em .25em .15em;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
.icon-2x{font-size:2em;}.icon-2x.icon-border{border-width:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
.icon-3x{font-size:3em;}.icon-3x.icon-border{border-width:3px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;}
.icon-4x{font-size:4em;}.icon-4x.icon-border{border-width:4px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}
.icon-5x{font-size:5em;}.icon-5x.icon-border{border-width:5px;-webkit-border-radius:7px;-moz-border-radius:7px;border-radius:7px;}
.pull-right{float:right;}
.pull-left{float:left;}
[class^="icon-"].pull-left,[class*=" icon-"].pull-left{margin-right:.3em;}
[class^="icon-"].pull-right,[class*=" icon-"].pull-right{margin-left:.3em;}
[class^="icon-"],[class*=" icon-"]{display:inline;width:auto;height:auto;line-height:normal;vertical-align:baseline;background-image:none;background-position:0% 0%;background-repeat:repeat;margin-top:0;}
.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"]{background-image:none;}
.btn [class^="icon-"].icon-large,.nav [class^="icon-"].icon-large,.btn [class*=" icon-"].icon-large,.nav [class*=" icon-"].icon-large{line-height:.9em;}
.btn [class^="icon-"].icon-spin,.nav [class^="icon-"].icon-spin,.btn [class*=" icon-"].icon-spin,.nav [class*=" icon-"].icon-spin{display:inline-block;}
.nav-tabs [class^="icon-"],.nav-pills [class^="icon-"],.nav-tabs [class*=" icon-"],.nav-pills [class*=" icon-"],.nav-tabs [class^="icon-"].icon-large,.nav-pills [class^="icon-"].icon-large,.nav-tabs [class*=" icon-"].icon-large,.nav-pills [class*=" icon-"].icon-large{line-height:.9em;}
.btn [class^="icon-"].pull-left.icon-2x,.btn [class*=" icon-"].pull-left.icon-2x,.btn [class^="icon-"].pull-right.icon-2x,.btn [class*=" icon-"].pull-right.icon-2x{margin-top:.18em;}
.btn [class^="icon-"].icon-spin.icon-large,.btn [class*=" icon-"].icon-spin.icon-large{line-height:.8em;}
.btn.btn-small [class^="icon-"].pull-left.icon-2x,.btn.btn-small [class*=" icon-"].pull-left.icon-2x,.btn.btn-small [class^="icon-"].pull-right.icon-2x,.btn.btn-small [class*=" icon-"].pull-right.icon-2x{margin-top:.25em;}
.btn.btn-large [class^="icon-"],.btn.btn-large [class*=" icon-"]{margin-top:0;}.btn.btn-large [class^="icon-"].pull-left.icon-2x,.btn.btn-large [class*=" icon-"].pull-left.icon-2x,.btn.btn-large [class^="icon-"].pull-right.icon-2x,.btn.btn-large [class*=" icon-"].pull-right.icon-2x{margin-top:.05em;}
.btn.btn-large [class^="icon-"].pull-left.icon-2x,.btn.btn-large [class*=" icon-"].pull-left.icon-2x{margin-right:.2em;}
.btn.btn-large [class^="icon-"].pull-right.icon-2x,.btn.btn-large [class*=" icon-"].pull-right.icon-2x{margin-left:.2em;}
.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{line-height:inherit;}
.icon-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:-35%;}.icon-stack [class^="icon-"],.icon-stack [class*=" icon-"]{display:block;text-align:center;position:absolute;width:100%;height:100%;font-size:1em;line-height:inherit;*line-height:2em;}
.icon-stack .icon-stack-base{font-size:2em;*line-height:1em;}
.icon-spin{display:inline-block;-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;-webkit-animation:spin 2s infinite linear;animation:spin 2s infinite linear;}
a .icon-stack,a .icon-spin{display:inline-block;text-decoration:none;}
@-moz-keyframes spin{0%{-moz-transform:rotate(0deg);} 100%{-moz-transform:rotate(359deg);}}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg);} 100%{-webkit-transform:rotate(359deg);}}@-o-keyframes spin{0%{-o-transform:rotate(0deg);} 100%{-o-transform:rotate(359deg);}}@-ms-keyframes spin{0%{-ms-transform:rotate(0deg);} 100%{-ms-transform:rotate(359deg);}}@keyframes spin{0%{transform:rotate(0deg);} 100%{transform:rotate(359deg);}}.icon-rotate-90:before{-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);}
.icon-rotate-180:before{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);}
.icon-rotate-270:before{-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);}
.icon-flip-horizontal:before{-webkit-transform:scale(-1, 1);-moz-transform:scale(-1, 1);-ms-transform:scale(-1, 1);-o-transform:scale(-1, 1);transform:scale(-1, 1);}
.icon-flip-vertical:before{-webkit-transform:scale(1, -1);-moz-transform:scale(1, -1);-ms-transform:scale(1, -1);-o-transform:scale(1, -1);transform:scale(1, -1);}
a .icon-rotate-90:before,a .icon-rotate-180:before,a .icon-rotate-270:before,a .icon-flip-horizontal:before,a .icon-flip-vertical:before{display:inline-block;}
.icon-glass:before{content:"\f000";}
.icon-music:before{content:"\f001";}
.icon-search:before{content:"\f002";}
.icon-envelope-alt:before{content:"\f003";}
.icon-heart:before{content:"\f004";}
.icon-star:before{content:"\f005";}
.icon-star-empty:before{content:"\f006";}
.icon-user:before{content:"\f007";}
.icon-film:before{content:"\f008";}
.icon-th-large:before{content:"\f009";}
.icon-th:before{content:"\f00a";}
.icon-th-list:before{content:"\f00b";}
.icon-ok:before{content:"\f00c";}
.icon-remove:before{content:"\f00d";}
.icon-zoom-in:before{content:"\f00e";}
.icon-zoom-out:before{content:"\f010";}
.icon-power-off:before,.icon-off:before{content:"\f011";}
.icon-signal:before{content:"\f012";}
.icon-gear:before,.icon-cog:before{content:"\f013";}
.icon-trash:before{content:"\f014";}
.icon-home:before{content:"\f015";}
.icon-file-alt:before{content:"\f016";}
.icon-time:before{content:"\f017";}
.icon-road:before{content:"\f018";}
.icon-download-alt:before{content:"\f019";}
.icon-download:before{content:"\f01a";}
.icon-upload:before{content:"\f01b";}
.icon-inbox:before{content:"\f01c";}
.icon-play-circle:before{content:"\f01d";}
.icon-rotate-right:before,.icon-repeat:before{content:"\f01e";}
.icon-refresh:before{content:"\f021";}
.icon-list-alt:before{content:"\f022";}
.icon-lock:before{content:"\f023";}
.icon-flag:before{content:"\f024";}
.icon-headphones:before{content:"\f025";}
.icon-volume-off:before{content:"\f026";}
.icon-volume-down:before{content:"\f027";}
.icon-volume-up:before{content:"\f028";}
.icon-qrcode:before{content:"\f029";}
.icon-barcode:before{content:"\f02a";}
.icon-tag:before{content:"\f02b";}
.icon-tags:before{content:"\f02c";}
.icon-book:before{content:"\f02d";}
.icon-bookmark:before{content:"\f02e";}
.icon-print:before{content:"\f02f";}
.icon-camera:before{content:"\f030";}
.icon-font:before{content:"\f031";}
.icon-bold:before{content:"\f032";}
.icon-italic:before{content:"\f033";}
.icon-text-height:before{content:"\f034";}
.icon-text-width:before{content:"\f035";}
.icon-align-left:before{content:"\f036";}
.icon-align-center:before{content:"\f037";}
.icon-align-right:before{content:"\f038";}
.icon-align-justify:before{content:"\f039";}
.icon-list:before{content:"\f03a";}
.icon-indent-left:before{content:"\f03b";}
.icon-indent-right:before{content:"\f03c";}
.icon-facetime-video:before{content:"\f03d";}
.icon-picture:before{content:"\f03e";}
.icon-pencil:before{content:"\f040";}
.icon-map-marker:before{content:"\f041";}
.icon-adjust:before{content:"\f042";}
.icon-tint:before{content:"\f043";}
.icon-edit:before{content:"\f044";}
.icon-share:before{content:"\f045";}
.icon-check:before{content:"\f046";}
.icon-move:before{content:"\f047";}
.icon-step-backward:before{content:"\f048";}
.icon-fast-backward:before{content:"\f049";}
.icon-backward:before{content:"\f04a";}
.icon-play:before{content:"\f04b";}
.icon-pause:before{content:"\f04c";}
.icon-stop:before{content:"\f04d";}
.icon-forward:before{content:"\f04e";}
.icon-fast-forward:before{content:"\f050";}
.icon-step-forward:before{content:"\f051";}
.icon-eject:before{content:"\f052";}
.icon-chevron-left:before{content:"\f053";}
.icon-chevron-right:before{content:"\f054";}
.icon-plus-sign:before{content:"\f055";}
.icon-minus-sign:before{content:"\f056";}
.icon-remove-sign:before{content:"\f057";}
.icon-ok-sign:before{content:"\f058";}
.icon-question-sign:before{content:"\f059";}
.icon-info-sign:before{content:"\f05a";}
.icon-screenshot:before{content:"\f05b";}
.icon-remove-circle:before{content:"\f05c";}
.icon-ok-circle:before{content:"\f05d";}
.icon-ban-circle:before{content:"\f05e";}
.icon-arrow-left:before{content:"\f060";}
.icon-arrow-right:before{content:"\f061";}
.icon-arrow-up:before{content:"\f062";}
.icon-arrow-down:before{content:"\f063";}
.icon-mail-forward:before,.icon-share-alt:before{content:"\f064";}
.icon-resize-full:before{content:"\f065";}
.icon-resize-small:before{content:"\f066";}
.icon-plus:before{content:"\f067";}
.icon-minus:before{content:"\f068";}
.icon-asterisk:before{content:"\f069";}
.icon-exclamation-sign:before{content:"\f06a";}
.icon-gift:before{content:"\f06b";}
.icon-leaf:before{content:"\f06c";}
.icon-fire:before{content:"\f06d";}
.icon-eye-open:before{content:"\f06e";}
.icon-eye-close:before{content:"\f070";}
.icon-warning-sign:before{content:"\f071";}
.icon-plane:before{content:"\f072";}
.icon-calendar:before{content:"\f073";}
.icon-random:before{content:"\f074";}
.icon-comment:before{content:"\f075";}
.icon-magnet:before{content:"\f076";}
.icon-chevron-up:before{content:"\f077";}
.icon-chevron-down:before{content:"\f078";}
.icon-retweet:before{content:"\f079";}
.icon-shopping-cart:before{content:"\f07a";}
.icon-folder-close:before{content:"\f07b";}
.icon-folder-open:before{content:"\f07c";}
.icon-resize-vertical:before{content:"\f07d";}
.icon-resize-horizontal:before{content:"\f07e";}
.icon-bar-chart:before{content:"\f080";}
.icon-twitter-sign:before{content:"\f081";}
.icon-facebook-sign:before{content:"\f082";}
.icon-camera-retro:before{content:"\f083";}
.icon-key:before{content:"\f084";}
.icon-gears:before,.icon-cogs:before{content:"\f085";}
.icon-comments:before{content:"\f086";}
.icon-thumbs-up-alt:before{content:"\f087";}
.icon-thumbs-down-alt:before{content:"\f088";}
.icon-star-half:before{content:"\f089";}
.icon-heart-empty:before{content:"\f08a";}
.icon-signout:before{content:"\f08b";}
.icon-linkedin-sign:before{content:"\f08c";}
.icon-pushpin:before{content:"\f08d";}
.icon-external-link:before{content:"\f08e";}
.icon-signin:before{content:"\f090";}
.icon-trophy:before{content:"\f091";}
.icon-github-sign:before{content:"\f092";}
.icon-upload-alt:before{content:"\f093";}
.icon-lemon:before{content:"\f094";}
.icon-phone:before{content:"\f095";}
.icon-unchecked:before,.icon-check-empty:before{content:"\f096";}
.icon-bookmark-empty:before{content:"\f097";}
.icon-phone-sign:before{content:"\f098";}
.icon-twitter:before{content:"\f099";}
.icon-facebook:before{content:"\f09a";}
.icon-github:before{content:"\f09b";}
.icon-unlock:before{content:"\f09c";}
.icon-credit-card:before{content:"\f09d";}
.icon-rss:before{content:"\f09e";}
.icon-hdd:before{content:"\f0a0";}
.icon-bullhorn:before{content:"\f0a1";}
.icon-bell:before{content:"\f0a2";}
.icon-certificate:before{content:"\f0a3";}
.icon-hand-right:before{content:"\f0a4";}
.icon-hand-left:before{content:"\f0a5";}
.icon-hand-up:before{content:"\f0a6";}
.icon-hand-down:before{content:"\f0a7";}
.icon-circle-arrow-left:before{content:"\f0a8";}
.icon-circle-arrow-right:before{content:"\f0a9";}
.icon-circle-arrow-up:before{content:"\f0aa";}
.icon-circle-arrow-down:before{content:"\f0ab";}
.icon-globe:before{content:"\f0ac";}
.icon-wrench:before{content:"\f0ad";}
.icon-tasks:before{content:"\f0ae";}
.icon-filter:before{content:"\f0b0";}
.icon-briefcase:before{content:"\f0b1";}
.icon-fullscreen:before{content:"\f0b2";}
.icon-group:before{content:"\f0c0";}
.icon-link:before{content:"\f0c1";}
.icon-cloud:before{content:"\f0c2";}
.icon-beaker:before{content:"\f0c3";}
.icon-cut:before{content:"\f0c4";}
.icon-copy:before{content:"\f0c5";}
.icon-paperclip:before,.icon-paper-clip:before{content:"\f0c6";}
.icon-save:before{content:"\f0c7";}
.icon-sign-blank:before{content:"\f0c8";}
.icon-reorder:before{content:"\f0c9";}
.icon-list-ul:before{content:"\f0ca";}
.icon-list-ol:before{content:"\f0cb";}
.icon-strikethrough:before{content:"\f0cc";}
.icon-underline:before{content:"\f0cd";}
.icon-table:before{content:"\f0ce";}
.icon-magic:before{content:"\f0d0";}
.icon-truck:before{content:"\f0d1";}
.icon-pinterest:before{content:"\f0d2";}
.icon-pinterest-sign:before{content:"\f0d3";}
.icon-google-plus-sign:before{content:"\f0d4";}
.icon-google-plus:before{content:"\f0d5";}
.icon-money:before{content:"\f0d6";}
.icon-caret-down:before{content:"\f0d7";}
.icon-caret-up:before{content:"\f0d8";}
.icon-caret-left:before{content:"\f0d9";}
.icon-caret-right:before{content:"\f0da";}
.icon-columns:before{content:"\f0db";}
.icon-sort:before{content:"\f0dc";}
.icon-sort-down:before{content:"\f0dd";}
.icon-sort-up:before{content:"\f0de";}
.icon-envelope:before{content:"\f0e0";}
.icon-linkedin:before{content:"\f0e1";}
.icon-rotate-left:before,.icon-undo:before{content:"\f0e2";}
.icon-legal:before{content:"\f0e3";}
.icon-dashboard:before{content:"\f0e4";}
.icon-comment-alt:before{content:"\f0e5";}
.icon-comments-alt:before{content:"\f0e6";}
.icon-bolt:before{content:"\f0e7";}
.icon-sitemap:before{content:"\f0e8";}
.icon-umbrella:before{content:"\f0e9";}
.icon-paste:before{content:"\f0ea";}
.icon-lightbulb:before{content:"\f0eb";}
.icon-exchange:before{content:"\f0ec";}
.icon-cloud-download:before{content:"\f0ed";}
.icon-cloud-upload:before{content:"\f0ee";}
.icon-user-md:before{content:"\f0f0";}
.icon-stethoscope:before{content:"\f0f1";}
.icon-suitcase:before{content:"\f0f2";}
.icon-bell-alt:before{content:"\f0f3";}
.icon-coffee:before{content:"\f0f4";}
.icon-food:before{content:"\f0f5";}
.icon-file-text-alt:before{content:"\f0f6";}
.icon-building:before{content:"\f0f7";}
.icon-hospital:before{content:"\f0f8";}
.icon-ambulance:before{content:"\f0f9";}
.icon-medkit:before{content:"\f0fa";}
.icon-fighter-jet:before{content:"\f0fb";}
.icon-beer:before{content:"\f0fc";}
.icon-h-sign:before{content:"\f0fd";}
.icon-plus-sign-alt:before{content:"\f0fe";}
.icon-double-angle-left:before{content:"\f100";}
.icon-double-angle-right:before{content:"\f101";}
.icon-double-angle-up:before{content:"\f102";}
.icon-double-angle-down:before{content:"\f103";}
.icon-angle-left:before{content:"\f104";}
.icon-angle-right:before{content:"\f105";}
.icon-angle-up:before{content:"\f106";}
.icon-angle-down:before{content:"\f107";}
.icon-desktop:before{content:"\f108";}
.icon-laptop:before{content:"\f109";}
.icon-tablet:before{content:"\f10a";}
.icon-mobile-phone:before{content:"\f10b";}
.icon-circle-blank:before{content:"\f10c";}
.icon-quote-left:before{content:"\f10d";}
.icon-quote-right:before{content:"\f10e";}
.icon-spinner:before{content:"\f110";}
.icon-circle:before{content:"\f111";}
.icon-mail-reply:before,.icon-reply:before{content:"\f112";}
.icon-github-alt:before{content:"\f113";}
.icon-folder-close-alt:before{content:"\f114";}
.icon-folder-open-alt:before{content:"\f115";}
.icon-expand-alt:before{content:"\f116";}
.icon-collapse-alt:before{content:"\f117";}
.icon-smile:before{content:"\f118";}
.icon-frown:before{content:"\f119";}
.icon-meh:before{content:"\f11a";}
.icon-gamepad:before{content:"\f11b";}
.icon-keyboard:before{content:"\f11c";}
.icon-flag-alt:before{content:"\f11d";}
.icon-flag-checkered:before{content:"\f11e";}
.icon-terminal:before{content:"\f120";}
.icon-code:before{content:"\f121";}
.icon-reply-all:before{content:"\f122";}
.icon-mail-reply-all:before{content:"\f122";}
.icon-star-half-full:before,.icon-star-half-empty:before{content:"\f123";}
.icon-location-arrow:before{content:"\f124";}
.icon-crop:before{content:"\f125";}
.icon-code-fork:before{content:"\f126";}
.icon-unlink:before{content:"\f127";}
.icon-question:before{content:"\f128";}
.icon-info:before{content:"\f129";}
.icon-exclamation:before{content:"\f12a";}
.icon-superscript:before{content:"\f12b";}
.icon-subscript:before{content:"\f12c";}
.icon-eraser:before{content:"\f12d";}
.icon-puzzle-piece:before{content:"\f12e";}
.icon-microphone:before{content:"\f130";}
.icon-microphone-off:before{content:"\f131";}
.icon-shield:before{content:"\f132";}
.icon-calendar-empty:before{content:"\f133";}
.icon-fire-extinguisher:before{content:"\f134";}
.icon-rocket:before{content:"\f135";}
.icon-maxcdn:before{content:"\f136";}
.icon-chevron-sign-left:before{content:"\f137";}
.icon-chevron-sign-right:before{content:"\f138";}
.icon-chevron-sign-up:before{content:"\f139";}
.icon-chevron-sign-down:before{content:"\f13a";}
.icon-html5:before{content:"\f13b";}
.icon-css3:before{content:"\f13c";}
.icon-anchor:before{content:"\f13d";}
.icon-unlock-alt:before{content:"\f13e";}
.icon-bullseye:before{content:"\f140";}
.icon-ellipsis-horizontal:before{content:"\f141";}
.icon-ellipsis-vertical:before{content:"\f142";}
.icon-rss-sign:before{content:"\f143";}
.icon-play-sign:before{content:"\f144";}
.icon-ticket:before{content:"\f145";}
.icon-minus-sign-alt:before{content:"\f146";}
.icon-check-minus:before{content:"\f147";}
.icon-level-up:before{content:"\f148";}
.icon-level-down:before{content:"\f149";}
.icon-check-sign:before{content:"\f14a";}
.icon-edit-sign:before{content:"\f14b";}
.icon-external-link-sign:before{content:"\f14c";}
.icon-share-sign:before{content:"\f14d";}
.icon-compass:before{content:"\f14e";}
.icon-collapse:before{content:"\f150";}
.icon-collapse-top:before{content:"\f151";}
.icon-expand:before{content:"\f152";}
.icon-euro:before,.icon-eur:before{content:"\f153";}
.icon-gbp:before{content:"\f154";}
.icon-dollar:before,.icon-usd:before{content:"\f155";}
.icon-rupee:before,.icon-inr:before{content:"\f156";}
.icon-yen:before,.icon-jpy:before{content:"\f157";}
.icon-renminbi:before,.icon-cny:before{content:"\f158";}
.icon-won:before,.icon-krw:before{content:"\f159";}
.icon-bitcoin:before,.icon-btc:before{content:"\f15a";}
.icon-file:before{content:"\f15b";}
.icon-file-text:before{content:"\f15c";}
.icon-sort-by-alphabet:before{content:"\f15d";}
.icon-sort-by-alphabet-alt:before{content:"\f15e";}
.icon-sort-by-attributes:before{content:"\f160";}
.icon-sort-by-attributes-alt:before{content:"\f161";}
.icon-sort-by-order:before{content:"\f162";}
.icon-sort-by-order-alt:before{content:"\f163";}
.icon-thumbs-up:before{content:"\f164";}
.icon-thumbs-down:before{content:"\f165";}
.icon-youtube-sign:before{content:"\f166";}
.icon-youtube:before{content:"\f167";}
.icon-xing:before{content:"\f168";}
.icon-xing-sign:before{content:"\f169";}
.icon-youtube-play:before{content:"\f16a";}
.icon-dropbox:before{content:"\f16b";}
.icon-stackexchange:before{content:"\f16c";}
.icon-instagram:before{content:"\f16d";}
.icon-flickr:before{content:"\f16e";}
.icon-adn:before{content:"\f170";}
.icon-bitbucket:before{content:"\f171";}
.icon-bitbucket-sign:before{content:"\f172";}
.icon-tumblr:before{content:"\f173";}
.icon-tumblr-sign:before{content:"\f174";}
.icon-long-arrow-down:before{content:"\f175";}
.icon-long-arrow-up:before{content:"\f176";}
.icon-long-arrow-left:before{content:"\f177";}
.icon-long-arrow-right:before{content:"\f178";}
.icon-apple:before{content:"\f179";}
.icon-windows:before{content:"\f17a";}
.icon-android:before{content:"\f17b";}
.icon-linux:before{content:"\f17c";}
.icon-dribbble:before{content:"\f17d";}
.icon-skype:before{content:"\f17e";}
.icon-foursquare:before{content:"\f180";}
.icon-trello:before{content:"\f181";}
.icon-female:before{content:"\f182";}
.icon-male:before{content:"\f183";}
.icon-gittip:before{content:"\f184";}
.icon-sun:before{content:"\f185";}
.icon-moon:before{content:"\f186";}
.icon-archive:before{content:"\f187";}
.icon-bug:before{content:"\f188";}
.icon-vk:before{content:"\f189";}
.icon-weibo:before{content:"\f18a";}
.icon-renren:before{content:"\f18b";}
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;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;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-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}.btn.active,.btn:active{background-color:#ccc\9}.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:thin dotted #333;outline:5px auto -webkit-focus-ring-color;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-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.active{color:rgba(255,255,255,.75)}.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;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);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}.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;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);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}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);backLine truncated
.btn{display:inline-block;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;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-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}.btn.active,.btn:active{background-color:#ccc\9}.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:thin dotted #333;outline:5px auto -webkit-focus-ring-color;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-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.active{color:rgba(255,255,255,.75)}.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;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);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}.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;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);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}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);backLine truncated
+152 -80
View File
@@ -9,11 +9,15 @@ var firstReport;
var toolOffsets = [
{x: 0, y: 0}
];
var g90InfluencesExtruder = false;
var z_heights = {};
var model = [];
var max = {x: undefined, y: undefined, z: undefined};
var min = {x: undefined, y: undefined, z: undefined};
var boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
var modelSize = {x: undefined, y: undefined, z: undefined};
var bed = {x: undefined, y: undefined, r: undefined, circular: false, centeredOrigin: false};
var ignoreOutsideBed = false;
var filamentByLayer = {};
var totalFilament = [0];
var printTime = 0;
@@ -75,6 +79,7 @@ var sendAnalyzeDone = function () {
max: max,
min: min,
modelSize: modelSize,
boundingBox: boundingBox,
totalFilament: totalFilament,
filamentByLayer: filamentByLayer,
printTime: printTime,
@@ -105,6 +110,36 @@ var purgeLayers = function () {
}
};
var bedBounds = function() {
if (!bed) {
return {xMin: 0, xMax: 0, yMin: 0, yMax: 0};
}
var result;
if (bed.circular) {
result = {xMin: -bed.r, xMax: bed.r, yMin: -bed.r, yMax: bed.r};
} else if (bed.centeredOrigin) {
result = {xMin: -bed.x/2.0, xMax: bed.x/2.0, yMin: -bed.y/2.0, yMax: bed.y/2.0};
} else {
result = {xMin: 0, xMax: bed.x, yMin: 0, yMax: bed.y};
}
return result;
};
var withinBedBounds = function(x, y, bedBounds) {
if (!ignoreOutsideBed) return true;
var result = true;
if (x !== undefined && !isNaN(x)) {
result = result && (x >= bedBounds.xMin && x <= bedBounds.xMax);
}
if (y !== undefined && !isNaN(y)) {
result = result && (y >= bedBounds.yMin && y <= bedBounds.yMax);
}
return result;
};
var analyzeModel = function () {
var tmp1 = 0, tmp2 = 0;
@@ -112,6 +147,8 @@ var analyzeModel = function () {
var type;
var printTimeAdd = 0;
var bounds = bedBounds();
for (var i = 0; i < model.length; i++) {
var cmds = model[i];
if (!cmds) continue;
@@ -119,41 +156,56 @@ var analyzeModel = function () {
for (var j = 0; j < cmds.length; j++) {
var tool = cmds[j].tool;
var x_ok = false;
var y_ok = false;
var retract = cmds[j].retract && cmds[j].retract > 0;
var extrude = cmds[j].extrude && cmds[j].extrude > 0 && !retract;
var move = cmds[j].x !== undefined || cmds[j].y !== undefined || cmds[j].z !== undefined;
var prevInBounds = withinBedBounds(cmds[j].prevX, cmds[j].prevY, bounds);
var inBounds = withinBedBounds(cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
bounds);
var recordX = function(x, inBounds) {
if (x === undefined || isNaN(x)) return;
if (typeof(cmds[j].x) !== 'undefined'
&& typeof(cmds[j].prevX) !== 'undefined'
&& typeof(cmds[j].extrude) !== 'undefined'
&& cmds[j].extrude
&& !isNaN(cmds[j].x)) {
var x = cmds[j].x;
max.x = max.x !== undefined ? Math.max(max.x, x) : x;
min.x = min.x !== undefined ? Math.min(min.x, x) : x;
x_ok = true;
}
if (inBounds) {
boundingBox.minX = boundingBox.minX !== undefined ? Math.min(boundingBox.minX, x): x;
boundingBox.maxX = boundingBox.maxX !== undefined ? Math.max(boundingBox.maxX, x): x;
}
};
if (typeof(cmds[j].y) !== 'undefined'
&& typeof(cmds[j].prevY) !== 'undefined'
&& typeof(cmds[j].extrude) !== 'undefined'
&& cmds[j].extrude
&& !isNaN(cmds[j].y)) {
var y = cmds[j].y;
var recordY = function(y, inBounds) {
if (y === undefined || isNaN(y)) return;
max.y = max.y !== undefined ? Math.max(max.y, y) : y;
min.y = min.y !== undefined ? Math.min(min.y, y) : y;
y_ok = true;
}
if (inBounds) {
boundingBox.minY = boundingBox.minY !== undefined ? Math.min(boundingBox.minY, y): y;
boundingBox.maxY = boundingBox.maxY !== undefined ? Math.max(boundingBox.maxY, y): y;
}
};
var recordZ = function(z) {
if (z === undefined || isNaN(z)) return;
if (typeof(cmds[j].prevZ) !== 'undefined'
&& typeof(cmds[j].extrude) !== 'undefined'
&& cmds[j].extrude
&& !isNaN(cmds[j].prevZ)) {
var z = cmds[j].prevZ;
max.z = max.z !== undefined ? Math.max(max.z, z) : z;
min.z = min.z !== undefined ? Math.min(min.z, z) : z;
boundingBox.minZ = min.z;
boundingBox.maxZ = max.z;
};
if (move && extrude) {
recordX(cmds[j].prevX, prevInBounds);
recordX(cmds[j].x, inBounds);
recordY(cmds[j].prevY, prevInBounds);
recordY(cmds[j].y, inBounds);
recordZ(cmds[j].prevZ);
recordZ(cmds[j].z);
}
if (!totalFilament[tool]) totalFilament[tool] = 0;
@@ -164,20 +216,25 @@ var analyzeModel = function () {
filamentByLayer[cmds[j].prevZ][tool] += cmds[j].extrusion;
}
var diffX = cmds[j].x - cmds[j].prevX;
var diffY = cmds[j].y - cmds[j].prevY;
if (x_ok && y_ok) {
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
} else if (cmds[j].retract === 0 && cmds[j].extrusion !== 0) {
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
printTimeAdd = Math.max(tmp1, tmp2);
} else if (cmds[j].retract !== 0) {
printTimeAdd = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
if (cmds[j].x !== undefined && !isNaN(cmds[j].x)
&& cmds[j].y !== undefined && !isNaN(cmds[j].y)) {
var diffX = cmds[j].x - cmds[j].prevX;
var diffY = cmds[j].y - cmds[j].prevY;
if (move) {
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
} else if (extrude) {
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
printTimeAdd = Math.max(tmp1, tmp2);
} else if (retract) {
printTimeAdd = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
}
} else {
printTimeAdd = 0;
}
printTime += printTimeAdd;
if (typeof(printTimeByLayer[cmds[j].prevZ]) === 'undefined') {
if (printTimeByLayer[cmds[j].prevZ] === undefined) {
printTimeByLayer[cmds[j].prevZ] = 0;
}
printTimeByLayer[cmds[j].prevZ] += printTimeAdd;
@@ -232,8 +289,8 @@ var doParse = function () {
var center_i, center_j, direction;
var prevX = 0, prevY = 0, prevZ = 0;
var f, lastF = 4000;
var extrude = false, extrudeRelative = false, retract = 0;
var positionRelative = false;
var extrude = false, relativeE = false, retract = 0;
var relativeMode = false;
var zLift = false;
var zLiftZ = undefined;
var zLiftMoves = [];
@@ -244,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;
@@ -268,30 +331,30 @@ 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 (positionRelative) {
x = prevX + Number(args[j].slice(1)) + offset.x;
if (relativeMode) {
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 (positionRelative) {
y = prevY + Number(args[j].slice(1)) + offset.y;
if (relativeMode) {
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;
case 'z':
if (positionRelative) {
if (relativeMode) {
z = prevZ + Number(args[j].slice(1));
} else {
z = Number(args[j].slice(1));
@@ -306,20 +369,20 @@ var doParse = function () {
assumeNonDC = true;
numSlice = Number(args[j].slice(1));
if (!extrudeRelative) {
if (relativeMode || relativeE) {
prev_extrude[tool]["abs"] = numSlice;
prev_extrude[tool][argChar] += numSlice;
} else {
// absolute extrusion positioning
prev_extrude[tool]["abs"] = numSlice - prev_extrude[tool][argChar];
prev_extrude[tool][argChar] = numSlice;
} else {
prev_extrude[tool]["abs"] = numSlice;
prev_extrude[tool][argChar] += numSlice;
}
extrude = prev_extrude[tool]["abs"] > 0;
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;
@@ -341,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;
}
@@ -354,31 +417,35 @@ 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;
}
} else if (/^(?:M82)/i.test(line)) {
extrudeRelative = false;
relativeE = false;
} else if (/^(?:G91)/i.test(line)) {
positionRelative = true;
extrudeRelative = true;
relativeMode = true;
if (g90InfluencesExtruder) {
relativeE = true;
}
} else if (/^(?:G90)/i.test(line)) {
positionRelative = false;
extrudeRelative = false;
relativeMode = false;
if (g90InfluencesExtruder) {
relativeE = false;
}
} else if (/^(?:M83)/i.test(line)) {
extrudeRelative = true;
relativeE = true;
} else if (/^(?:M101)/i.test(line)) {
dcExtrude = true;
} 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;
@@ -390,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':
@@ -407,10 +474,10 @@ var doParse = function () {
case 'b':
case 'c':
numSlice = Number(args[j].slice(1));
if (!extrudeRelative)
prev_extrude[tool][argChar] = 0;
else {
if (relativeMode || relativeE) {
prev_extrude[tool][argChar] = numSlice;
} else {
prev_extrude[tool][argChar] = 0;
}
break;
}
@@ -423,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;
@@ -449,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;
}
@@ -462,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;
}
@@ -477,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 {
@@ -488,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 {
@@ -548,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 = [];
@@ -568,7 +635,10 @@ 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;
doParse();
gcode = [];
@@ -589,6 +659,7 @@ var runAnalyze = function (message) {
max = {x: undefined, y: undefined, z: undefined};
min = {x: undefined, y: undefined, z: undefined};
modelSize = {x: undefined, y: undefined, z: undefined};
boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
filamentByLayer = {};
totalFilament = 0;
printTime = 0;
@@ -601,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];
}
};
@@ -12,6 +12,9 @@ GCODE.gCodeReader = (function(){
var max = {x: undefined, y: undefined, z: undefined};
var min = {x: undefined, y: undefined, z: undefined};
var modelSize = {x: undefined, y: undefined, z: undefined};
var boundingBox = {minX: undefined, maxX: undefined,
minY: undefined, maxY: undefined,
minZ: undefined, maxZ: undefined};
var filamentByLayer = {};
var printTimeByLayer;
var totalFilament=0;
@@ -24,7 +27,16 @@ GCODE.gCodeReader = (function(){
analyzeModel: false,
toolOffsets: [
{x: 0, y: 0}
]
],
bed: {
x: undefined,
y: undefined,
r: undefined,
circular: undefined,
centeredOrigin: undefined
},
ignoreOutsideBed: false,
g90InfluencesExtruder: false
};
var percentageTree = undefined;
@@ -122,6 +134,12 @@ GCODE.gCodeReader = (function(){
clear: function() {
model = [];
z_heights = [];
max = {x: undefined, y: undefined, z: undefined};
min = {x: undefined, y: undefined, z: undefined};
modelSize = {x: undefined, y: undefined, z: undefined};
boundingBox = {minX: undefined, maxX: undefined,
minY: undefined, maxY: undefined,
minZ: undefined, maxZ: undefined};
},
loadFile: function(reader){
@@ -138,7 +156,10 @@ GCODE.gCodeReader = (function(){
gcode: gcode,
options: {
firstReport: 5,
toolOffsets: gCodeOptions["toolOffsets"]
toolOffsets: gCodeOptions["toolOffsets"],
bed: gCodeOptions["bed"],
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
}
}
}
@@ -180,6 +201,7 @@ GCODE.gCodeReader = (function(){
min = msg.min;
max = msg.max;
modelSize = msg.modelSize;
boundingBox = msg.boundingBox;
totalFilament = msg.totalFilament;
filamentByLayer = msg.filamentByLayer;
speeds = msg.speeds;
@@ -201,6 +223,7 @@ GCODE.gCodeReader = (function(){
min: min,
max: max,
modelSize: modelSize,
boundingBox: boundingBox,
totalFilament: totalFilament,
speeds: speeds,
speedsByLayer: speedsByLayer,
+67 -20
View File
@@ -20,7 +20,8 @@ GCODE.renderer = (function(){
var lastX, lastY;
var dragStart, dragged;
var scaleFactor = 1.1;
var model;
var model = undefined;
var modelInfo = undefined;
var initialized = false;
var renderOptions = {
colorGrid: "#bbbbbb",
@@ -40,6 +41,8 @@ GCODE.renderer = (function(){
differentiateColors: true,
showNextLayer: false,
showPreviousLayer: false,
showBoundingBox: false,
showFullSize: false,
moveModel: true,
zoomInOnModel: false,
@@ -65,6 +68,7 @@ GCODE.renderer = (function(){
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
drawGrid();
drawBoundingBox();
if(renderOptions['showNextLayer'] && layerNumStore < model.length - 1) {
drawLayer(layerNumStore + 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore + 1), true);
}
@@ -378,6 +382,44 @@ GCODE.renderer = (function(){
ctx.stroke();
};
var drawBoundingBox = function() {
if (!modelInfo) return;
var minX, minY, width, height;
if (renderOptions["showFullSize"]) {
minX = modelInfo.min.x * zoomFactor;
minY = modelInfo.min.y * zoomFactor;
width = modelInfo.modelSize.x * zoomFactor;
height = modelInfo.modelSize.y * zoomFactor;
ctx.beginPath();
ctx.strokeStyle = "#0000ff";
ctx.setLineDash([2, 5]);
ctx.rect(minX, minY * -1, width, height * -1);
ctx.stroke();
}
if (renderOptions["showBoundingBox"]) {
minX = modelInfo.boundingBox.minX * zoomFactor;
minY = modelInfo.boundingBox.minY * zoomFactor;
width = modelInfo.boundingBox.maxX * zoomFactor - minX;
height = modelInfo.boundingBox.maxY * zoomFactor - minY;
ctx.beginPath();
ctx.strokeStyle = "#ff0000";
ctx.setLineDash([2, 5]);
ctx.rect(minX, minY * -1, width, height * -1);
ctx.stroke();
}
ctx.setLineDash([1, 0]);
};
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
@@ -524,27 +566,27 @@ GCODE.renderer = (function(){
ctx.stroke();
};
var applyOffsets = function(mdlInfo) {
var applyOffsets = function() {
var canvasCenter;
// determine bed and model offsets
if (ctx) ctx.translate(-offsetModelX, -offsetModelY);
if (renderOptions["centerViewport"] || renderOptions["zoomInOnModel"]) {
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
if (mdlInfo) {
offsetModelX = canvasCenter.x - (mdlInfo.min.x + mdlInfo.modelSize.x / 2) * zoomFactor;
offsetModelY = canvasCenter.y + (mdlInfo.min.y + mdlInfo.modelSize.y / 2) * zoomFactor;
if (modelInfo) {
offsetModelX = canvasCenter.x - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) * zoomFactor / 2;
offsetModelY = canvasCenter.y + (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) * zoomFactor / 2;
} else {
offsetModelX = 0;
offsetModelY = 0;
}
offsetBedX = 0;
offsetBedY = 0;
} else if (mdlInfo && renderOptions["moveModel"]) {
offsetModelX = (renderOptions["bed"]["x"] / 2 - (mdlInfo.min.x + mdlInfo.modelSize.x / 2)) * zoomFactor;
offsetModelY = -1 * (renderOptions["bed"]["y"] / 2 - (mdlInfo.min.y + mdlInfo.modelSize.y / 2)) * zoomFactor;
offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (mdlInfo.min.x + mdlInfo.modelSize.x / 2)) * zoomFactor;
offsetBedY = (renderOptions["bed"]["y"] / 2 - (mdlInfo.min.y + mdlInfo.modelSize.y / 2)) * zoomFactor;
} else if (modelInfo && renderOptions["moveModel"]) {
offsetModelX = (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2) * zoomFactor;
offsetModelY = -1 * (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2) * zoomFactor;
offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2) * zoomFactor;
offsetBedY = (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2) * zoomFactor;
} else if (renderOptions["bed"]["circular"] || renderOptions["bed"]["centeredOrigin"]) {
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
offsetModelX = canvasCenter.x;
@@ -560,7 +602,7 @@ GCODE.renderer = (function(){
if (ctx) ctx.translate(offsetModelX, offsetModelY);
};
var applyZoom = function(mdlInfo) {
var applyZoom = function() {
// get middle of canvas
var pt = ctx.transformedPoint(canvas.width/2,canvas.height/2);
@@ -575,9 +617,12 @@ GCODE.renderer = (function(){
transform = ctx.getTransform();
}
if (mdlInfo && renderOptions["zoomInOnModel"]) {
if (modelInfo && renderOptions["zoomInOnModel"]) {
// if we need to zoom in on model, scale factor is calculated by longer side of object in relation to that axis of canvas
var scaleF = mdlInfo.modelSize.x > mdlInfo.modelSize.y ? (canvas.width - 10) / mdlInfo.modelSize.x : (canvas.height - 10) / mdlInfo.modelSize.y;
var width = modelInfo.boundingBox.maxX - modelInfo.boundingBox.minX;
var length = modelInfo.boundingBox.maxY - modelInfo.boundingBox.minY;
var scaleF = width > length ? (canvas.width - 10) / width : (canvas.height - 10) / length;
scaleF /= zoomFactor;
if (transform.a && transform.d) {
scaleX = scaleF / transform.a * (renderOptions["invertAxes"]["x"] ? -1 : 1);
@@ -682,6 +727,7 @@ GCODE.renderer = (function(){
var p2 = ctx.transformedPoint(canvas.width, canvas.height);
ctx.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
drawGrid();
drawBoundingBox();
if (model && model.length) {
if (layerNum < model.length) {
if (renderOptions['showNextLayer'] && layerNum < model.length - 1) {
@@ -715,30 +761,31 @@ GCODE.renderer = (function(){
scaleY = 1;
speeds = [];
speedsByLayer = {};
modelInfo = undefined;
this.doRender([], 0);
},
doRender: function(mdl, layerNum){
model = mdl;
modelInfo = undefined;
var mdlInfo = undefined;
prevX = 0;
prevY = 0;
if (!initialized) this.init();
var toProgress = 1;
if (model) {
mdlInfo = GCODE.gCodeReader.getModelInfo();
speeds = mdlInfo.speeds;
speedsByLayer = mdlInfo.speedsByLayer;
if (model && model.length) {
modelInfo = GCODE.gCodeReader.getModelInfo();
speeds = modelInfo.speeds;
speedsByLayer = modelInfo.speedsByLayer;
if (model[layerNum]) {
toProgress = model[layerNum].length;
}
}
applyInversion();
applyOffsets(mdlInfo);
applyZoom(mdlInfo);
applyOffsets();
applyZoom();
this.render(layerNum, 0, toProgress);
},
+2 -1
View File
@@ -161,7 +161,8 @@ GCODE.ui = (function(){
bed: options.bed
});
GCODE.gCodeReader.setOption({
toolOffsets: options.toolOffsets
toolOffsets: options.toolOffsets,
bed: options.bed
});
GCODE.renderer.render(0, 0);
+40 -6
View File
@@ -11,6 +11,13 @@
background-color: #ffffff;
}
a,
a:hover,
a:active,
a:visited {
color: #333333;
}
#startup-overlay {
position: fixed;
top: 0;
@@ -53,6 +60,10 @@
text-align: center;
}
.normal {
color: #333333;
}
.green {
color: #169300;
}
@@ -166,9 +177,22 @@
var cachedTimeout;
var message = window.document.getElementById("message");
var reloadnow = window.document.getElementById("reloadnow");
var reloadnowlink = window.document.getElementById("reloadnowlink");
var reload = function() {
var reloadUrl = baseUrl + currentQuery + currentFragment;
if (reloadUrl == window.location.href) {
window.location.reload(false);
} else {
window.location.href = reloadUrl;
}
};
var indexCached = false;
var indexCachedCallback = function(result) {
if (indexCached) return;
if (result == "load") {
if (indexCached) {
return;
@@ -178,13 +202,9 @@
indexCached = true;
message.className = "pulsate1 green";
message.innerText = "OctoPrint server ready, reloading page...";
reloadnow.style.display = "none";
var reloadUrl = baseUrl + currentQuery + currentFragment;
if (reloadUrl == window.location.href) {
window.location.reload(false);
} else {
window.location.href = reloadUrl;
}
reload();
} else {
// cached.gif still not available, let's look at it again in a second
cachedTimeout = setTimeout(function() {
@@ -198,6 +218,19 @@
if (result == "load") {
// our online.gif loaded, so the server is up, let's wait for it to become ready
serverIsOnline = true;
message.innerText = "OctoPrint server started, waiting for it to get ready...";
reloadnowlink.onclick = function() {
indexCached = true; // not really, but we fake it
message.className = "pulsate1";
message.innerText = "Reloading page...";
reloadnow.style.display = "none";
reload();
};
reloadnow.style.display = "block";
ping(indexCachedUrl, timeout, indexCachedCallback);
} else {
// online.gif still not available, let's look at it again later
@@ -255,6 +288,7 @@
<div class="inner">
<div class="content">
<h1 id="message" class="pulsate3">OctoPrint is still starting up, please wait...</h1>
<small id="reloadnow" style="display: none"><a id="reloadnowlink" class="normal" href="javascript:void(0)">Don't wait, reload now!</a></small>
</div>
</div>
</div>
@@ -14,6 +14,7 @@ ko.bindingHandlers.toggleContent = {
e.preventDefault();
if(options.class) {
$elm.children('[class^="icon-"]').toggleClass(options.class);
$elm.children('[class^="fa"]').toggleClass(options.class);
}
if(options.container) {
if(options.parent) {
@@ -106,6 +106,7 @@
var onOpen = function() {
self.reconnecting = false;
self.reconnectTrial = 0;
self.onConnected();
};
var onClose = function(e) {
@@ -117,6 +118,8 @@
return;
}
self.onDisconnected(e.code);
if (self.reconnectTrial < self.options.timeouts.length) {
var timeout = self.options.timeouts[self.reconnectTrial];
setTimeout(function() { self.reconnect() }, timeout * 1000);
@@ -160,6 +163,8 @@
OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {};
OctoPrintSocketClient.prototype.onReconnectFailed = function() {};
OctoPrintSocketClient.prototype.onConnected = function() {};
OctoPrintSocketClient.prototype.onDisconnected = function(code) {};
OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) {
this.increaseRate();
+150 -97
View File
@@ -1,13 +1,17 @@
function DataUpdater(allViewModels) {
function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
var self = this;
self.allViewModels = allViewModels;
self.connectCallback = connectCallback;
self.disconnectCallback = disconnectCallback;
self._pluginHash = undefined;
self._configHash = undefined;
self._connectedDeferred = undefined;
self._initializedDeferred = undefined;
self._throttleFactor = 1;
self._baseProcessingLimit = 500.0;
self._lastProcessingTimes = [];
@@ -57,6 +61,13 @@ function DataUpdater(allViewModels) {
return self._connectedDeferred.promise();
};
self.initialized = function() {
if (self._initializedDeferred) {
self._initializedDeferred.resolve();
self._initializedDeferred = undefined;
}
};
self._onReconnectAttempt = function(trial) {
if (trial <= 0) {
// Only consider it a real disconnect if the trial number has exceeded our threshold.
@@ -99,7 +110,27 @@ function DataUpdater(allViewModels) {
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, but you may try a manual reconnect using the button below."));
};
self._onConnected = function(event) {
self._onDisconnected = function(code) {
if (self._initializedDeferred) {
self._initializedDeferred.reject();
}
self._initializedDeferred = undefined;
if (self.disconnectCallback) {
self.disconnectCallback();
}
};
self._onConnectMessage = function(event) {
if (self._initializedDeferred) {
self._initializedDeferred.reject();
}
self._initializedDeferred = $.Deferred();
if (self.connectCallback) {
self.connectCallback();
}
var data = event.data;
// update version information
@@ -117,37 +148,40 @@ function DataUpdater(allViewModels) {
var oldConfigHash = self._configHash;
self._configHash = data["config_hash"];
// process safe mode
if (self._safeModePopup) self._safeModePopup.remove();
if (data["safe_mode"]) {
// safe mode is active, let's inform the user
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
self._ifInitialized(function() {
// process safe mode
if (self._safeModePopup) self._safeModePopup.remove();
if (data["safe_mode"]) {
// safe mode is active, let's inform the user
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
self._safeModePopup = new PNotify({
title: gettext("Safe mode is active"),
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
hide: false
});
}
self._safeModePopup = new PNotify({
title: gettext("Safe mode is active"),
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
hide: false
});
}
// if the offline overlay is still showing, now's a good time to
// hide it, plus reload the camera feed if it's currently displayed
if ($("#offline_overlay").is(":visible")) {
hideOfflineOverlay();
callViewModels(self.allViewModels, "onServerReconnect");
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
} else {
callViewModels(self.allViewModels, "onServerConnect");
}
// if the offline overlay is still showing, now's a good time to
// hide it, plus reload the camera feed if it's currently displayed
if ($("#offline_overlay").is(":visible")) {
hideOfflineOverlay();
callViewModels(self.allViewModels, "onServerReconnect");
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
} else {
callViewModels(self.allViewModels, "onServerConnect");
}
// if the version, the plugin hash or the config hash changed, we
// want the user to reload the UI since it might be stale now
var versionChanged = oldVersion != VERSION;
var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash;
var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash;
if (versionChanged || pluginsChanged || configChanged) {
showReloadOverlay();
}
// if the version, the plugin hash or the config hash changed, we
// want the user to reload the UI since it might be stale now
var versionChanged = oldVersion !== VERSION;
var pluginsChanged = oldPluginHash !== undefined && oldPluginHash !== self._pluginHash;
var configChanged = oldConfigHash !== undefined && oldConfigHash !== self._configHash;
if (versionChanged || pluginsChanged || configChanged) {
showReloadOverlay();
}
});
log.info("Connected to the server");
@@ -159,79 +193,89 @@ function DataUpdater(allViewModels) {
};
self._onHistoryData = function(event) {
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
};
self._onCurrentData = function(event) {
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
};
self._onSlicingProgress = function(event) {
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
var data = event.data;
callViewModels(self.allViewModels, "onSlicingProgress", [
data["slicer"],
data["model_path"],
data["machinecode_path"],
data["progress"]
]);
};
self._onEvent = function(event) {
var gcodeUploadProgress = $("#gcode_upload_progress");
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
var type = event.data["type"];
var payload = event.data["payload"];
var html = "";
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type == "PrintCancelled") {
if (payload.firmwareError) {
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
type: "error",
hide: false
});
}
} else if (type == "Error") {
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
type: "error",
hide: false
});
}
var legacyEventHandlers = {
"UpdatedFiles": "onUpdatedFiles",
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
"SlicingDone": "onSlicingDone",
"SlicingCancelled": "onSlicingCancelled",
"SlicingFailed": "onSlicingFailed"
};
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onEvent" + type)) {
viewModel["onEvent" + type](payload);
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
// there might still be code that uses the old callbacks, make sure those still get called
// but log a warning
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
viewModel[legacyEventHandlers[type]](payload);
}
self._ifInitialized(function() {
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
});
};
self._onCurrentData = function(event) {
self._ifInitialized(function() {
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
});
};
self._onSlicingProgress = function(event) {
self._ifInitialized(function() {
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
var data = event.data;
callViewModels(self.allViewModels, "onSlicingProgress", [
data["slicer"],
data["model_path"],
data["machinecode_path"],
data["progress"]
]);
});
};
self._onEvent = function(event) {
self._ifInitialized(function() {
var type = event.data["type"];
var payload = event.data["payload"];
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type == "PrintCancelled") {
if (payload.firmwareError) {
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
type: "error",
hide: false
});
}
} else if (type == "Error") {
if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect"
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
type: "error",
hide: false
});
}
}
var legacyEventHandlers = {
"UpdatedFiles": "onUpdatedFiles",
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
"SlicingDone": "onSlicingDone",
"SlicingCancelled": "onSlicingCancelled",
"SlicingFailed": "onSlicingFailed"
};
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onEvent" + type)) {
viewModel["onEvent" + type](payload);
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
// there might still be code that uses the old callbacks, make sure those still get called
// but log a warning
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
viewModel[legacyEventHandlers[type]](payload);
}
});
})
};
self._onTimelapse = function(event) {
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
self._ifInitialized(function() {
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
})
};
self._onPluginMessage = function(event) {
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
self._ifInitialized(function() {
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
})
};
self._onIncreaseRate = function(measurement, minimum) {
@@ -244,12 +288,21 @@ function DataUpdater(allViewModels) {
OctoPrint.socket.decreaseRate();
};
self._ifInitialized = function(callback) {
if (self._initializedDeferred) {
self._initializedDeferred.done(callback);
} else {
callback();
}
};
OctoPrint.socket.onDisconnected = self._onDisconnected;
OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt;
OctoPrint.socket.onReconnectFailed = self._onReconnectFailed;
OctoPrint.socket.onRateTooHigh = self._onDecreaseRate;
OctoPrint.socket.onRateTooLow = self._onIncreaseRate;
OctoPrint.socket
.onMessage("connected", self._onConnected)
.onMessage("connected", self._onConnectMessage)
.onMessage("history", self._onHistoryData)
.onMessage("current", self._onCurrentData)
.onMessage("slicingProgress", self._onSlicingProgress)
+59 -17
View File
@@ -398,7 +398,7 @@ function formatFuzzyPrintTime(totalSeconds) {
*
* Accuracy decreases the higher the estimation is:
*
* * less than 30s: "a couple of seconds"
* * less than 30s: "a few seconds"
* * 30s to a minute: "less than a minute"
* * 1 to 30min: rounded to full minutes, above 30s is minute + 1 ("27 minutes", "2 minutes")
* * 30min to 40min: "40 minutes"
@@ -495,7 +495,7 @@ function formatFuzzyPrintTime(totalSeconds) {
} else {
// only seconds
if (seconds < 30) {
text = gettext("a couple of seconds");
text = gettext("a few seconds");
} else {
text = gettext("less than a minute");
}
@@ -524,12 +524,14 @@ function formatFilament(filament) {
}
function cleanTemperature(temp) {
if (!temp || temp < 10) return gettext("off");
if (temp === undefined || !_.isNumber(temp)) return "-";
if (temp < 10) return gettext("off");
return temp;
}
function formatTemperature(temp, showF) {
if (!temp || temp < 10) return gettext("off");
if (temp === undefined || !_.isNumber(temp)) return "-";
if (temp < 10) return gettext("off");
if (showF) {
return _.sprintf("%.1f&deg;C (%.1f&deg;F)", temp, temp * 9 / 5 + 32);
} else {
@@ -646,6 +648,7 @@ function showConfirmationDialog(msg, onacknowledge, options) {
var proceed = options.proceed || gettext("Proceed");
var proceedClass = options.proceedClass || "danger";
var onproceed = options.onproceed || undefined;
var onclose = options.onclose || undefined;
var dialogClass = options.dialogClass || "";
var modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a><h3>' + title + '</h3>');
@@ -663,14 +666,19 @@ function showConfirmationDialog(msg, onacknowledge, options) {
.append($('<div></div>').addClass('modal-header').append(modalHeader))
.append($('<div></div>').addClass('modal-body').append(modalBody))
.append($('<div></div>').addClass('modal-footer').append(cancelButton).append(proceedButton));
modal.on('hidden', function(event) {
if (onclose && _.isFunction(onclose)) {
onclose(event);
}
});
modal.modal("show");
proceedButton.click(function(e) {
e.preventDefault();
modal.modal("hide");
if (onproceed && _.isFunction(onproceed)) {
onproceed(e);
}
modal.modal("hide");
});
return modal;
@@ -682,9 +690,14 @@ function showConfirmationDialog(msg, onacknowledge, options) {
* Will listen to the supplied promise, update the progress on .progress events and
* enabling the close button and (optionally) closing the dialog on promise resolve.
*
* The calling code should call "notify" on the deferred backing the promise and supply
* two parameters: the text to display on the progress bar and the optional output field and
* a boolean value indicating whether the operation behind that update was successful or not.
* The calling code should call "notify" on the deferred backing the promise and supply:
*
* * the text to display on the progress bar and the optional output field and
* a boolean value indicating whether the operation behind that update was successful or not
* * a short text to display on the progress bar, a long text to display on the optional output
* field and a boolean value indicating whether the operation behind that update was
* successful or not
*
* Non-successful progress updates will remove the barClassSuccess class from the progress bar and
* apply the barClassFailure class and also apply the outputClassFailure to the produced line
* in the output.
@@ -764,7 +777,7 @@ function showProgressModal(options, promise) {
var pre;
if (output) {
pre = $("<pre class='terminal pre-scrollable' style='height: 70px; font-size: 0.8em'></pre>");
pre = $("<pre class='pre-scrollable pre-output' style='height: 70px; font-size: 0.8em'></pre>");
modalBody.append(pre);
}
@@ -778,7 +791,19 @@ function showProgressModal(options, promise) {
var counter = 0;
promise
.progress(function(text, success) {
.progress(function() {
var short, long, success;
if (arguments.length === 2) {
short = long = arguments[0];
success = arguments[1];
} else if (arguments.length === 3) {
short = arguments[0];
long = arguments[1];
success = arguments[2];
} else {
throw Error("Invalid parameters for showProgressModal, expected either (text, success) or (short, long, success)");
}
var value;
if (max === undefined || max <= 0) {
@@ -790,8 +815,8 @@ function showProgressModal(options, promise) {
// update progress bar
progressBar.width(String(value) + "%");
progressTextFront.text(text);
progressTextBack.text(text);
progressTextFront.text(short);
progressTextBack.text(short);
progressTextFront.width(progress.width());
// if not successful, apply failure class
@@ -803,9 +828,9 @@ function showProgressModal(options, promise) {
if (output && pre) {
if (success) {
pre.append($("<span class='" + outputClassSuccess + "'>" + text + "</span><br>"));
pre.append($("<span class='" + outputClassSuccess + "'>" + long + "</span>"));
} else {
pre.append($("<span class='" + outputClassFailure + "'>" + text + "</span><br>"));
pre.append($("<span class='" + outputClassFailure + "'>" + long + "</span>"));
}
pre.scrollTop(pre[0].scrollHeight - pre.height());
}
@@ -958,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);
}
@@ -1048,8 +1089,9 @@ var getQueryParameterByName = function(name, url) {
*
* E.g. turns a null byte in the string into "\x00".
*
* Only characters 0 to 31, 127 and 255 will be escaped, that
* should leave printable characters and unicode alone.
* Characters 0 to 31 excluding 9, 10 and 13 will be escaped, as will
* 127 and 255. That should leave printable characters and unicode
* alone.
*
* Originally based on
* https://gist.github.com/mathiasbynens/1243213#gistcomment-53590
@@ -1063,7 +1105,7 @@ var escapeUnprintableCharacters = function(str) {
var charCode;
while (!isNaN(charCode = str.charCodeAt(index))) {
if (charCode < 32 || charCode == 127 || charCode == 255) {
if ((charCode < 32 && charCode != 9 && charCode != 10 && charCode != 13) || charCode == 127 || charCode == 255) {
// special hex chars
result += "\\x" + (charCode > 15 ? "" : "0") + charCode.toString(16)
} else {
+127 -26
View File
@@ -7,7 +7,7 @@ $(function() {
//~~ Logging setup
log.setLevel(CONFIG_DEBUG ? "debug" : "info");
log.setLevel(CONFIG_DEBUG ? log.levels.DEBUG : log.levels.INFO);
//~~ OctoPrint client setup
OctoPrint.options.baseurl = BASEURL;
@@ -38,7 +38,18 @@ $(function() {
browserTabVisibility: undefined,
selectedTab: undefined,
settingsOpen: false,
wizardOpen: false
wizardOpen: false,
browser: {
chrome: false,
firefox: false,
safari: false,
ie: false,
edge: false,
opera: false,
mobile: false,
desktop: false
}
};
var browserVisibilityCallbacks = [];
@@ -88,6 +99,22 @@ $(function() {
updateBrowserVisibility();
}
// determine browser - loosely based on is.js
var navigator = window.navigator;
var userAgent = (navigator && navigator.userAgent || "").toLowerCase();
var vendor = (navigator && navigator.vendor || "").toLowerCase();
exports.browser.opera = userAgent.match(/opera|opr/) != null;
exports.browser.chrome = !exports.browser.opera && /google inc/.test(vendor) && userAgent.match(/chrome|crios/) != null;
exports.browser.firefox = userAgent.match(/firefox|fxios/) != null;
exports.browser.ie = userAgent.match(/msie|trident/) != null;
exports.browser.edge = userAgent.match(/edge/) != null;
exports.browser.safari = !exports.browser.chrome && !exports.browser.edge && !exports.browser.opera && userAgent.match(/safari/) != null;
exports.browser.mobile = $.browser.mobile;
exports.browser.desktop = !exports.browser.mobile;
// exports
exports.isVisible = function() { return !isHidden() };
@@ -98,6 +125,8 @@ $(function() {
return exports;
})();
log.debug("Browser enviroment:", OctoPrint.coreui.browser);
//~~ AJAX setup
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
@@ -444,6 +473,18 @@ $(function() {
}
};
$.fn.lazyload = function() {
return this.each(function() {
if (this.tagName.toLowerCase() != "img") return;
var src = this.getAttribute("data-src");
if (src) {
this.setAttribute("src", src);
this.removeAttribute("data-src");
}
});
};
// Use bootstrap tabdrop for tabs and pills
$('.nav-pills, .nav-tabs').tabdrop();
@@ -493,7 +534,15 @@ $(function() {
}
}
//~~ view model binding
//~~ final initialization - passive login, settings fetch, view model binding
if (!_.has(viewModelMap, "settingsViewModel")) {
throw new Error("settingsViewModel is missing, can't run UI");
}
if (!_.has(viewModelMap, "loginStateViewModel")) {
throw new Error("loginStateViewModel is missing, can't run UI");
}
var bindViewModels = function() {
log.info("Going to bind " + allViewModelData.length + " view models...");
@@ -562,7 +611,8 @@ $(function() {
});
}
viewModel._unbound = viewModel._bindings != undefined && viewModel._bindings.length == 0;
viewModel._unbound = viewModel._bindings !== undefined && viewModel._bindings.length === 0;
viewModel._bound = viewModel._bindings.length > 0;
if (viewModel.hasOwnProperty("onAfterBinding")) {
viewModel.onAfterBinding();
@@ -574,6 +624,7 @@ $(function() {
// startup complete
callViewModels(allViewModels, "onStartupComplete");
setOnViewModels(allViewModels, "_startupComplete", true);
// make sure we can track the browser tab visibility
OctoPrint.coreui.onBrowserVisibilityChange(function(status) {
@@ -593,34 +644,84 @@ $(function() {
log.info("Application startup complete");
};
if (!_.has(viewModelMap, "settingsViewModel")) {
throw new Error("settingsViewModel is missing, can't run UI")
}
var fetchSettings = function() {
log.info("Finalizing application startup");
//~~ Starting up the app
callViewModels(allViewModels, "onStartup");
viewModelMap["settingsViewModel"].requestData()
.done(function() {
// There appears to be an odd race condition either in JQuery's AJAX implementation or
// the browser's implementation of XHR, causing a second GET request from inside the
// completion handler of the very same request to never get its completion handler called
// if ETag headers are present on the response (the status code of the request does NOT
// seem to matter here, only that the ETag header is present).
//
// Minimal example with which I was able to reproduce this behaviour can be found
// at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f
//
// Decoupling all consecutive calls from this done event handler hence is an easy way
// to avoid this problem. A zero timeout should do the trick nicely.
window.setTimeout(bindViewModels, 0);
});
};
log.info("Initial application setup done, connecting to server...");
/**
* The following looks a bit complicated, so let me explain...
*
* Once we connect to the server (and that also includes consecutive reconnects), the
* first thing we need to do is perform a passive login to a) establish a proper request
* session with the server and b) figure out the login status of our client. That passive
* login will be responded to with our session cookie and we must make absolutely sure that
* this cannot be overridden by any concurrent requests. E.g. if we would send the passive
* login request and also something like a settings fetch, the settings would not have the
* cookie yet, hence the server would generate a new session for that request, and if the
* response for the settings now arrives later than the passive login we'll get our
* session cookie from that login directly overwritten again. That will not only lead to
* us losing our login session with the server but also the client _thinking_ it is logged
* in when in fact it isn't. See also #1881.
*
* So what we do here is ensure that we send the passive login request _and nothing else_
* until that has been responded to and hence our session been properly established. Only
* then we may trigger stuff like the various view model callbacks that might cause
* additional requests.
*
* onServerConnect below takes care of the passive login. Only once that's completed it tells
* our DataUpdater that it's ok to trigger any callbacks in view models. On the initial
* server connect (during first initialization) we also trigger the settings fetch and
* binding proceedure once that's done, but only then.
*
* Or, as a fancy diagram: https://gist.githubusercontent.com/foosel/0cdc3a03cf5311804271f12e87293c0c/raw/abc84fdc3b13030d70961539d9c132ae39c32085/octoprint_web_startup.txt
*/
var onServerConnect = function() {
// Always perform a passive login on server (re)connect. No need for
// onServerConnect/onServerReconnect on the LoginStateViewModel with this in place.
return viewModelMap["loginStateViewModel"].requestData()
.done(function() {
// Only mark our data updater as initialized once we've done our initial
// passive login request.
//
// This is to ensure that we have no concurrent requests triggered by socket events
// overriding each other's session during app intialization
dataUpdater.initialized();
});
};
var dataUpdater = new DataUpdater(allViewModels);
dataUpdater.connect()
.done(function() {
log.info("Finalizing application startup");
// make sure we trigger onServerConnect should we dis- and reconnect to the server
dataUpdater.connectCallback = onServerConnect;
//~~ Starting up the app
callViewModels(allViewModels, "onStartup");
viewModelMap["settingsViewModel"].requestData()
.done(function() {
// There appears to be an odd race condition either in JQuery's AJAX implementation or
// the browser's implementation of XHR, causing a second GET request from inside the
// completion handler of the very same request to never get its completion handler called
// if ETag headers are present on the response (the status code of the request does NOT
// seem to matter here, only that the ETag header is present).
//
// Minimal example with which I was able to reproduce this behaviour can be found
// at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f
//
// Decoupling all consecutive calls from this done event handler hence is an easy way
// to avoid this problem. A zero timeout should do the trick nicely.
window.setTimeout(bindViewModels, 0);
});
// perform passive login first
onServerConnect().done(function() {
// then trigger a settings fetch
window.setTimeout(fetchSettings, 0);
});
});
}
);
@@ -101,7 +101,7 @@ $(function() {
self.isReady(data.flags.ready);
self.isLoading(data.flags.loading);
if (self.loginState.hasPermission(self.access.permissions.CONNECTION)() && self.previousIsOperational != self.isOperational()) {
if (self.loginState.hasPermission(self.access.permissions.CONNECTION)() && self.previousIsOperational !== self.isOperational()) {
// only open or close if the panel is visible (for admins) and
// the state just changed to avoid thwarting manual open/close
self.openOrCloseOnStateChange();
@@ -133,16 +133,14 @@ $(function() {
self.onStartup = function() {
self.requestData();
};
// when isAdmin becomes true the first time, set the panel open or
// closed based on the connection state
var subscription = self.loginState.isAdmin.subscribe(function(newValue) {
if (newValue) {
// wait until after the isAdmin state has run through all subscriptions
setTimeout(self.openOrCloseOnStateChange, 0);
subscription.dispose();
}
});
self.onUserLoggedIn = function() {
self.openOrCloseOnStateChange();
};
self.onUserLoggedOut = function() {
self.openOrCloseOnStateChange();
};
}
@@ -38,6 +38,8 @@ $(function() {
self.additionalControls = [];
self.webcamDisableTimeout = undefined;
self.webcamLoaded = ko.observable(false);
self.webcamError = ko.observable(false);
self.keycontrolActive = ko.observable(false);
self.keycontrolHelpActive = ko.observable(false);
@@ -48,6 +50,14 @@ $(function() {
return self.keycontrolActive() && self.keycontrolPossible();
});
self.webcamRatioClass = ko.pureComputed(function() {
if (self.settings.webcam_streamRatio() == "4:3") {
return "ratio43";
} else {
return "ratio169";
}
});
self.settings.printerProfiles.currentProfileData.subscribe(function () {
self._updateExtruderCount();
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount);
@@ -344,43 +354,21 @@ $(function() {
self.requestData();
};
self.updateRotatorWidth = function() {
var webcamImage = $("#webcam_image");
if (self.settings.webcam_rotate90()) {
if (webcamImage.width() > 0) {
$("#webcam_rotator").css("height", webcamImage.width());
} else {
webcamImage.off("load.rotator");
webcamImage.on("load.rotator", function() {
$("#webcam_rotator").css("height", webcamImage.width());
webcamImage.off("load.rotator");
});
}
} else {
$("#webcam_rotator").css("height", "");
}
};
self.onSettingsBeforeSave = self.updateRotatorWidth;
self._isSafari = function() {
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
return is_safari && !is_chrome;
}
self._disableWebcam = function() {
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
// more load by the constant connection creation than by the actual webcam stream
// safari bug doesn't release the mjpeg stream, so we just disable this for safari.
if (self._isSafari()) {
if (OctoPrint.coreui.browser.safari) {
return;
}
var timeout = self.settings.webcam_streamTimeout() || 5;
self.webcamDisableTimeout = setTimeout(function () {
log.debug("Unloading webcam stream");
$("#webcam_image").attr("src", "");
}, 5000);
self.webcamLoaded(false);
}, timeout * 1000);
};
self._enableWebcam = function() {
@@ -395,7 +383,7 @@ $(function() {
var currentSrc = webcamImage.attr("src");
// safari bug doesn't release the mjpeg stream, so we just set it up the once
if (self._isSafari() && currentSrc != undefined) {
if (OctoPrint.coreui.browser.safari && currentSrc != undefined) {
return;
}
@@ -408,11 +396,24 @@ $(function() {
}
newSrc += new Date().getTime();
self.updateRotatorWidth();
self.webcamLoaded(false);
self.webcamError(false);
webcamImage.attr("src", newSrc);
}
};
self.onWebcamLoaded = function() {
log.debug("Webcam stream loaded");
self.webcamLoaded(true);
self.webcamError(false);
};
self.onWebcamErrored = function() {
log.debug("Webcam stream failed to load/disabled");
self.webcamLoaded(false);
self.webcamError(true);
};
self.onTabChange = function (current, previous) {
if (current == "#control") {
self._enableWebcam();
@@ -438,6 +439,7 @@ $(function() {
self.additionalControls = additionalControls;
self.rerenderControls();
}
self._enableWebcam();
};
self.onFocus = function (data, event) {
+73 -47
View File
@@ -60,6 +60,14 @@ $(function() {
self.localTarget = undefined;
self.sdTarget = undefined;
self.dropOverlay = undefined;
self.dropZone = undefined;
self.dropZoneLocal = undefined;
self.dropZoneSd = undefined;
self.dropZoneBackground = undefined;
self.dropZoneLocalBackground = undefined;
self.dropZoneSdBackground = undefined;
self.ignoreUpdatedFilesEvent = false;
self.addingFolder = ko.observable(false);
@@ -400,14 +408,21 @@ $(function() {
}
};
self.loadFile = function(file, printAfterLoad) {
if (!file) {
self.loadFile = function(data, printAfterLoad) {
if (!data) {
return;
}
var withinPrintDimensions = self.evaluatePrintDimensions(file, true);
var print = printAfterLoad && withinPrintDimensions;
OctoPrint.files.select(file.origin, file.path, print);
if (printAfterLoad && self.listHelper.isSelected(data) && self.enablePrint(data)) {
// file was already selected, just start the print job
OctoPrint.job.start();
} else {
// select file, start print job (if requested and within dimensions)
var withinPrintDimensions = self.evaluatePrintDimensions(data, true);
var print = printAfterLoad && withinPrintDimensions;
OctoPrint.files.select(data.origin, data.path, print);
}
};
self.removeFile = function(file, event) {
@@ -456,13 +471,13 @@ $(function() {
if (event) {
var element = $(event.currentTarget);
if (element.length) {
var icon = $("i.icon-trash", element);
var icon = $("i.fa-trash-o", element);
if (icon.length) {
activateSpinner = function() {
icon.removeClass("icon-trash").addClass("icon-spinner icon-spin");
icon.removeClass("fa-trash-o").addClass("fa-spinner fa-spin");
};
finishSpinner = function() {
icon.removeClass("icon-spinner icon-spin").addClass("icon-trash");
icon.removeClass("fa-spinner fa-spin").addClass("fa-trash-o");
};
}
}
@@ -550,9 +565,13 @@ $(function() {
};
self.enableSelect = function(data) {
var isLoadActionPossible = self.isLoadActionPossible();
return isLoadActionPossible && !self.listHelper.isSelected(data);
return self.isLoadAndPrintActionPossible() && !self.listHelper.isSelected(data);
}
self.enablePrint = function(data) {
return self.loginState.hasPermission(self.access.permissions.PRINT)() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading());
};
self.enableSelectAndPrint = function(data, printAfterSelect) {
var isLoadAndPrintActionPossible = self.isLoadAndPrintActionPossible();
return isLoadAndPrintActionPossible && !self.listHelper.isSelected(data);
@@ -829,15 +848,26 @@ $(function() {
}
self.sdTarget = $("#drop_sd");
self.dropOverlay = $("#drop_overlay");
self.dropZone = $("#drop");
self.dropZoneLocal = $("#drop_locally");
self.dropZoneSd = $("#drop_sd");
self.dropZoneBackground = $("#drop_background");
self.dropZoneLocalBackground = $("#drop_locally_background");
self.dropZoneSdBackground = $("#drop_sd_background");
self.dropOverlay.on('drop', self._forceEndDragNDrop);
function evaluateDropzones() {
var enableLocal = self.loginState.hasPermission(self.access.permissions.UPLOAD)();
var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady();
var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady() && !self.isPrinting();
self._setDropzone("local", enableLocal);
self._setDropzone("sdcard", enableSd);
}
self.loginState.currentUser.subscribe(evaluateDropzones);
self.printerState.isSdReady.subscribe(evaluateDropzones);
self.isPrinting.subscribe(evaluateDropzones);
evaluateDropzones();
self.requestData();
@@ -980,10 +1010,12 @@ $(function() {
self._enableDragNDrop = function(enable) {
if (enable) {
$(document).bind("dragover", self._handleDragNDrop);
$(document).bind("dragenter", self._handleDragNDrop);
$(document).bind("dragleave", self._endDragNDrop);
log.debug("Enabled drag-n-drop");
} else {
$(document).unbind("dragover", self._handleDragNDrop);
$(document).unbind("dragenter", self._handleDragNDrop);
$(document).unbind("dragleave", self._endDragNDrop);
log.debug("Disabled drag-n-drop");
}
};
@@ -1056,34 +1088,35 @@ $(function() {
self._setProgressBar(progress, uploaded ? gettext("Saving ...") : gettext("Uploading ..."), uploaded);
};
self._handleDragNDrop = function (e) {
var dropOverlay = $("#drop_overlay");
var dropZone = $("#drop");
var dropZoneLocal = $("#drop_locally");
var dropZoneSd = $("#drop_sd");
var dropZoneBackground = $("#drop_background");
var dropZoneLocalBackground = $("#drop_locally_background");
var dropZoneSdBackground = $("#drop_sd_background");
var timeout = window.dropZoneTimeout;
self._dragNDropTarget = null;
self._forceEndDragNDrop = function () {
self.dropOverlay.removeClass("in");
if (self.dropZoneLocal) self.dropZoneLocalBackground.removeClass("hover");
if (self.dropZoneSd) self.dropZoneSdBackground.removeClass("hover");
if (self.dropZone) self.dropZoneBackground.removeClass("hover");
self._dragNDropTarget = null;
};
if (!timeout) {
dropOverlay.addClass('in');
} else {
clearTimeout(timeout);
}
self._endDragNDrop = function (e) {
if (e.target != self._dragNDropTarget) return;
self._forceEndDragNDrop();
};
self._handleDragNDrop = function (e) {
self.dropOverlay.addClass('in');
var foundLocal = false;
var foundSd = false;
var found = false;
var node = e.target;
do {
if (dropZoneLocal && node === dropZoneLocal[0]) {
if (self.dropZoneLocal && node === self.dropZoneLocal[0]) {
foundLocal = true;
break;
} else if (dropZoneSd && node === dropZoneSd[0]) {
} else if (self.dropZoneSd && node === self.dropZoneSd[0]) {
foundSd = true;
break;
} else if (dropZone && node === dropZone[0]) {
} else if (self.dropZone && node === self.dropZone[0]) {
found = true;
break;
}
@@ -1091,26 +1124,19 @@ $(function() {
} while (node != null);
if (foundLocal) {
dropZoneLocalBackground.addClass("hover");
dropZoneSdBackground.removeClass("hover");
} else if (foundSd && self.printerState.isSdReady()) {
dropZoneSdBackground.addClass("hover");
dropZoneLocalBackground.removeClass("hover");
self.dropZoneLocalBackground.addClass("hover");
self.dropZoneSdBackground.removeClass("hover");
} else if (foundSd && self.printerState.isSdReady() && !self.isPrinting()) {
self.dropZoneSdBackground.addClass("hover");
self.dropZoneLocalBackground.removeClass("hover");
} else if (found) {
dropZoneBackground.addClass("hover");
self.dropZoneBackground.addClass("hover");
} else {
if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover");
if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover");
if (dropZoneBackground) dropZoneBackground.removeClass("hover");
if (self.dropZoneLocalBackground) self.dropZoneLocalBackground.removeClass("hover");
if (self.dropZoneSdBackground) self.dropZoneSdBackground.removeClass("hover");
if (self.dropZoneBackground) self.dropZoneBackground.removeClass("hover");
}
window.dropZoneTimeout = setTimeout(function () {
window.dropZoneTimeout = null;
dropOverlay.removeClass("in");
if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover");
if (dropZoneSd) dropZoneSdBackground.removeClass("hover");
if (dropZone) dropZoneBackground.removeClass("hover");
}, 100);
self._dragNDropTarget = e.target;
}
}
@@ -47,6 +47,8 @@ $(function() {
self.renderer_zoomOnModel = ko.observable(false);
self.renderer_showMoves = ko.observable(true);
self.renderer_showRetracts = ko.observable(true);
self.renderer_showBoundingBox = ko.observable(false);
self.renderer_showFullSize = ko.observable(false);
self.renderer_extrusionWidthEnabled = ko.observable(false);
self.renderer_extrusionWidth = ko.observable(2);
self.renderer_showNext = ko.observable(false);
@@ -66,6 +68,8 @@ $(function() {
centerViewport: self.renderer_centerViewport(),
showMoves: self.renderer_showMoves(),
showRetracts: self.renderer_showRetracts(),
showBoundingBox: self.renderer_showBoundingBox(),
showFullSize: self.renderer_showFullSize(),
extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
showNextLayer: self.renderer_showNext(),
showPreviousLayer: self.renderer_showPrevious(),
@@ -78,7 +82,8 @@ $(function() {
var reader = {
sortLayers: self.reader_sortLayers(),
purgeEmptyLayers: self.reader_hideEmptyLayers()
purgeEmptyLayers: self.reader_hideEmptyLayers(),
ignoreOutsideBed: true
};
if (additionalReaderOptions) {
_.extend(reader, additionalReaderOptions);
@@ -96,6 +101,8 @@ $(function() {
self.renderer_zoomOnModel.subscribe(self.synchronizeOptions);
self.renderer_showMoves.subscribe(self.synchronizeOptions);
self.renderer_showRetracts.subscribe(self.synchronizeOptions);
self.renderer_showBoundingBox.subscribe(self.synchronizeOptions);
self.renderer_showFullSize.subscribe(self.synchronizeOptions);
self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions);
self.renderer_extrusionWidth.subscribe(self.synchronizeOptions);
self.renderer_showNext.subscribe(self.synchronizeOptions);
@@ -121,10 +128,13 @@ $(function() {
}
var bedDimensions = self._retrieveBedDimensions(currentProfileData);
if (toolOffsets) {
if (bedDimensions) {
GCODE.ui.updateOptions({
renderer: {
bed: bedDimensions
},
reader: {
bed: bedDimensions
}
});
}
@@ -139,6 +149,14 @@ $(function() {
}
});
self.settings.feature_g90InfluencesExtruder.subscribe(function() {
GCODE.ui.updateOptions({
reader: {
g90InfluencesExtruder: self.settings.feature_g90InfluencesExtruder()
}
});
});
self._retrieveBedDimensions = function(currentProfileData) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
@@ -240,7 +258,7 @@ $(function() {
self._configureLayerSlider(layerSliderElement);
self._configureLayerCommandSlider(commandSliderElement);
self.settings.requestData()
self.settings.firstRequest
.done(function() {
var initResult = GCODE.ui.init({
container: "#gcode_canvas",
@@ -329,6 +347,7 @@ $(function() {
result: response
}
};
GCODE.renderer.clear();
GCODE.gCodeReader.loadFile(par);
if (self.layerSlider != undefined) {
@@ -399,7 +418,7 @@ $(function() {
self.selectedFile.date(data.job.file.date);
self.selectedFile.size(data.job.file.size);
if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || ($.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) {
if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || (OctoPrint.coreui.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) {
self.waitForApproval(true);
self.loadedFilepath = undefined;
self.loadedFileDate = undefined;
@@ -13,6 +13,7 @@ $(function() {
self.isUser = ko.observable(false);
self.allViewModels = undefined;
self.startupDeferred = $.Deferred();
self.currentUser = ko.observable(undefined);
@@ -37,28 +38,45 @@ $(function() {
});
self.reloadUser = function() {
if (self.currentUser() == undefined) {
if (self.currentUser() === undefined) {
return;
}
OctoPrint.access.users.get(self.currentUser().name)
return OctoPrint.access.users.get(self.currentUser().name)
.done(self.updateCurrentUserData);
};
self.requestData = function() {
OctoPrint.browser.passiveLogin()
return OctoPrint.browser.passiveLogin()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
if (response && response.name) {
self.loggedIn(true);
self.updateCurrentUserData(response);
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
var process = function() {
var currentLoggedIn = self.loggedIn();
if (response && response.name) {
self.loggedIn(true);
self.updateCurrentUserData(response);
if (!currentLoggedIn) {
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
log.info("User " + response.name + " logged in")
}
} else {
self.loggedIn(false);
self.resetCurrentUserData();
if (currentLoggedIn) {
callViewModels(self.allViewModels, "onUserLoggedOut");
log.info("User logged out");
}
}
};
if (self.startupDeferred !== undefined) {
// Make sure we only fire our "onUserLogged(In|Out)" message after the application
// has started up.
self.startupDeferred.done(process);
} else {
self.loggedIn(false);
self.resetCurrentUserData();
callViewModels(self.allViewModels, "onUserLoggedOut");
process();
}
};
@@ -108,7 +126,7 @@ $(function() {
};
self.logout = function() {
OctoPrint.browser.logout()
return OctoPrint.browser.logout()
.done(function(response) {
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
self.fromResponse(response);
@@ -129,11 +147,8 @@ $(function() {
self.onAllBound = function(allViewModels) {
self.allViewModels = allViewModels;
};
self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() {
if (self.allViewModels == undefined) return;
self.requestData();
self.startupDeferred.resolve();
self.startupDeferred = undefined;
};
self.onStartup = function() {
@@ -453,7 +453,7 @@ $(function() {
};
self.requestData = function() {
OctoPrint.printerprofiles.list()
return OctoPrint.printerprofiles.list()
.done(self.fromResponse);
};
@@ -476,8 +476,16 @@ $(function() {
});
self.profiles.updateItems(items);
self.defaultProfile(defaultProfile);
self.currentProfile(currentProfile);
self.currentProfileData(currentProfileData);
if (currentProfile && currentProfileData) {
self.currentProfile(currentProfile);
self.currentProfileData(currentProfileData);
} else {
// shouldn't normally happen, but just to not have anything else crash...
log.warn("Current printer profile could not be detected, using default values");
self.currentProfile("");
self.currentProfileData(ko.mapping.fromJS(cleanProfile(), self.currentProfileData));
}
};
self.addProfile = function(callback) {
@@ -504,7 +512,10 @@ $(function() {
self.requestInProgress(true);
OctoPrint.printerprofiles.delete(data.id, {url: data.resource})
.done(function() {
self.requestData();
self.requestData()
.always(function() {
self.requestInProgress(false);
});
})
.fail(function(xhr) {
var text;
@@ -514,8 +525,6 @@ $(function() {
text = gettext("There was unexpected error while removing the printer profile, please consult the logs.");
}
new PNotify({title: gettext("Could not delete profile"), text: text, type: "error", hide: false});
})
.always(function() {
self.requestInProgress(false);
});
};
@@ -535,13 +544,14 @@ $(function() {
if (callback !== undefined) {
callback();
}
self.requestData();
self.requestData()
.always(function() {
self.requestInProgress(false);
});
})
.fail(function() {
var text = gettext("There was unexpected error while updating the printer profile, please consult the logs.");
new PNotify({title: gettext("Could not update profile"), text: text, type: "error", hide: false});
})
.always(function() {
self.requestInProgress(false);
});
};
@@ -7,6 +7,11 @@ $(function() {
self.printerProfiles = parameters[2];
self.about = parameters[3];
// use this promise to do certain things once the SettingsViewModel has processed
// its first request
var firstRequest = $.Deferred();
self.firstRequest = firstRequest.promise();
self.allViewModels = [];
self.receiving = ko.observable(false);
@@ -91,6 +96,8 @@ $(function() {
}
};
self.webcam_available_ratios = ["16:9", "4:3"];
var auto_locale = {language: "_default", display: gettext("Autodetect from browser"), english: undefined};
self.locales = ko.observableArray([auto_locale].concat(_.sortBy(_.values(AVAILABLE_LOCALES), function(n) {
return n.display;
@@ -110,6 +117,8 @@ $(function() {
self.printer_defaultExtrusionLength = ko.observable(undefined);
self.webcam_streamUrl = ko.observable(undefined);
self.webcam_streamRatio = ko.observable(undefined);
self.webcam_streamTimeout = ko.observable(undefined);
self.webcam_snapshotUrl = ko.observable(undefined);
self.webcam_ffmpegPath = ko.observable(undefined);
self.webcam_bitrate = ko.observable(undefined);
@@ -140,6 +149,7 @@ $(function() {
self.feature_firmwareDetection = ko.observable(undefined);
self.feature_printCancelConfirmation = ko.observable(undefined);
self.feature_blockWhileDwelling = ko.observable(undefined);
self.feature_g90InfluencesExtruder = ko.observable(undefined);
self.serial_port = ko.observable();
self.serial_baudrate = ko.observable();
@@ -151,6 +161,7 @@ $(function() {
self.serial_timeoutCommunication = ko.observable(undefined);
self.serial_timeoutTemperature = ko.observable(undefined);
self.serial_timeoutTemperatureTargetSet = ko.observable(undefined);
self.serial_timeoutTemperatureAutoreport = ko.observable(undefined);
self.serial_timeoutSdStatus = ko.observable(undefined);
self.serial_log = ko.observable(undefined);
self.serial_additionalPorts = ko.observable(undefined);
@@ -179,9 +190,13 @@ $(function() {
self.scripts_gcode_beforePrintResumed = ko.observable(undefined);
self.scripts_gcode_afterPrinterConnected = ko.observable(undefined);
self.scripts_gcode_beforePrinterDisconnected = ko.observable(undefined);
self.scripts_gcode_afterToolChange = ko.observable(undefined);
self.scripts_gcode_beforeToolChange = ko.observable(undefined);
self.temperature_profiles = ko.observableArray(undefined);
self.temperature_cutoff = ko.observable(undefined);
self.temperature_sendAutomatically = ko.observable(undefined);
self.temperature_sendAutomaticallyAfter = ko.observable(undefined);
self.system_actions = ko.observableArray([]);
@@ -224,37 +239,48 @@ $(function() {
self.terminalFilters.remove(filter);
};
self.testWebcamStreamUrlBusy = ko.observable(false);
self.testWebcamStreamUrl = function() {
if (!self.webcam_streamUrl()) {
return;
}
if (self.testWebcamStreamUrlBusy()) {
return;
}
var text = gettext("If you see your webcam stream below, the entered stream URL is ok.");
var image = $('<img src="' + self.webcam_streamUrl() + '">');
var message = $("<p></p>")
.append(text)
.append(image);
self.testWebcamStreamUrlBusy(true);
showMessageDialog({
title: gettext("Stream test"),
message: message
message: message,
onclose: function() {
self.testWebcamStreamUrlBusy(false);
}
});
};
self.testWebcamSnapshotUrlBusy = ko.observable(false);
self.testWebcamSnapshotUrl = function(viewModel, event) {
if (!self.webcam_snapshotUrl()) {
return;
}
var target = $(event.target);
target.prepend('<i class="icon-spinner icon-spin"></i> ');
if (self.testWebcamSnapshotUrlBusy()) {
return;
}
var errorText = gettext("Could not retrieve snapshot URL, please double check the URL");
var errorTitle = gettext("Snapshot test failed");
self.testWebcamSnapshotUrlBusy(true);
OctoPrint.util.testUrl(self.webcam_snapshotUrl(), {method: "GET", response: "bytes"})
.done(function(response) {
$("i.icon-spinner", target).remove();
if (!response.result) {
showMessageDialog({
title: errorTitle,
@@ -274,23 +300,34 @@ $(function() {
var text = gettext("If you see your webcam snapshot picture below, the entered snapshot URL is ok.");
showMessageDialog({
title: gettext("Snapshot test"),
message: $('<p>' + text + '</p><p><img src="data:' + mimeType + ';base64,' + content + '" /></p>')
message: $('<p>' + text + '</p><p><img src="data:' + mimeType + ';base64,' + content + '" /></p>'),
onclose: function() {
self.testWebcamSnapshotUrlBusy(false);
}
});
})
.fail(function() {
$("i.icon-spinner", target).remove();
showMessageDialog({
title: errorTitle,
message: errorText
message: errorText,
onclose: function() {
self.testWebcamSnapshotUrlBusy(false);
}
});
});
};
self.testWebcamFfmpegPathBusy = ko.observable(false);
self.testWebcamFfmpegPath = function() {
if (!self.webcam_ffmpegPath()) {
return;
}
if (self.testWebcamFfmpegPathBusy()) {
return;
}
self.testWebcamFfmpegPathBusy(true);
OctoPrint.util.testExecutable(self.webcam_ffmpegPath())
.done(function(response) {
if (!response.result) {
@@ -306,6 +343,9 @@ $(function() {
}
self.webcam_ffmpegPathOk(response.result);
self.webcam_ffmpegPathBroken(!response.result);
})
.always(function() {
self.testWebcamFfmpegPathBusy(false);
});
};
@@ -730,6 +770,8 @@ $(function() {
};
mapToObservables(serverChangedData, specialMappings, clientChangedData);
firstRequest.resolve();
};
self.saveData = function (data, successCallback, setAsSending) {
@@ -844,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();
}
}
@@ -7,7 +7,7 @@ $(function() {
self.access = parameters[2];
self._createToolEntry = function() {
return {
var entry = {
name: ko.observable(),
key: ko.observable(),
actual: ko.observable(0),
@@ -15,14 +15,66 @@ $(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;
// TODO: find some nicer way to update plot AFTER graph becomes visible
self.loginStateSubscription = undefined;
self.tools = ko.observableArray([]);
self.hasBed = ko.observable(true);
self.bedTemp = self._createToolEntry();
self.bedTemp["name"](gettext("Bed"));
self.bedTemp["key"]("bed");
@@ -94,7 +146,7 @@ $(function() {
if (!self._printerProfileInitialized) {
self._triggerBacklog();
}
self.updatePlot();
self.updatePlot(false);
};
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
self._printerProfileUpdated();
@@ -124,39 +176,10 @@ $(function() {
});
self.temperatures = [];
self.plotOptions = {
yaxis: {
min: 0,
max: 310,
ticks: 10
},
xaxis: {
mode: "time",
minTickSize: [2, "minute"],
tickFormatter: function(val, axis) {
if (val == undefined || val == 0)
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
// current time in milliseconds in UTC
var timestampUtc = Date.now();
// calculate difference in milliseconds
var diff = timestampUtc - val;
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins == 0)
return gettext("just now");
else
return "- " + diffInMins + " " + gettext("min");
}
},
legend: {
position: "sw",
noColumns: 2,
backgroundOpacity: 0
}
};
self.plot = undefined;
self.plotHoverPos = undefined;
self.plotLegendTimeout = undefined;
self.fromCurrentData = function(data) {
self._processStateData(data.state);
@@ -222,12 +245,12 @@ $(function() {
if (!CONFIG_TEMPERATURE_GRAPH) return;
self.temperatures = self._processTemperatureData(serverTime, data, self.temperatures);
self.updatePlot();
self.updatePlot(false);
};
self._processTemperatureHistoryData = function(serverTime, data) {
self.temperatures = self._processTemperatureData(serverTime, data);
self.updatePlot();
self.updatePlot(false);
};
self._processOffsetData = function(data) {
@@ -286,7 +309,9 @@ $(function() {
return result;
};
self.updatePlot = function() {
self.updatePlot = function(force) {
force = force == undefined ? true : force;
var graph = $("#temperature-graph");
if (graph.length) {
var data = [];
@@ -295,6 +320,8 @@ $(function() {
var maxTemps = [310/1.1];
var showFahrenheit = self._shallShowFahrenheit();
_.each(_.keys(heaterOptions), function(type) {
if (type == "bed" && !self.hasBed()) {
return;
@@ -308,9 +335,6 @@ $(function() {
targets = self.temperatures[type].target;
}
var showFahrenheit = (self.settingsViewModel.settings !== undefined )
? self.settingsViewModel.settings.appearance.showFahrenheitAlso()
: false;
var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1], showFahrenheit) : "-";
var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1], showFahrenheit) : "-";
@@ -328,11 +352,115 @@ $(function() {
maxTemps.push(self.getMaxTemp(actuals, targets));
});
self.plotOptions.yaxis.max = Math.max.apply(null, maxTemps) * 1.1;
$.plot(graph, data, self.plotOptions);
if (!self.plot || force) {
// we don't have a plot yet, we need to set stuff up
var options = {
yaxis: {
min: 0,
max: Math.max(Math.max.apply(null, maxTemps) * 1.1, 310),
ticks: 10
},
xaxis: {
mode: "time",
minTickSize: [2, "minute"],
tickFormatter: function(val, axis) {
if (val == undefined || val == 0)
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
// current time in milliseconds in UTC
var timestampUtc = Date.now();
// calculate difference in milliseconds
var diff = timestampUtc - val;
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins == 0)
return gettext("just now");
else
return "- " + diffInMins + " " + gettext("min");
}
},
legend: {
position: "sw",
noColumns: 2,
backgroundOpacity: 0
}
};
if (!OctoPrint.coreui.browser.mobile) {
options["crosshair"] = { mode: "x" };
options["grid"] = { hoverable: true, autoHighlight: false };
}
self.plot = $.plot(graph, data, options);
} else {
// graph already active, let's just update the data
self.plot.setData(data);
self.plot.getAxes().yaxis.max = Math.max(Math.max.apply(null, maxTemps) * 1.1, 310);
self.updateLegend(self._replaceLegendLabel);
self.plot.draw();
}
}
};
self.updateLegend = function(replaceLegendLabel) {
self.plotLegendTimeout = undefined;
var resetLegend = function() {
_.each(dataset, function(series, index) {
var value = series.data && series.data.length ? series.data[series.data.length - 1][1] : undefined;
replaceLegendLabel(index, series, value);
});
};
var pos = self.plotHoverPos;
if (pos && !OctoPrint.coreui.browser.mobile) {
// we got a hover position, let's see what we need to do with that
var i;
var axes = self.plot.getAxes();
var dataset = self.plot.getData();
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
// position outside of the graph, show latest temperature in legend
resetLegend();
} else {
// position inside the graph, determine temperature at point and display that in the legend
_.each(dataset, function(series, index) {
for (i = 0; i < series.data.length; i++) {
if (series.data[i][0] > pos.x) {
break;
}
}
var y;
var p1 = series.data[i - 1];
var p2 = series.data[i];
if (p1 === undefined && p2 === undefined) {
y = undefined;
} else if (p1 === undefined) {
y = p2[1];
} else if (p2 === undefined) {
y = p1[1];
} else {
y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
}
replaceLegendLabel(index, series, y, true);
});
}
} else {
resetLegend();
}
// update the grid
self.plot.setupGrid();
};
self.getMaxTemp = function(actuals, targets) {
var pair;
var maxTemp = 0;
@@ -349,66 +477,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);
}
};
@@ -433,21 +686,70 @@ $(function() {
return OctoPrint.printer.setBedTemperatureOffset(parseInt(offset));
};
self._replaceLegendLabel = function(index, series, value, emph) {
var showFahrenheit = self._shallShowFahrenheit();
var temp = formatTemperature(value, showFahrenheit);
if (emph) {
temp = "<em>" + temp + "</em>";
}
series.label = series.label.replace(/:.*/, ": " + temp);
};
self._shallShowFahrenheit = function() {
return (self.settingsViewModel.settings !== undefined )
? self.settingsViewModel.settings.appearance.showFahrenheitAlso()
: false;
};
self.handleEnter = function(event, type, item) {
if (event.keyCode == 13) {
if (type == "target") {
self.setTarget(item);
self.setTarget(item)
.done(function() {
event.target.blur();
});
} else if (type == "offset") {
self.setOffset(item);
self.confirmChangeOffset();
}
}
};
self.handleFocus = function(event, type, item) {
if (type == "target") {
var value = item.newTarget();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
item.newTarget(item.target());
}
event.target.select();
} else if (type == "offset") {
event.target.select();
}
};
self.onAfterTabChange = function(current, previous) {
if (current != "#temp") {
return;
}
self.updatePlot();
self.updatePlot(false);
};
self.onStartup = function() {
var graph = $("#temperature-graph");
if (graph.length && !OctoPrint.coreui.browser.mobile) {
graph.bind("plothover", function (event, pos, item) {
self.plotHoverPos = pos;
if (!self.plotLegendTimeout) {
self.plotLegendTimeout = window.setTimeout(function() {
self.updateLegend(self._replaceLegendLabel)
}, 50);
}
});
}
};
self.onStartup = function() {
self.changeOffsetDialog = $("#change_offset_dialog");
};
self.onStartupComplete = function() {
@@ -459,6 +761,6 @@ $(function() {
OCTOPRINT_VIEWMODELS.push([
TemperatureViewModel,
["loginStateViewModel", "settingsViewModel", "accessViewModel"],
["#temp", "#temp_link"]
["#temp", "#change_offset_dialog"]
]);
});
@@ -36,8 +36,10 @@ $(function() {
self.enableFancyFunctionality = ko.observable(true);
self.disableTerminalLogDuringPrinting = ko.observable(false);
self.acceptableTime = 500;
self.acceptableFancyTime = 500;
self.acceptableUnfancyTime = 300;
self.reenableTimeout = 5000;
self.forceFancyFunctionality = ko.observable(false);
self.forceTerminalLogDuringPrinting = ko.observable(false);
@@ -123,23 +125,63 @@ $(function() {
self.updateFilterRegex();
});
self._reenableFancyTimer = undefined;
self._reenableUnfancyTimer = undefined;
self._disableFancy = function(difference) {
log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality");
if (self._reenableFancyTimer) {
window.clearTimeout(self._reenableFancyTimer);
self._reenableFancyTimer = undefined;
}
self.enableFancyFunctionality(false);
};
self._reenableFancy = function(difference) {
if (self._reenableFancyTimer) return;
self._reenableFancyTimer = window.setTimeout(function() {
log.info("Terminal: Client speed recovered, enabling fancy terminal functionality");
self.enableFancyFunctionality(true);
}, self.reenableTimeout);
};
self._disableUnfancy = function(difference) {
log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing");
if (self._reenableUnfancyTimer) {
window.clearTimeout(self._reenableUnfancyTimer);
self._reenableUnfancyTimer = undefined;
}
self.disableTerminalLogDuringPrinting(true);
};
self._reenableUnfancy = function() {
if (self._reenableUnfancyTimer) return;
self._reenableUnfancyTimer = window.setTimeout(function() {
log.info("Terminal: Client speed recovered, enabling terminal output during printing");
self.disableTerminalLogDuringPrinting(false);
}, self.reenableTimeout);
};
self.fromCurrentData = function(data) {
self._processStateData(data.state);
var start = new Date().getTime();
self._processCurrentLogData(data.logs);
var end = new Date().getTime();
var difference = end - start;
if (self.enableFancyFunctionality()) {
if (difference > self.acceptableTime) {
self.enableFancyFunctionality(false);
log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality");
// fancy enabled -> check if we need to disable fancy
if (difference >= self.acceptableFancyTime) {
self._disableFancy(difference);
}
} else if (!self.disableTerminalLogDuringPrinting()) {
// fancy disabled, unfancy not -> check if we need to disable unfancy or re-enable fancy
if (difference >= self.acceptableUnfancyTime) {
self._disableUnfancy(difference);
} else if (difference < self.acceptableFancyTime / 2.0) {
self._reenableFancy(difference);
}
} else {
if (!self.disableTerminalLogDuringPrinting() && difference > self.acceptableUnfancyTime) {
self.disableTerminalLogDuringPrinting(true);
log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing");
// fancy & unfancy disabled -> check if we need to re-enable unfancy
if (difference < self.acceptableUnfancyTime / 2.0) {
self._reenableUnfancy(difference);
}
}
};
@@ -11,7 +11,7 @@ $(function() {
self.defaultPostRoll = 0;
self.defaultInterval = 10;
self.defaultRetractionZHop = 0;
self.defaultCapturePostroll = true;
self.defaultCapturePostRoll = true;
self.timelapseType = ko.observable(undefined);
self.timelapseTimedInterval = ko.observable(self.defaultInterval);
@@ -52,10 +52,6 @@ $(function() {
return self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN)() && self.isDirty() && self.isOperational() && !self.isPrinting();
});
self.isOperational.subscribe(function() {
self.requestData();
});
self.timelapseType.subscribe(function() {
self.isDirty(true);
});
@@ -163,18 +159,20 @@ $(function() {
// timelapse config
self.timelapseType(config.type);
if (config.type == "timed") {
if (config.interval != undefined && config.interval > 0) {
self.timelapseTimedInterval(config.interval);
}
if (config.type == "timed" && config.interval != undefined && config.interval > 0) {
self.timelapseTimedInterval(config.interval);
} else {
self.timelapseTimedInterval(self.defaultInterval);
}
if (config.type == "zchange") {
if (config.retractionZHop != undefined && config.retractionZHop > 0) {
self.timelapseRetractionZHop(config.retractionZHop);
}
if (config.type == "timed" && config.capturePostRoll != undefined){
self.timelapseCapturePostRoll(config.capturePostRoll);
} else {
self.timelapseCapturePostRoll(self.defaultCapturePostRoll);
}
if (config.type == "zchange" && config.retractionZHop != undefined && config.retractionZHop > 0) {
self.timelapseRetractionZHop(config.retractionZHop);
} else {
self.timelapseRetractionZHop(self.defaultRetractionZHop);
}
@@ -191,12 +189,6 @@ $(function() {
self.timelapseFps(self.defaultFps);
}
if (config.capturePostRoll != undefined){
self.timelapseCapturePostRoll(config.capturePostRoll);
} else {
self.timelapseCapturePostRoll(self.defaultCapturePostRoll);
}
self.persist(false);
self.isDirty(false);
};
@@ -240,6 +232,16 @@ $(function() {
.done(function() {
self.markedForFileDeletion.remove(filename);
self.requestData()
})
.fail(function(jqXHR) {
var html = "<p>" + _.sprintf(gettext("Failed to remove timelapse %(name)s.</p><p>Please consult octoprint.log for details.</p>"), {name: filename});
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + jqXHR.responseText + '</pre>');
new PNotify({
title: gettext("Could not remove timelapse"),
text: html,
type: "error",
hide: false
});
});
};
@@ -308,7 +310,7 @@ $(function() {
self._bulkRemove = function(files, type) {
var title, message, handler;
if (type == "files") {
if (type === "files") {
title = gettext("Deleting timelapse files");
message = _.sprintf(gettext("Deleting %(count)d timelapse files..."), {count: files.length});
handler = function(filename) {
@@ -316,11 +318,13 @@ $(function() {
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
})
.fail(function() {
deferred.notify(_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}), false);
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
}
} else if (type == "unrendered") {
} else if (type === "unrendered") {
title = gettext("Deleting unrendered timelapses");
message = _.sprintf(gettext("Deleting %(count)d unrendered timelapses..."), {count: files.length});
handler = function(filename) {
@@ -0,0 +1,176 @@
/* Flot plugin for showing crosshairs when the mouse hovers over the plot.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin supports these options:
crosshair: {
mode: null or "x" or "y" or "xy"
color: color
lineWidth: number
}
Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
crosshair that lets you trace the values on the x axis, "y" enables a
horizontal crosshair and "xy" enables them both. "color" is the color of the
crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
the drawn lines (default is 1).
The plugin also adds four public methods:
- setCrosshair( pos )
Set the position of the crosshair. Note that this is cleared if the user
moves the mouse. "pos" is in coordinates of the plot and should be on the
form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
axes), which is coincidentally the same format as what you get from a
"plothover" event. If "pos" is null, the crosshair is cleared.
- clearCrosshair()
Clear the crosshair.
- lockCrosshair(pos)
Cause the crosshair to lock to the current location, no longer updating if
the user moves the mouse. Optionally supply a position (passed on to
setCrosshair()) to move it to.
Example usage:
var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
$("#graph").bind( "plothover", function ( evt, position, item ) {
if ( item ) {
// Lock the crosshair to the data point being hovered
myFlot.lockCrosshair({
x: item.datapoint[ 0 ],
y: item.datapoint[ 1 ]
});
} else {
// Return normal crosshair operation
myFlot.unlockCrosshair();
}
});
- unlockCrosshair()
Free the crosshair to move again after locking it.
*/
(function ($) {
var options = {
crosshair: {
mode: null, // one of null, "x", "y" or "xy",
color: "rgba(170, 0, 0, 0.80)",
lineWidth: 1
}
};
function init(plot) {
// position of crosshair in pixels
var crosshair = { x: -1, y: -1, locked: false };
plot.setCrosshair = function setCrosshair(pos) {
if (!pos)
crosshair.x = -1;
else {
var o = plot.p2c(pos);
crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
}
plot.triggerRedrawOverlay();
};
plot.clearCrosshair = plot.setCrosshair; // passes null for pos
plot.lockCrosshair = function lockCrosshair(pos) {
if (pos)
plot.setCrosshair(pos);
crosshair.locked = true;
};
plot.unlockCrosshair = function unlockCrosshair() {
crosshair.locked = false;
};
function onMouseOut(e) {
if (crosshair.locked)
return;
if (crosshair.x != -1) {
crosshair.x = -1;
plot.triggerRedrawOverlay();
}
}
function onMouseMove(e) {
if (crosshair.locked)
return;
if (plot.getSelection && plot.getSelection()) {
crosshair.x = -1; // hide the crosshair while selecting
return;
}
var offset = plot.offset();
crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
plot.triggerRedrawOverlay();
}
plot.hooks.bindEvents.push(function (plot, eventHolder) {
if (!plot.getOptions().crosshair.mode)
return;
eventHolder.mouseout(onMouseOut);
eventHolder.mousemove(onMouseMove);
});
plot.hooks.drawOverlay.push(function (plot, ctx) {
var c = plot.getOptions().crosshair;
if (!c.mode)
return;
var plotOffset = plot.getPlotOffset();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
if (crosshair.x != -1) {
var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;
ctx.strokeStyle = c.color;
ctx.lineWidth = c.lineWidth;
ctx.lineJoin = "round";
ctx.beginPath();
if (c.mode.indexOf("x") != -1) {
var drawX = Math.floor(crosshair.x) + adj;
ctx.moveTo(drawX, 0);
ctx.lineTo(drawX, plot.height());
}
if (c.mode.indexOf("y") != -1) {
var drawY = Math.floor(crosshair.y) + adj;
ctx.moveTo(0, drawY);
ctx.lineTo(plot.width(), drawY);
}
ctx.stroke();
}
ctx.restore();
});
plot.hooks.shutdown.push(function (plot, eventHolder) {
eventHolder.unbind("mouseout", onMouseOut);
eventHolder.unbind("mousemove", onMouseMove);
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'crosshair',
version: '1.0'
});
})(jQuery);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,59 @@
/* Flot plugin for automatically redrawing plots as the placeholder resizes.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
It works by listening for changes on the placeholder div (through the jQuery
resize event plugin) - if the size changes, it will redraw the plot.
There are no options. If you need to disable the plugin for some plots, you
can just fix the size of their placeholders.
*/
/* Inline dependency:
* jQuery resize event - v1.1 - 3/14/2010
* http://benalman.com/projects/jquery-resize-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);
(function ($) {
var options = { }; // no options
function init(plot) {
function onResize() {
var placeholder = plot.getPlaceholder();
// somebody might have hidden us and we can't plot
// when we don't have the dimensions
if (placeholder.width() == 0 || placeholder.height() == 0)
return;
plot.resize();
plot.setupGrid();
plot.draw();
}
function bindEvents(plot, eventHolder) {
plot.getPlaceholder().resize(onResize);
}
function shutdown(plot, eventHolder) {
plot.getPlaceholder().unbind("resize", onResize);
}
plot.hooks.bindEvents.push(bindEvents);
plot.hooks.shutdown.push(shutdown);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'resize',
version: '1.0'
});
})(jQuery);
@@ -0,0 +1,432 @@
/* Pretty handling of time axes.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
Set axis.mode to "time" to enable. See the section "Time series data" in
API.txt for details.
*/
(function($) {
var options = {
xaxis: {
timezone: null, // "browser" for local to the client or timezone for timezone-js
timeformat: null, // format string to use
twelveHourClock: false, // 12 or 24 time in time mode
monthNames: null // list of names of months
}
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
// Returns a string with the date d formatted according to fmt.
// A subset of the Open Group's strftime format is supported.
function formatDate(d, fmt, monthNames, dayNames) {
if (typeof d.strftime == "function") {
return d.strftime(fmt);
}
var leftPad = function(n, pad) {
n = "" + n;
pad = "" + (pad == null ? "0" : pad);
return n.length == 1 ? pad + n : n;
};
var r = [];
var escape = false;
var hours = d.getHours();
var isAM = hours < 12;
if (monthNames == null) {
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
}
if (dayNames == null) {
dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
}
var hours12;
if (hours > 12) {
hours12 = hours - 12;
} else if (hours == 0) {
hours12 = 12;
} else {
hours12 = hours;
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'a': c = "" + dayNames[d.getDay()]; break;
case 'b': c = "" + monthNames[d.getMonth()]; break;
case 'd': c = leftPad(d.getDate()); break;
case 'e': c = leftPad(d.getDate(), " "); break;
case 'h': // For back-compat with 0.7; remove in 1.0
case 'H': c = leftPad(hours); break;
case 'I': c = leftPad(hours12); break;
case 'l': c = leftPad(hours12, " "); break;
case 'm': c = leftPad(d.getMonth() + 1); break;
case 'M': c = leftPad(d.getMinutes()); break;
// quarters not in Open Group's strftime specification
case 'q':
c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
case 'S': c = leftPad(d.getSeconds()); break;
case 'y': c = leftPad(d.getFullYear() % 100); break;
case 'Y': c = "" + d.getFullYear(); break;
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
case 'w': c = "" + d.getDay(); break;
}
r.push(c);
escape = false;
} else {
if (c == "%") {
escape = true;
} else {
r.push(c);
}
}
}
return r.join("");
}
// To have a consistent view of time-based data independent of which time
// zone the client happens to be in we need a date-like object independent
// of time zones. This is done through a wrapper that only calls the UTC
// versions of the accessor methods.
function makeUtcWrapper(d) {
function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
sourceObj[sourceMethod] = function() {
return targetObj[targetMethod].apply(targetObj, arguments);
};
};
var utc = {
date: d
};
// support strftime, if found
if (d.strftime != undefined) {
addProxyMethod(utc, "strftime", d, "strftime");
}
addProxyMethod(utc, "getTime", d, "getTime");
addProxyMethod(utc, "setTime", d, "setTime");
var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
for (var p = 0; p < props.length; p++) {
addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
}
return utc;
};
// select time zone strategy. This returns a date-like object tied to the
// desired timezone
function dateGenerator(ts, opts) {
if (opts.timezone == "browser") {
return new Date(ts);
} else if (!opts.timezone || opts.timezone == "utc") {
return makeUtcWrapper(new Date(ts));
} else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
var d = new timezoneJS.Date();
// timezone-js is fickle, so be sure to set the time zone before
// setting the time.
d.setTimezone(opts.timezone);
d.setTime(ts);
return d;
} else {
return makeUtcWrapper(new Date(ts));
}
}
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"quarter": 3 * 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var baseSpec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"]
];
// we don't know which variant(s) we'll need yet, but generating both is
// cheap
var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
[1, "year"]]);
var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
[1, "year"]]);
function init(plot) {
plot.hooks.processOptions.push(function (plot, options) {
$.each(plot.getAxes(), function(axisName, axis) {
var opts = axis.options;
if (opts.mode == "time") {
axis.tickGenerator = function(axis) {
var ticks = [];
var d = dateGenerator(axis.min, opts);
var minSize = 0;
// make quarter use a possibility if quarters are
// mentioned in either of these options
var spec = (opts.tickSize && opts.tickSize[1] ===
"quarter") ||
(opts.minTickSize && opts.minTickSize[1] ===
"quarter") ? specQuarters : specMonths;
if (opts.minTickSize != null) {
if (typeof opts.tickSize == "number") {
minSize = opts.tickSize;
} else {
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
}
}
for (var i = 0; i < spec.length - 1; ++i) {
if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
break;
}
}
var size = spec[i][0];
var unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
// if given a minTickSize in years, just use it,
// ensuring that it's an integer
if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
size = Math.floor(opts.minTickSize[0]);
} else {
var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
var norm = (axis.delta / timeUnitSize.year) / magn;
if (norm < 1.5) {
size = 1;
} else if (norm < 3) {
size = 2;
} else if (norm < 7.5) {
size = 5;
} else {
size = 10;
}
size *= magn;
}
// minimum size for years is 1
if (size < 1) {
size = 1;
}
}
axis.tickSize = opts.tickSize || [size, unit];
var tickSize = axis.tickSize[0];
unit = axis.tickSize[1];
var step = tickSize * timeUnitSize[unit];
if (unit == "second") {
d.setSeconds(floorInBase(d.getSeconds(), tickSize));
} else if (unit == "minute") {
d.setMinutes(floorInBase(d.getMinutes(), tickSize));
} else if (unit == "hour") {
d.setHours(floorInBase(d.getHours(), tickSize));
} else if (unit == "month") {
d.setMonth(floorInBase(d.getMonth(), tickSize));
} else if (unit == "quarter") {
d.setMonth(3 * floorInBase(d.getMonth() / 3,
tickSize));
} else if (unit == "year") {
d.setFullYear(floorInBase(d.getFullYear(), tickSize));
}
// reset smaller components
d.setMilliseconds(0);
if (step >= timeUnitSize.minute) {
d.setSeconds(0);
}
if (step >= timeUnitSize.hour) {
d.setMinutes(0);
}
if (step >= timeUnitSize.day) {
d.setHours(0);
}
if (step >= timeUnitSize.day * 4) {
d.setDate(1);
}
if (step >= timeUnitSize.month * 2) {
d.setMonth(floorInBase(d.getMonth(), 3));
}
if (step >= timeUnitSize.quarter * 2) {
d.setMonth(floorInBase(d.getMonth(), 6));
}
if (step >= timeUnitSize.year) {
d.setMonth(0);
}
var carry = 0;
var v = Number.NaN;
var prev;
do {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month" || unit == "quarter") {
if (tickSize < 1) {
// a bit complicated - we'll divide the
// month/quarter up but we need to take
// care of fractions so we don't end up in
// the middle of a day
d.setDate(1);
var start = d.getTime();
d.setMonth(d.getMonth() +
(unit == "quarter" ? 3 : 1));
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getHours();
d.setHours(0);
} else {
d.setMonth(d.getMonth() +
tickSize * (unit == "quarter" ? 3 : 1));
}
} else if (unit == "year") {
d.setFullYear(d.getFullYear() + tickSize);
} else {
d.setTime(v + step);
}
} while (v < axis.max && v != prev);
return ticks;
};
axis.tickFormatter = function (v, axis) {
var d = dateGenerator(v, axis.options);
// first check global format
if (opts.timeformat != null) {
return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
}
// possibly use quarters if quarters are mentioned in
// any of these places
var useQuarters = (axis.options.tickSize &&
axis.options.tickSize[1] == "quarter") ||
(axis.options.minTickSize &&
axis.options.minTickSize[1] == "quarter");
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
var suffix = (opts.twelveHourClock) ? " %p" : "";
var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
var fmt;
if (t < timeUnitSize.minute) {
fmt = hourCode + ":%M:%S" + suffix;
} else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day) {
fmt = hourCode + ":%M" + suffix;
} else {
fmt = "%b %d " + hourCode + ":%M" + suffix;
}
} else if (t < timeUnitSize.month) {
fmt = "%b %d";
} else if ((useQuarters && t < timeUnitSize.quarter) ||
(!useQuarters && t < timeUnitSize.year)) {
if (span < timeUnitSize.year) {
fmt = "%b";
} else {
fmt = "%b %Y";
}
} else if (useQuarters && t < timeUnitSize.year) {
if (span < timeUnitSize.year) {
fmt = "Q%q";
} else {
fmt = "Q%q %Y";
}
} else {
fmt = "%Y";
}
var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
return rt;
};
}
});
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'time',
version: '1.0'
});
// Time-axis support used to be in Flot core, which exposed the
// formatDate function on the plot object. Various plugins depend
// on the function, so we need to re-expose it here.
$.plot.formatDate = formatDate;
$.plot.dateGenerator = dateGenerator;
})(jQuery);
+572 -459
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["node_modules/browser-pack/_prelude.js","lib/entry.js","lib/event/close.js","lib/event/emitter.js","lib/event/event.js","lib/event/eventtarget.js","lib/event/trans-message.js","lib/facade.js","lib/iframe-bootstrap.js","lib/info-ajax.js","lib/info-iframe-receiver.js","lib/info-iframe.js","lib/info-receiver.js","lib/location.js","lib/main.js","lib/shims.js","lib/transport-list.js","lib/transport/browser/abstract-xhr.js","lib/transport/browser/eventsource.js","lib/transport/browser/websocket.js","lib/transport/eventsource.js","lib/transport/htmlfile.js","lib/transport/iframe.js","lib/transport/jsonp-polling.js","lib/transport/lib/ajax-based.js","lib/transport/lib/buffered-sender.js","lib/transport/lib/iframe-wrap.js","lib/transport/lib/polling.js","lib/transport/lib/sender-receiver.js","lib/transport/receiver/eventsource.js","lib/transport/receiver/htmlfile.js","lib/transport/receiver/jsonp.js","lib/transport/receiver/xhr.js","lib/transport/sender/jsonp.js","lib/transport/sender/xdr.js","lib/transport/sender/xhr-cors.js","lib/transport/sender/xhr-fake.js","lib/transport/sender/xhr-local.js","lib/transport/websocket.js","lib/transport/xdr-polling.js","lib/transport/xdr-streaming.js","lib/transport/xhr-polling.js","lib/transport/xhr-streaming.js","lib/utils/browser-crypto.js","lib/utils/browser.js","lib/utils/escape.js","lib/utils/event.js","lib/utils/iframe.js","lib/utils/log.js","lib/utils/object.js","lib/utils/random.js","lib/utils/transport.js","lib/utils/url.js","lib/version.js","node_modules/debug/src/browser.js","node_modules/debug/src/debug.js","node_modules/inherits/inherits_browser.js","node_modules/json3/lib/json3.js","node_modules/ms/index.js","node_modules/querystringify/index.js","node_modules/requires-port/index.js","node_modules/url-parse/index.js","node_modules/url-parse/lolcation.js"],"names":[],"mappings":";AAAA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;Line truncated
+4 -3
View File
@@ -1,3 +1,4 @@
/* sockjs-client v1.1.1 | http://sockjs.org | MIT license */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.SockJS=t()}}(function(){var t;return function e(t,n,r){function i(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[s]={exports:{}};t[s][0].call(c.exports,function(e){var n=t[s][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(t,e){(function(n){"use strict";var r=t("./transport-list");e.exports=t("./main")(r),"_sockjs_onload"in n&&setTimeout(n._sockjs_onload,1)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./main":14,"./transport-list":16}],2:[function(t,e){"use strict";function n(){i.call(this),this.initEvent("close",!1,!1),this.wasClean=!1,this.code=0,this.reason=""}var r=t("inherits"),i=t("./event");r(n,i),e.exports=n},{"./event":4,inherits:54}],3:[function(t,e){"use strict";function n(){i.call(this)}var r=t("inherits"),i=t("./eventtarget");r(n,i),n.prototype.removeAllListeners=function(t){t?delete this._listeners[t]:this._listeners={}},n.prototype.once=function(t,e){function n(){r.removeListener(t,n),i||(i=!0,e.apply(this,arguments))}var r=this,i=!1;this.on(t,n)},n.prototype.emit=function(){var t=arguments[0],e=this._listeners[t];if(e){for(var n=arguments.length,r=new Array(n-1),i=1;n>i;i++)r[i-1]=arguments[i];for(var o=0;o<e.length;o++)e[o].apply(this,r)}},n.prototype.on=n.prototype.addListener=i.prototype.addEventListener,n.prototype.removeListener=i.prototype.removeEventListener,e.exports.EventEmitter=n},{"./eventtarget":5,inherits:54}],4:[function(t,e){"use strict";function n(t){this.type=t}n.prototype.initEvent=function(t,e,n){return this.type=t,this.bubbles=e,this.cancelable=n,this.timeStamp=+new Date,this},n.prototype.stopPropagation=function(){},n.prototype.preventDefault=function(){},n.CAPTURING_PHASE=1,n.AT_TARGET=2,n.BUBBLING_PHASE=3,e.exports=n},{}],5:[function(t,e){"use strict";function n(){this._listeners={}}n.prototype.addEventListener=function(t,e){t in this._listeners||(this._listeners[t]=[]);var n=this._listeners[t];-1===n.indexOf(e)&&(n=n.concat([e])),this._listeners[t]=n},n.prototype.removeEventListener=function(t,e){var n=this._listeners[t];if(n){var r=n.indexOf(e);return-1!==r?void(n.length>1?this._listeners[t]=n.slice(0,r).concat(n.slice(r+1)):delete this._listeners[t]):void 0}},n.prototype.dispatchEvent=function(){var t=arguments[0],e=t.type,n=1===arguments.length?[t]:Array.apply(null,arguments);if(this["on"+e]&&this["on"+e].apply(this,n),e in this._listeners)for(var r=this._listeners[e],i=0;i<r.length;i++)r[i].apply(this,n)},e.exports=n},{}],6:[function(t,e){"use strict";function n(t){i.call(this),this.initEvent("message",!1,!1),this.data=t}var r=t("inherits"),i=t("./event");r(n,i),e.exports=n},{"./event":4,inherits:54}],7:[function(t,e){"use strict";function n(t){this._transport=t,t.on("message",this._transportMessage.bind(this)),t.on("close",this._transportClose.bind(this))}var r=t("json3"),i=t("./utils/iframe");n.prototype._transportClose=function(t,e){i.postMessage("c",r.stringify([t,e]))},n.prototype._transportMessage=function(t){i.postMessage("t",t)},n.prototype._send=function(t){this._transport.send(t)},n.prototype._close=function(){this._transport.close(),this._transport.removeAllListeners()},e.exports=n},{"./utils/iframe":47,json3:55}],8:[function(t,e){"use strict";var n=t("./utils/url"),r=t("./utils/event"),i=t("json3"),o=t("./facade"),s=t("./info-iframe-receiver"),a=t("./utils/iframe"),u=t("./location");e.exports=function(t,e){var l={};e.forEach(function(t){t.facadeTransport&&(l[t.facadeTransport.transportName]=t.facadeTransport)}),l[s.transportName]=s;var c;t.bootstrap_iframe=function(){var e;a.currentWindowId=u.hash.slice(1);var s=function(r){if(r.source===parent&&("undefined"==typeof c&&(c=r.origin),r.origin===c)){var s;try{s=i.parse(r.data)}catch(f){return}if(s.windowId===a.currentWindowId)switch(s.type){case"s":var h;try{h=i.parse(s.data)}catch(f){break}var d=h[0],p=h[1],v=h[2],m=h[3];if(d!==t.version)throw new Error('Incompatible SockJS! Main site uses: "'+d+'", the iframe: "'+t.version+'".');if(!n.isOriginEqual(v,u.href)||!n.isOriginEqual(m,u.href))throw new Error("Can't connect to different domain from within an iframe. ("+u.href+", "+v+", "+m+")");e=new o(new l[p](v,m));break;case"m":e._send(s.data);break;case"c":e&&e._close(),e=null}}};r.attachEvent("message",s),a.postMessage("s")}}},{"./facade":7,"./info-iframe-receiver":10,"./location":13,"./utils/event":46,"./utils/iframe":47,"./utils/url":52,debug:void 0,json3:55}],9:[function(t,e){"use strict";function n(t,e){r.callLine truncated
}},"undefined"==typeof i.async&&n.document.attachEvent)if(s.isOpera())e=this.script2=n.document.createElement("script"),e.text="try{var a = document.getElementById('"+i.id+"'); if(a)a.onerror();}catch(x){};",i.async=e.async=!1;else{try{i.htmlFor=i.id,i.event="onclick"}catch(a){}i.async=!0}"undefined"!=typeof i.async&&(i.async=!0);var u=n.document.getElementsByTagName("head")[0];u.insertBefore(i,u.firstChild),e&&u.insertBefore(e,u.firstChild)},e.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../utils/browser":44,"../../utils/iframe":47,"../../utils/random":50,"../../utils/url":52,debug:void 0,events:3,inherits:54}],32:[function(t,e){"use strict";function n(t,e){i.call(this);var n=this;this.bufferPosition=0,this.xo=new e("POST",t,null),this.xo.on("chunk",this._chunkHandler.bind(this)),this.xo.once("finish",function(t,e){n._chunkHandler(t,e),n.xo=null;var r=200===t?"network":"permanent";n.emit("close",null,r),n._cleanup()})}var r=t("inherits"),i=t("events").EventEmitter;r(n,i),n.prototype._chunkHandler=function(t,e){if(200===t&&e)for(var n=-1;;this.bufferPosition+=n+1){var r=e.slice(this.bufferPosition);if(n=r.indexOf("\n"),-1===n)break;var i=r.slice(0,n);i&&this.emit("message",i)}},n.prototype._cleanup=function(){this.removeAllListeners()},n.prototype.abort=function(){this.xo&&(this.xo.close(),this.emit("close",null,"user"),this.xo=null),this._cleanup()},e.exports=n},{debug:void 0,events:3,inherits:54}],33:[function(t,e){(function(n){"use strict";function r(t){try{return n.document.createElement('<iframe name="'+t+'">')}catch(e){var r=n.document.createElement("iframe");return r.name=t,r}}function i(){o=n.document.createElement("form"),o.style.display="none",o.style.position="absolute",o.method="POST",o.enctype="application/x-www-form-urlencoded",o.acceptCharset="UTF-8",s=n.document.createElement("textarea"),s.name="d",o.appendChild(s),n.document.body.appendChild(o)}var o,s,a=t("../../utils/random"),u=t("../../utils/url");e.exports=function(t,e,n){o||i();var l="a"+a.string(8);o.target=l,o.action=u.addQuery(u.addPath(t,"/jsonp_send"),"i="+l);var c=r(l);c.id=l,c.style.display="none",o.appendChild(c);try{s.value=e}catch(f){}o.submit();var h=function(t){c.onerror&&(c.onreadystatechange=c.onerror=c.onload=null,setTimeout(function(){c.parentNode.removeChild(c),c=null},500),s.value="",n(t))};return c.onerror=function(){h()},c.onload=function(){h()},c.onreadystatechange=function(t){"complete"===c.readyState&&h()},function(){h(new Error("Aborted"))}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../utils/random":50,"../../utils/url":52,debug:void 0}],34:[function(t,e){(function(n){"use strict";function r(t,e,n){var r=this;i.call(this),setTimeout(function(){r._start(t,e,n)},0)}var i=t("events").EventEmitter,o=t("inherits"),s=t("../../utils/event"),a=t("../../utils/browser"),u=t("../../utils/url");o(r,i),r.prototype._start=function(t,e,r){var i=this,o=new n.XDomainRequest;e=u.addQuery(e,"t="+ +new Date),o.onerror=function(){i._error()},o.ontimeout=function(){i._error()},o.onprogress=function(){i.emit("chunk",200,o.responseText)},o.onload=function(){i.emit("finish",200,o.responseText),i._cleanup(!1)},this.xdr=o,this.unloadRef=s.unloadAdd(function(){i._cleanup(!0)});try{this.xdr.open(t,e),this.timeout&&(this.xdr.timeout=this.timeout),this.xdr.send(r)}catch(a){this._error()}},r.prototype._error=function(){this.emit("finish",0,""),this._cleanup(!1)},r.prototype._cleanup=function(t){if(this.xdr){if(this.removeAllListeners(),s.unloadDel(this.unloadRef),this.xdr.ontimeout=this.xdr.onerror=this.xdr.onprogress=this.xdr.onload=null,t)try{this.xdr.abort()}catch(e){}this.unloadRef=this.xdr=null}},r.prototype.close=function(){this._cleanup(!0)},r.enabled=!(!n.XDomainRequest||!a.hasDomain()),e.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../utils/browser":44,"../../utils/event":46,"../../utils/url":52,debug:void 0,events:3,inherits:54}],35:[function(t,e){"use strict";function n(t,e,n,r){i.call(this,t,e,n,r)}var r=t("inherits"),i=t("../driver/xhr");r(n,i),n.enabled=i.enabled&&i.supportsCORS,e.exports=n},{"../driver/xhr":17,inherits:54}],36:[function(t,e){"use strict";function n(){var t=this;r.call(this),this.to=setTimeout(function(){t.emit("finish",200,"{}")},n.timeout)}var r=t("events").EventEmitter,i=t("inherits");i(n,r),n.prototype.close=function(){clearTimeout(this.to)},n.timeout=2e3,e.exports=n},{events:3,inherits:54}],37:[function(t,e){"use strict";function n(t,e,n){i.call(this,t,e,n,{noCredentials:!0})}var r=t("inherits"),i=t("../driver/xhr");r(n,i),n.enabled=i.enabled,e.exports=n},{"../driver/xhr":17,inherits:54}],38:[function(t,e){"use strict";function n(t,e,o){if(!n.enabled())throw new Error("Transport created when disabled");s.call(this);var u=this,l=i.addPath(t,"/websocket");l="https"=Line truncated
/* sockjs-client v1.1.2 | http://sockjs.org | MIT license */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.SockJS=t()}}(function(){var t;return function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[s]={exports:{}};e[s][0].call(c.exports,function(t){var n=e[s][1][t];return i(n?n:t)},c,c.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(t,e,n){(function(n){"use strict";var r=t("./transport-list");e.exports=t("./main")(r),"_sockjs_onload"in n&&setTimeout(n._sockjs_onload,1)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./main":14,"./transport-list":16}],2:[function(t,e,n){"use strict";function r(){o.call(this),this.initEvent("close",!1,!1),this.wasClean=!1,this.code=0,this.reason=""}var i=t("inherits"),o=t("./event");i(r,o),e.exports=r},{"./event":4,inherits:54}],3:[function(t,e,n){"use strict";function r(){o.call(this)}var i=t("inherits"),o=t("./eventtarget");i(r,o),r.prototype.removeAllListeners=function(t){t?delete this._listeners[t]:this._listeners={}},r.prototype.once=function(t,e){function n(){r.removeListener(t,n),i||(i=!0,e.apply(this,arguments))}var r=this,i=!1;this.on(t,n)},r.prototype.emit=function(){var t=arguments[0],e=this._listeners[t];if(e){for(var n=arguments.length,r=new Array(n-1),i=1;i<n;i++)r[i-1]=arguments[i];for(var o=0;o<e.length;o++)e[o].apply(this,r)}},r.prototype.on=r.prototype.addListener=o.prototype.addEventListener,r.prototype.removeListener=o.prototype.removeEventListener,e.exports.EventEmitter=r},{"./eventtarget":5,inherits:54}],4:[function(t,e,n){"use strict";function r(t){this.type=t}r.prototype.initEvent=function(t,e,n){return this.type=t,this.bubbles=e,this.cancelable=n,this.timeStamp=+new Date,this},r.prototype.stopPropagation=function(){},r.prototype.preventDefault=function(){},r.CAPTURING_PHASE=1,r.AT_TARGET=2,r.BUBBLING_PHASE=3,e.exports=r},{}],5:[function(t,e,n){"use strict";function r(){this._listeners={}}r.prototype.addEventListener=function(t,e){t in this._listeners||(this._listeners[t]=[]);var n=this._listeners[t];n.indexOf(e)===-1&&(n=n.concat([e])),this._listeners[t]=n},r.prototype.removeEventListener=function(t,e){var n=this._listeners[t];if(n){var r=n.indexOf(e);return r!==-1?void(n.length>1?this._listeners[t]=n.slice(0,r).concat(n.slice(r+1)):delete this._listeners[t]):void 0}},r.prototype.dispatchEvent=function(){var t=arguments[0],e=t.type,n=1===arguments.length?[t]:Array.apply(null,arguments);if(this["on"+e]&&this["on"+e].apply(this,n),e in this._listeners)for(var r=this._listeners[e],i=0;i<r.length;i++)r[i].apply(this,n)},e.exports=r},{}],6:[function(t,e,n){"use strict";function r(t){o.call(this),this.initEvent("message",!1,!1),this.data=t}var i=t("inherits"),o=t("./event");i(r,o),e.exports=r},{"./event":4,inherits:54}],7:[function(t,e,n){"use strict";function r(t){this._transport=t,t.on("message",this._transportMessage.bind(this)),t.on("close",this._transportClose.bind(this))}var i=t("json3"),o=t("./utils/iframe");r.prototype._transportClose=function(t,e){o.postMessage("c",i.stringify([t,e]))},r.prototype._transportMessage=function(t){o.postMessage("t",t)},r.prototype._send=function(t){this._transport.send(t)},r.prototype._close=function(){this._transport.close(),this._transport.removeAllListeners()},e.exports=r},{"./utils/iframe":47,json3:55}],8:[function(t,e,n){"use strict";var r=t("./utils/url"),i=t("./utils/event"),o=t("json3"),s=t("./facade"),a=t("./info-iframe-receiver"),l=t("./utils/iframe"),u=t("./location");e.exports=function(t,e){var n={};e.forEach(function(t){t.facadeTransport&&(n[t.facadeTransport.transportName]=t.facadeTransport)}),n[a.transportName]=a;var c;t.bootstrap_iframe=function(){var e;l.currentWindowId=u.hash.slice(1);var a=function(i){if(i.source===parent&&("undefined"==typeof c&&(c=i.origin),i.origin===c)){var a;try{a=o.parse(i.data)}catch(t){return}if(a.windowId===l.currentWindowId)switch(a.type){case"s":var f;try{f=o.parse(a.data)}catch(t){break}var h=f[0],d=f[1],p=f[2],v=f[3];if(h!==t.version)throw new Error('Incompatible SockJS! Main site uses: "'+h+'", the iframe: "'+t.version+'".');if(!r.isOriginEqual(p,u.href)||!r.isOriginEqual(v,u.href))throw new Error("Can't connect to different domain from within an iframe. ("+u.href+", "+p+", "+v+")");e=new s(new n[d](p,v));break;case"m":e._send(a.data);break;case"c":e&&e._close(),e=null}}};i.attachEvent("message",a),l.postMessage("s")}}},{"./facade":7,"./info-iframe-receiver":10,"./location":13,"./utils/event":46,"./utils/iframe":47,"./utils/url":52,debug:void 0,json3:55}],9:[function(t,e,n){"use strict";functLine truncated
i.async=e.async=!1;else{try{i.htmlFor=i.id,i.event="onclick"}catch(t){}i.async=!0}"undefined"!=typeof i.async&&(i.async=!0);var a=n.document.getElementsByTagName("head")[0];a.insertBefore(i,a.firstChild),e&&a.insertBefore(e,a.firstChild)},e.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../utils/browser":44,"../../utils/iframe":47,"../../utils/random":50,"../../utils/url":52,debug:void 0,events:3,inherits:54}],32:[function(t,e,n){"use strict";function r(t,e){o.call(this);var n=this;this.bufferPosition=0,this.xo=new e("POST",t,null),this.xo.on("chunk",this._chunkHandler.bind(this)),this.xo.once("finish",function(t,e){n._chunkHandler(t,e),n.xo=null;var r=200===t?"network":"permanent";n.emit("close",null,r),n._cleanup()})}var i=t("inherits"),o=t("events").EventEmitter;i(r,o),r.prototype._chunkHandler=function(t,e){if(200===t&&e)for(var n=-1;;this.bufferPosition+=n+1){var r=e.slice(this.bufferPosition);if(n=r.indexOf("\n"),n===-1)break;var i=r.slice(0,n);i&&this.emit("message",i)}},r.prototype._cleanup=function(){this.removeAllListeners()},r.prototype.abort=function(){this.xo&&(this.xo.close(),this.emit("close",null,"user"),this.xo=null),this._cleanup()},e.exports=r},{debug:void 0,events:3,inherits:54}],33:[function(t,e,n){(function(n){"use strict";function r(t){try{return n.document.createElement('<iframe name="'+t+'">')}catch(r){var e=n.document.createElement("iframe");return e.name=t,e}}function i(){o=n.document.createElement("form"),o.style.display="none",o.style.position="absolute",o.method="POST",o.enctype="application/x-www-form-urlencoded",o.acceptCharset="UTF-8",s=n.document.createElement("textarea"),s.name="d",o.appendChild(s),n.document.body.appendChild(o)}var o,s,a=t("../../utils/random"),l=t("../../utils/url");e.exports=function(t,e,n){o||i();var u="a"+a.string(8);o.target=u,o.action=l.addQuery(l.addPath(t,"/jsonp_send"),"i="+u);var c=r(u);c.id=u,c.style.display="none",o.appendChild(c);try{s.value=e}catch(t){}o.submit();var f=function(t){c.onerror&&(c.onreadystatechange=c.onerror=c.onload=null,setTimeout(function(){c.parentNode.removeChild(c),c=null},500),s.value="",n(t))};return c.onerror=function(){f()},c.onload=function(){f()},c.onreadystatechange=function(t){"complete"===c.readyState&&f()},function(){f(new Error("Aborted"))}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../utils/random":50,"../../utils/url":52,debug:void 0}],34:[function(t,e,n){(function(n){"use strict";function r(t,e,n){var r=this;i.call(this),setTimeout(function(){r._start(t,e,n)},0)}var i=t("events").EventEmitter,o=t("inherits"),s=t("../../utils/event"),a=t("../../utils/browser"),l=t("../../utils/url");o(r,i),r.prototype._start=function(t,e,r){var i=this,o=new n.XDomainRequest;e=l.addQuery(e,"t="+ +new Date),o.onerror=function(){i._error()},o.ontimeout=function(){i._error()},o.onprogress=function(){i.emit("chunk",200,o.responseText)},o.onload=function(){i.emit("finish",200,o.responseText),i._cleanup(!1)},this.xdr=o,this.unloadRef=s.unloadAdd(function(){i._cleanup(!0)});try{this.xdr.open(t,e),this.timeout&&(this.xdr.timeout=this.timeout),this.xdr.send(r)}catch(t){this._error()}},r.prototype._error=function(){this.emit("finish",0,""),this._cleanup(!1)},r.prototype._cleanup=function(t){if(this.xdr){if(this.removeAllListeners(),s.unloadDel(this.unloadRef),this.xdr.ontimeout=this.xdr.onerror=this.xdr.onprogress=this.xdr.onload=null,t)try{this.xdr.abort()}catch(t){}this.unloadRef=this.xdr=null}},r.prototype.close=function(){this._cleanup(!0)},r.enabled=!(!n.XDomainRequest||!a.hasDomain()),e.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../utils/browser":44,"../../utils/event":46,"../../utils/url":52,debug:void 0,events:3,inherits:54}],35:[function(t,e,n){"use strict";function r(t,e,n,r){o.call(this,t,e,n,r)}var i=t("inherits"),o=t("../driver/xhr");i(r,o),r.enabled=o.enabled&&o.supportsCORS,e.exports=r},{"../driver/xhr":17,inherits:54}],36:[function(t,e,n){"use strict";function r(){var t=this;i.call(this),this.to=setTimeout(function(){t.emit("finish",200,"{}")},r.timeout)}var i=t("events").EventEmitter,o=t("inherits");o(r,i),r.prototype.close=function(){clearTimeout(this.to)},r.timeout=2e3,e.exports=r},{events:3,inherits:54}],37:[function(t,e,n){"use strict";function r(t,e,n){o.call(this,t,e,n,{noCredentials:!0})}var i=t("inherits"),o=t("../driver/xhr");i(r,o),r.enabled=o.enabled,e.exports=r},{"../driver/xhr":17,inherits:54}],38:[function(t,e,n){"use strict";function r(t,e,n){if(!r.enabled())throw new Error("Transport created when disabled");a.call(this);var s=this,u=o.addPath(t,"/websocket");u="https"===u.slice(0,5)?"wss"+u.slice(5):"ws"+u.slice(4),this.url=u,this.ws=new l(this.url,[],n),this.ws.onmessage=function(t){s.emit("message",t.data)},this.unloadRef=i.unloadAdd(function(){s.ws.close()Line truncated
//# sourceMappingURL=sockjs.min.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["node_modules/browser-pack/_prelude.js","lib/entry.js","lib/event/close.js","lib/event/emitter.js","lib/event/event.js","lib/event/eventtarget.js","lib/event/trans-message.js","lib/facade.js","lib/iframe-bootstrap.js","lib/info-ajax.js","lib/info-iframe-receiver.js","lib/info-iframe.js","lib/info-receiver.js","lib/location.js","lib/main.js","lib/shims.js","lib/transport-list.js","lib/transport/browser/abstract-xhr.js","lib/transport/browser/eventsource.js","lib/transport/browser/websocket.js","lib/transport/eventsource.js","lib/transport/htmlfile.js","lib/transport/iframe.js","lib/transport/jsonp-polling.js","lib/transport/lib/ajax-based.js","lib/transport/lib/buffered-sender.js","lib/transport/lib/iframe-wrap.js","lib/transport/lib/polling.js","lib/transport/lib/sender-receiver.js","lib/transport/receiver/eventsource.js","lib/transport/receiver/htmlfile.js","lib/transport/receiver/jsonp.js","lib/transport/receiver/xhr.js","lib/transport/sender/jsonp.js","lib/transport/sender/xdr.js","lib/transport/sender/xhr-cors.js","lib/transport/sender/xhr-fake.js","lib/transport/sender/xhr-local.js","lib/transport/websocket.js","lib/transport/xdr-polling.js","lib/transport/xdr-streaming.js","lib/transport/xhr-polling.js","lib/transport/xhr-streaming.js","lib/utils/browser-crypto.js","lib/utils/browser.js","lib/utils/escape.js","lib/utils/event.js","lib/utils/iframe.js","lib/utils/log.js","lib/utils/object.js","lib/utils/random.js","lib/utils/transport.js","lib/utils/url.js","lib/version.js","node_modules/inherits/inherits_browser.js","node_modules/json3/lib/json3.js","node_modules/querystringify/index.js","node_modules/requires-port/index.js","node_modules/url-parse/index.js","node_modules/url-parse/lolcation.js"],"names":["f","exports","module","define","amd","g","window","global","self","this","SockJS","e","t","n","r","s","o","u","a","require","i","Error","code","l","call","length","1","transportList","setTimeout","_sockjs_onload","CloseEvent","Event","initEvent","wasClean","reason","inherits","EventEmitter","EventTarget","prototype","removeAllListeners","type","_listeners","once","listener","removeListener","fired","apply","arguments","on","emit","listeners","args","Array","ai","addListener","addEventListener","removeEventListener","eventType","canBubble","cancelable","bubbles","timeStamp","Date","stopPropagation","preventDefault","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","arr","indexOf","concat","idx","slice","dispatchEvent","event","TransportMessageEvent","data","FacadeJS","transport","_transport","_transportMessage","bind","_transportClose","JSON3","iframeUtils","postMessage","stringify","frame","_send","send","_close","close","urlUtils","eventUtils","InfoIframeReceiver","loc","availableTransports","transportMap","forEach","at","facadeTransport","transportName","parentOrigin","bootstrap_iframe","facade","currentWindowId","hash","onMessage","source","parent","origin","iframeMessage","parse","ignored","windowId","p","version","transUrl","baseUrl","isOriginEqual","href","attachEvent","InfoAjax","url","AjaxObject","t0","xo","status","text","info","rtt","objectUtils","isObject","InfoReceiverIframe","ir","XHRLocalObject","InfoIframe","go","ifr","IframeTransport","msg","d","document","body","utils","enabled","InfoReceiver","urlInfo","doXhr","XDR","XHRCors","XHRLocal","XHRFake","_getReceiver","sameOrigin","sameScheme","addPath","timeoutRef","_cleanup","timeout","clearTimeout","location","protocol","host","port","protocols","options","TypeError","readyState","CONNECTING","extensions","protocols_whitelist","log","warn","_transportsWhitelist","transports","_transportOptions","transportOptions","sessionId","_generateSessionId","random","string","_server","server","numberString","parsedUrl","URL","SyntaxError","secure","isArray","sortedProtocols","sort","proto","getOrigin","_origin","toLowerCase","set","pathname","replace","_urlInfo","nullOrigin","browser","hasDomain","isSchemeEqual","_ir","_receiveInfo","userSetCode","escape","CLOSING","CLOSED","OPEN","quote","_rto","countRTO","_transUrl","base_url","extend","enabledTransports","filterToEnabled","_transports","main","_connect","Transport","shift","needBody","unshift","timeoutMs","roundTrips","_transportTimeoutId","_transportTimeout","transportUrl","transportObj","payload","content","_open","forceFail","onmessage","onclose","onerror","toInteger","num","Math","floor","abs","ToUint32","x","Empty","defineProperty","ArrayPrototype","ObjectPrototype","Object","FunctionPrototype","Function","StringPrototype","String","array_slice","_toString","toString","isFunction","val","obj","isString","supportsDescriptors","object","name","method","forceAssign","configurable","enumerable","writable","value","defineProperties","map","hasOwnProperty","toObject","that","target","binder","bound","result","boundLength","max","boundArgs","push","join","boxedString","splitString","properlyBoxesContext","properlyBoxesNonStrict","properlyBoxesStrict","_","__","context","funLine truncated
+186 -6
View File
@@ -407,7 +407,6 @@ table {
width: 80px;
.actioncol;
}
}
}
@@ -420,12 +419,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,
@@ -498,7 +537,7 @@ ul.dropdown-menu li a {
position: relative;
outline: none;
//min-height: 440px;
background-color: black;
.keycontrol_overlay {
position: absolute;
@@ -533,6 +572,89 @@ ul.dropdown-menu li a {
float: left;
}
}
.nowebcam {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
.text {
color: white;
text-align: center;
position: relative;
margin: auto;
width: 80%;
top: 50%;
transform: translateY(-50%);
display: block;
&.webcam_loading {
animation: pulsate 3s ease-out;
animation-iteration-count: infinite;
}
}
}
.webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 100%;
pointer-events: none;
.webcam_fixed_ratio {
position: absolute;
transform: rotate(-90deg);
top: 0;
bottom: 0;
pointer-events: none;
.webcam_fixed_ratio_inner {
width: 100%;
height: 100%;
pointer-events: none;
}
}
}
.webcam_unrotated {
.webcam_fixed_ratio {
width: 100%;
pointer-events: none;
padding-bottom: 100%;
&.ratio43 {
padding-bottom: 75%;
}
&.ratio169 {
padding-bottom: 56.25%;
}
&.ratio1610 {
padding-bottom: 62.5%;
}
position: relative;
.webcam_fixed_ratio_inner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
pointer-events: none;
}
}
}
img {
width: 100%;
height: 100%;
object-fit: contain;
}
}
/** State sidebar panel */
@@ -874,6 +996,18 @@ textarea.block {
width: 100%;
}
@keyframes pulsate {
0% {
opacity: 0.5;
}
50% {
opacity: 1.0;
}
100% {
opacity: 0.5;
}
}
#drop_overlay {
position: fixed;
top: 0;
@@ -1002,6 +1136,10 @@ textarea.block {
display: inline-block !important;
}
a.dropdown-sd {
padding-top: 4px !important;
}
.center {
float: none;
margin-left: auto;
@@ -1132,6 +1270,12 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
-webkit-overflow-scrolling: touch;
}
.pre-output {
span {
display: block; // so we don't need to add individual <br> tags to each line
}
}
.input-append, .input-prepend {
.add-on {
&.add-on-limited {
@@ -1140,6 +1284,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,
@@ -1147,10 +1312,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
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,25 @@
/*!
* Font Awesome 3.2.1
* the iconic font designed for Bootstrap
* ------------------------------------------------------------------------------
* The full suite of pictographic icons, examples, and documentation can be
* found at http://fontawesome.io. Stay up to date on Twitter at
* http://twitter.com/fontawesome.
*
* License
* ------------------------------------------------------------------------------
* - The Font Awesome font is licensed under SIL OFL 1.1 -
* http://scripts.sil.org/OFL
* - Font Awesome CSS, LESS, and SASS files are licensed under MIT License -
* http://opensource.org/licenses/mit-license.html
* - Font Awesome documentation licensed under CC BY 3.0 -
* http://creativecommons.org/licenses/by/3.0/
* - Attribution is no longer required in Font Awesome 3.0, but much appreciated:
* "Font Awesome by Dave Gandy - http://fontawesome.io"
*
* Author - Dave Gandy
* ------------------------------------------------------------------------------
* Email: dave@fontawesome.io
* Twitter: http://twitter.com/davegandy
* Work: Lead Product Designer @ Kyruus - http://kyruus.com
*/@font-face{font-family:'FontAwesome3';src:url('../fonts/fontawesome-webfont.eot?v=3.2.1');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=3.2.1') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff?v=3.2.1') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=3.2.1') format('truetype'),url('../fonts/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1') format('svg');font-weight:normal;font-style:normal}[class^="icon-"],[class*=" icon-"]{font-family:FontAwesome3;font-weight:normal;font-style:normal;text-decoration:inherit;-webkit-font-smoothing:antialiased;*margin-right:.3em}[class^="icon-"]:before,[class*=" icon-"]:before{text-decoration:inherit;display:inline-block;speak:none}.icon-large:before{vertical-align:-10%;font-size:1.33333333em}a [class^="icon-"],a [class*=" icon-"]{display:inline}[class^="icon-"].icon-fixed-width,[class*=" icon-"].icon-fixed-width{display:inline-block;width:1.14285714em;text-align:right;padding-right:.28571429em}[class^="icon-"].icon-fixed-width.icon-large,[class*=" icon-"].icon-fixed-width.icon-large{width:1.42857143em}.icons-ul{margin-left:2.14285714em;list-style-type:none}.icons-ul>li{position:relative}.icons-ul .icon-li{position:absolute;left:-2.14285714em;width:2.14285714em;text-align:center;line-height:inherit}[class^="icon-"].hide,[class*=" icon-"].hide{display:none}.icon-muted{color:#eee}.icon-light{color:#fff}.icon-dark{color:#333}.icon-border{border:solid 1px #eee;padding:.2em .25em .15em;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.icon-2x{font-size:2em}.icon-2x.icon-border{border-width:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.icon-3x{font-size:3em}.icon-3x.icon-border{border-width:3px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.icon-4x{font-size:4em}.icon-4x.icon-border{border-width:4px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.icon-5x{font-size:5em}.icon-5x.icon-border{border-width:5px;-webkit-border-radius:7px;-moz-border-radius:7px;border-radius:7px}.pull-right{float:right}.pull-left{float:left}[class^="icon-"].pull-left,[class*=" icon-"].pull-left{margin-right:.3em}[class^="icon-"].pull-right,[class*=" icon-"].pull-right{margin-left:.3em}[class^="icon-"],[class*=" icon-"]{display:inline;width:auto;height:auto;line-height:normal;vertical-align:baseline;background-image:none;background-position:0 0;background-repeat:repeat;margin-top:0}.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"]{background-image:none}.btn [class^="icon-"].icon-large,.nav [class^="icon-"].icon-large,.btn [class*=" icon-"].icon-large,.nav [class*=" icon-"].icon-large{line-height:.9em}.btn [class^="icon-"].icon-spin,.nav [class^="icon-"].icon-spin,.btn [class*=" icon-"].icon-spin,.nav [class*=" icon-"].icon-spin{display:inline-block}.nav-tabs [class^="icon-"],.nav-pills [class^="icon-"],.nav-tabs [class*=" icon-"],.nav-pills [class*=" icon-"],.nav-tabs [class^="icon-"].icon-large,.nav-pills [class^="icon-"].icon-large,.nav-tabs [class*=" icon-"].icon-large,.nav-pills [class*=" icon-"].icon-large{line-height:.9em}.btn [class^="icon-"].pull-left.icon-2x,.btn [class*=" icon-"].pull-left.icon-2x,.btn [class^="icon-"].pull-right.icon-2x,.btn [class*=" icon-"].pull-right.icon-2x{margin-top:.18em}.btn [class^="icon-"].icon-spin.icon-large,.btn [class*=" icon-"].icon-spin.icon-large{line-height:.8em}.btn.btn-small [class^="icon-"].pull-left.icon-2x,.btn.btn-small [class*=" icon-"].pull-left.icon-2x,.btn.btn-small [class^="icon-"].pull-right.icon-2x,.btn.btn-small [class*=" icon-"].pull-right.icon-2x{margin-top:.25em}.btn.btn-large [class^="icon-"],.btn.btn-large [class*=" icon-"]{margin-top:0}.btn.btn-large [class^="icon-"].pull-left.icon-2x,.btn.btn-large [class*=" icon-"].pull-left.icon-2x,.btn.btn-large [class^="icon-"].pull-right.icon-2x,.btn.btn-large [class*=" icon-"].pull-right.icon-2x{margin-top:.05em}.btn.btn-large [class^="icon-"].pull-left.icon-2x,.btn.btn-large [class*=" icon-"].pull-left.icon-2x{margin-right:.2em}.btn.btn-large [class^="icon-"].pull-right.icon-2x,.btn.btn-large [class*=" icon-"].pull-right.icon-2x{margin-left:.2em}.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{line-height:inherit}.icon-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:-35%}.icon-stack [class^="icon-"],.icon-stack [class*=" icon-"]{display:block;text-align:center;position:absolute;width:100%;height:100%;font-size:1em;line-height:inherit;*line-height:2em}.icon-stack .icLine truncated
File renamed without changes.

Before

Width:  |  Height:  |  Size: 193 KiB

After

Width:  |  Height:  |  Size: 193 KiB

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,4 @@
/*!
* Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome
* License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
*/@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.7.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'),url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left{margin-right:.3em}.fa.fa-pull-right{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scale(-1,1);-ms-transform:scale(-1,1);transform:scale(-1,1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scale(1,-1);-ms-transform:scale(1,-1);transform:scale(1,-1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-remove:before,.fa-close:before,.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.faLine truncated
File diff suppressed because it is too large. Load diff

After

Width:  |  Height:  |  Size: 434 KiB

+1 -1
View File
@@ -16,6 +16,6 @@
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="#" class="btn btn-primary" data-bind="click: function() { if ($root.enableAddFolder()) { $root.addFolder() } }, enabled: $root.enableAddFolder(), css: {disabled: !$root.enableAddFolder()}"><i class="icon-spinner icon-spin" data-bind="visible: addingFolder"></i> {{ _('Create') }}</a>
<a href="#" class="btn btn-primary" data-bind="click: function() { if ($root.enableAddFolder()) { $root.addFolder() } }, enabled: $root.enableAddFolder(), css: {disabled: !$root.enableAddFolder()}"><i class="fa fa-spinner fa-spin" data-bind="visible: addingFolder"></i> {{ _('Create') }}</a>
</div>
</div>
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more