Rebase to devel

This commit is contained in:
Kyle Evans committed 2016-11-27 00:32:38 -06:00
commit 537ed2d11f
86 files changed
+3865 -2299

No files matched your search

+77
View File
@@ -1,5 +1,64 @@
# OctoPrint Changelog
## 1.3.0rc2 (2016-11-24)
### Features
* OctoPrint will now track the current print head position on pause and cancel and provide it as new template variables ``pause_position``/``cancel_position`` for the relevant GCODE scripts. This will allow more intelligent pause codes that park the print head at a rest position during pause and move it back to the exact position it was before the pause on resume ([Example](https://gist.github.com/foosel/1c09e269b1c0bb7a471c20eef50c8d3e)). Note that this is NOT enabled by default and for now will necessitate adjusting the pause and resume GCODE scripts yourself since position tracking with multiple extruders or when printing from SD is currently not fool proof thanks to firmware limitations regarding reliable tracking of the various ``E`` values and the currently selected tool ``T``. In order to fully implement this feature, the following improvements were also done:
* New ``PositionUpdated`` event when OctoPrint receives a response to an ``M114`` position query.
* Extended ``PrintPaused`` and ``PrintCancelled`` events with position data from ``M114`` position query on print interruption/end.
* Added (optional) firmware auto detection. If enabled (which it is by default), OctoPrint will now send an ``M115`` to the printer on initial connection in order to try to figure out what kind of firmware it is. For FIRMWARE_NAME values containing "repetier" (case insensitive), all Repetier-specific flags will be set on the comm layer. For FIRMWARE_NAME values containing "reprapfirmware" (also case insensitive), all RepRapFirmware-specific flags will be set on the comm layer. For now no other handling will be performed.
* Added safe mode flag ``--safe`` and config setting ``startOnceInSafeMode`` that disables all third party plugins when active. The config setting will automatically be removed from `config.yaml` after the server has started through successfully.
* Added ``octoprint config`` CLI that allows easier manipulation of config.yaml entries from the command line. Example: ``octoprint config set --bool server.startOnceInSafeMode true``
### Improvements
* [#1422](https://github.com/foosel/OctoPrint/issues/1422) - Added option for post roll for timed timelapse to duplicate last frame instead of capturing new frames. That makes for a faster render at the cost of a still frame at the end of the rendered video. See also [#1553](https://github.com/foosel/OctoPrint/pull/1553).
* [#1551](https://github.com/foosel/OctoPrint/issues/1551) - Allow to define a custom bounding box for valid printer head movements in the printer profile, to make print dimension check more flexible.
* [#1583](https://github.com/foosel/OctoPrint/pull/1583) - Strip invalid `pip` arguments from `pip uninstall` commands, if provided by the user as additional pip arguments.
* [#1593](https://github.com/foosel/OctoPrint/issues/1593) - Automatically migrate old manual system commands for restarting OctoPrint and rebooting or shutting down the server to the new system wide configuration settings. Make a backup copy of the old `config.yaml` before doing so in case a manual rollback is required.
* Support ``M114`` responses without whitespace between coordinates (protocol consistency - who needs it?).
* Don't focus files in the file list after deleting a file - made the list too jumpy.
* Better error resilience against errors in UI components.
* `M600` is now marked as a long running command by default.
* Plugin Manager: Allow closing of all notifications and close them automatically on detected server disconnect. No need to keep a "Restart needed" message around if a restart is in progress.
* Software Update: "busy" spinner on check buttons while already checking for updates.
* Software Update: Prevent update notification when wizard is open.
* Plugin Manager / Software Update: The "There's a new version of pip" message during plugin installs and software updates is no longer displayed like an error.
* Plugin Manager / Software Update: The "busy" dialog can no longer be closed accidentally.
### Bug fixes
* [#1148](https://github.com/foosel/OctoPrint/issues/1148) - Fixed retraction z hop setting for Z-triggered timelapses. Was not correctly propagated to the backend and hence not taking effect.
* [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Invalidate ``/api/settings`` cache on change of the user's login state (include user roles into ETag calculation).
* [#1586](https://github.com/foosel/OctoPrint/issues/1586) - Fixed incompatibility of update script and command line helper with non-ASCII output from called commands.
* [#1588](https://github.com/foosel/OctoPrint/issues/1588) - Fixed feedback controls again.
* Invalidate ``/api/settings`` cache on change of the currently enabled plugins (by including plugin names into ETag calculation) and/or on change of the current effective config.
* Invalidate ``/api/timelapse`` cache on change of the current timelapse configuration.
* Fixed an issue causing the version number not to be properly extracted from ``sdist`` tarballs generated under Windows.
* Get rid of double scroll bar in printer profile editor.
* Fixed tracking of current byte position in file being streamed from disk. Turns out that ``self._handle.tell`` lied to us thanks to line buffering.
* Fixed select & print not working anymore for SD files thanks to a timing issue.
* Fixed ``PrintFailed`` event payload (was still missing new folder relevant data).
* Fixed premature parse stop on ``M114`` and ``M115`` responses with ``ok``-prefix.
* Make sure `?l10n` request parameter gets also propagated to API calls as `X-Locale` header in case of locale sensitive API responses.
* Fix language mixture due to cached template configs including localized strings; cache per locale.
* Only insert divider in system menu after core commands if there are custom commands.
* Fix update of webcam stream URL not being applied due to caching.
* Fixed a rare race condition causing the new "The settings changed, reload?" popup to show up even when the settings change originated in the same client instance.
* Fixed a bunch of missing translations.
* Pinned Tornado version to 4.0.2. Former version requirement was able to pull in a beta version causing issues with websockets due to a bug in `permessage-deflate` handling. The Tornado requirement needs an update, but we'll leave it at 4.0.2 for 1.3.0 since we'll need to do some migration work for compatibility with anything newer. Potentially related to [#1523](https://github.com/foosel/OctoPrint/issues/1523).
### Changes from `maintenance` not yet released as part of a stable release
#### Bug fixes
* [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first.
* [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses
* Fix issue with settings restriction causing internal settings defaults to be changed.
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.0rc1...1.3.0rc2))
## 1.3.0rc1 (2016-10-19)
### New Features
@@ -104,6 +163,24 @@
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.3.0rc1))
## 1.2.18rc1 (2016-11-22)
### Improvements
* Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate.
* Limited Cura profile importer to `.ini` files and clarified the supported versions
* Add support for the `R` parameter for `M109` and `M190`
### Bug fixes
* [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default
* [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer
* [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first.
* [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses
* Fix issue with settings restriction causing internal settings defaults to be changed.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.17...1.2.18))
## 1.2.17 (2016-11-08)
### Improvements
+2 -6
View File
@@ -33,27 +33,22 @@ thanks to everyone who contributed!
* Gary Deen
* Gary N McKinney
* George Robles
* Gregor Lütolf
* J. Eckert
* Jason Galarneau
* Joe Korzeniewski
* Josh Daniels
* Joshua David Gregory
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Korneel Bullens
* Lamin Kivelä
* M Khorakiwala
* Makespace Madrid
* Mark Lane
* Mark Qvist
* Mark Walker
* Masayoshi Mitsui
* Michael Aumock
* Michael McDargh Sr
* Miles Flavel
* Nikolai Langer
* Noe Ruiz
* Patrick McGinnis
* Peter Grace
@@ -68,10 +63,11 @@ thanks to everyone who contributed!
* Shane Ekerbicer
* Simon Hallam
* Stefan Krister
* Stephane Schittly
* Steven Pearson
* Sven Mueller
* Terrance Shaw
* Thomas Hatley
* Trent Shumay
and 968 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 989 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+50 -12
View File
@@ -308,6 +308,17 @@ PrintCancelled
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of cancelling, if available
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
* ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114`
* ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected
tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT
be accurate)
* ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the
feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will
NOT be accurate)
.. deprecated:: 1.3.0
@@ -324,6 +335,17 @@ PrintPaused
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of pausing, if available
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
* ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114`
* ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected
tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT
be accurate)
* ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the
feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will
NOT be accurate)
.. deprecated:: 1.3.0
@@ -352,37 +374,53 @@ GCODE processing
----------------
PowerOn
The GCode has turned on the printer power via M80
An ``M80`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
PowerOff
The GCODE has turned on the printer power via M81
An ``M81`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Home
The head has gone home via G28
A ``G28`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
ZChange
The printer's Z-Height has changed (new layer)
The printer's Z-Height has changed (new layer) through a ``G0`` or ``G1`` that was sent to the printer through OctoPrint
(not triggered when printing from SD!)
Paused
The print has been paused
Dwell
A ``G4`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Waiting
The print is paused due to a gcode wait command
One of the following commands was sent to the printer through OctoPrint (not triggered when printing from SD!):
``M0``, ``M1``, ``M226``
Cooling
The GCODE has enabled the platform cooler via M245
An ``M245`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Alert
The GCODE has issued a user alert (beep) via M300
An ``M300`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Conveyor
The GCODE has enabled the conveyor belt via M240
An ``M240`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Eject
The GCODE has enabled the part ejector via M40
An ``M40`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
EStop
The GCODE has issued a panic stop via M112
An ``M112`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
PositionUpdate
The response to an ``M114`` was received by OctoPrint. The payload contains the current position information
parsed from the response and (in the case of the selected tool ``t`` and the current feedrate ``f``) tracked
by OctoPrint.
Payload:
* ``x``: x coordinate, parsed from response
* ``y``: y coordinate, parsed from response
* ``z``: z coordinate, parsed from response
* ``e``: e coordinate, parsed from response
* ``t``: last tool selected *through OctoPrint*
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
Timelapses
----------
+27
View File
@@ -60,9 +60,36 @@ All GCODE scripts have access to the following template variables through the te
* ``printer_profile``: The currently selected Printer Profile, including
information such as the extruder count, the build volume size, the filament diameter etc.
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!)
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
and ``script.name`` respectively.
There are a couple of additional template variables available for the following specific scripts:
* ``afterPrintPaused`` and ``beforePrintResumed``
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
``t`` taken from commands sent through OctoPrint.
* ``afterPrintCancelled``
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
current tool ``t`` taken from commands sent through OctoPrint.
.. warning::
Note that current firmware implementations only report back one ``E`` value, the current extrusion value for the current
extruder. Retrieving all ``E`` values by cycling through all extruders on pause and cancel is something OctoPrint
currently does NOT do since it would simply take too long. That means that if you want to write a ``beforePrintResumed``
script that basically resets everything back to the point when the printer was paused *and* you are running with
multiple extruders, you'll have to find some other way to have your ``E`` values set correctly for all your available
extruders - the data available in ``pause_position`` will *not* suffice. Additionally, most firmwares don't report
the currently selected tool in the ``M114`` response, meaning that the only way OctoPrint can keep track of that is
by tracking it itself. Same goes for the current feed rate ``F``. So if you are printing from SD, this data will be
*wrong*. This is also the reason why OctoPrint currently doesn't bundle a more sophisticated pause and resume script
that would actually move the print head out of the way and pause and back to the original position on resume - it
might cause issues for the multitude of users out there with multi-extruder setups or for people printing from the
printer's SD, thanks to the lack of information the firmware provides.
The :ref:`predefined GCODE scripts <sec-features-gcode_scripts-predefined>` are also called with the following additional
template variables:
+4
View File
@@ -14,6 +14,10 @@
``OctoPrint.options.baseurl``
The base URL of the OctoPrint API
``OctoPrint.options.locale``
The locale to set in ``X-Locale`` headers on API requests. Useful for API
endpoints that might return localized content.
.. js:data:: OctoPrint.plugins
Registration of client library components provided by plugins.
+99 -13
View File
@@ -18,10 +18,6 @@ __revision__ = versions.get('full-revisionid', versions.get('full', None))
del versions
del get_versions
#~~ sane logging defaults
log.basicConfig()
#~~ try to ensure a sound SSL environment
urllib3_ssl = True
@@ -61,10 +57,21 @@ class FatalStartupError(BaseException):
def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
logging_config=None, debug=False, verbosity=0, uncaught_logger=None,
uncaught_handler=None, after_settings=None, after_logging=None):
uncaught_handler=None, safe_mode=False, after_preinit_logging=None,
after_settings=None, after_logging=None, after_safe_mode=None):
kwargs = dict()
logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler)
kwargs["logger"] = logger
kwargs["recorder"] = recorder
if callable(after_preinit_logging):
after_preinit_logging(**kwargs)
settings = init_settings(basedir, configfile)
kwargs["settings"] = settings
if callable(after_settings):
after_settings(settings)
after_settings(**kwargs)
logger = init_logging(settings,
use_logging_file=use_logging_file,
@@ -74,11 +81,20 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
verbosity=verbosity,
uncaught_logger=uncaught_logger,
uncaught_handler=uncaught_handler)
if callable(after_logging):
after_logging(logger)
kwargs["logger"] = logger
plugin_manager = init_pluginsystem(settings)
return settings, logger, plugin_manager
if callable(after_logging):
after_logging(**kwargs)
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
safe_mode = safe_mode or settings_safe_mode
kwargs["safe_mode"] = safe_mode
if callable(after_safe_mode):
after_safe_mode(**kwargs)
plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode)
return settings, logger, safe_mode, plugin_manager
def init_settings(basedir, configfile):
@@ -94,6 +110,45 @@ def init_settings(basedir, configfile):
raise FatalStartupError(message)
def preinit_logging(debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None):
config = {
"version": 1,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
}
},
"loggers": {
"octoprint": {
"level": "DEBUG" if debug else "INFO"
},
"octoprint.util": {
"level": "INFO"
}
},
"root": {
"level": "WARN",
"handlers": ["console"]
}
}
logger = set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler)
from octoprint.logging.handlers import RecordingLogHandler
recorder = RecordingLogHandler(level=log.DEBUG)
log.getLogger().addHandler(recorder)
return logger, recorder
def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None):
"""Sets up logging."""
@@ -182,6 +237,11 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
else:
config = default_config
# configure logging globally
return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler)
def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler):
# configure logging globally
import logging.config as logconfig
logconfig.dictConfig(config)
@@ -207,19 +267,45 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
if uncaught_handler is None:
def exception_logger(exc_type, exc_value, exc_tb):
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
uncaught_handler = exception_logger
sys.excepthook = uncaught_handler
return logger
def init_pluginsystem(settings):
def init_pluginsystem(settings, safe_mode=False):
"""Initializes the plugin manager based on the settings."""
from octoprint.plugin import plugin_manager
pm = plugin_manager(init=True, settings=settings)
import os
logger = log.getLogger(__name__)
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
settings.getBaseFolder("plugins")]
plugin_entry_points = ["octoprint.plugin"]
plugin_disabled_list = settings.get(["plugins", "_disabled"])
plugin_validators = []
if safe_mode:
def validator(phase, plugin_info):
if phase == "after_load":
setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled)
setattr(plugin_info, "safe_mode_enabled", False)
elif phase == "before_enable":
if not plugin_info.bundled:
setattr(plugin_info, "safe_mode_enabled", True)
return False
return True
plugin_validators.append(validator)
from octoprint.plugin import plugin_manager
pm = plugin_manager(init=True,
plugin_folders=plugin_folders,
plugin_entry_points=plugin_entry_points,
plugin_disabled_list=plugin_disabled_list,
plugin_validators=plugin_validators)
settings_overlays = dict()
disabled_from_overlays = dict()
+6 -2
View File
@@ -13,10 +13,11 @@ import octoprint
class OctoPrintContext(object):
"""Custom context wrapping the standard options."""
def __init__(self, configfile=None, basedir=None, verbosity=0):
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
self.safe_mode = safe_mode
pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True)
"""Decorator to pass in the :class:`OctoPrintContext` instance."""
@@ -95,6 +96,8 @@ def standard_options(hidden=False):
help="Specify the config file to use."),
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Increase logging verbosity"),
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Enable safe mode; disables all third party plugins")
]
return bulk_options(options)
@@ -120,9 +123,10 @@ from .server import server_commands
from .plugins import plugin_commands
from .dev import dev_commands
from .client import client_commands
from .config import config_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands])
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands])
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__)
+221
View File
@@ -0,0 +1,221 @@
# 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import logging
from octoprint import init_settings, FatalStartupError
from octoprint.cli import pass_octoprint_ctx, standard_options, bulk_options
import yaml
import json
import pprint
def _to_settings_path(path):
if not isinstance(path, (list, tuple)):
path = filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))
return path
def _set_helper(settings, path, value, data_type=None):
path = _to_settings_path(path)
method = settings.set
if data_type is not None:
name = None
if data_type == bool:
name = "setBoolean"
elif data_type == float:
name = "setFloat"
elif data_type == int:
name = "setInt"
if name is not None:
method = getattr(settings, name)
method(path, value)
settings.save()
#~~ "octoprint config" commands
@click.group()
def config_commands():
pass
@config_commands.group(name="config")
@pass_octoprint_ctx
@click.pass_context
def config(ctx, obj):
"""Basic config manipulation."""
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
try:
obj.settings = init_settings(obj.basedir, obj.configfile)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
ctx.exit(-1)
@config.command(name="set")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--bool", "as_bool", is_flag=True,
help="Interpret value as bool")
@click.option("--float", "as_float", is_flag=True,
help="Interpret value as float")
@click.option("--int", "as_int", is_flag=True,
help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True,
help="Parse value from json")
@pass_octoprint_ctx
@click.pass_context
def set_command(ctx, obj, path, value, as_bool, as_float, as_int, as_json):
"""Sets a config path to the provided value."""
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
data_type = None
if as_bool:
data_type = bool
elif as_float:
data_type = float
elif as_int:
data_type = int
_set_helper(obj.settings, path, value, data_type=data_type)
@config.command(name="remove")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@pass_octoprint_ctx
def remove_command(obj, path):
"""Removes a config path."""
_set_helper(obj.settings, path, None)
@config.command(name="append_value")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--json", "as_json", is_flag=True)
@pass_octoprint_ctx
@click.pass_context
def append_value_command(ctx, obj, path, value, as_json=False):
"""Appends value to list behind config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot append to non-list value at given path", err=True)
ctx.exit(-1)
current.append(value)
_set_helper(obj.settings, path, current)
@config.command(name="insert_value")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("index", type=click.INT)
@click.argument("value", type=click.STRING)
@click.option("--json", "as_json", is_flag=True)
@pass_octoprint_ctx
@click.pass_context
def insert_value_command(ctx, obj, path, index, value, as_json=False):
"""Inserts value at index of list behind config key."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot insert into non-list value at given path", err=True)
ctx.exit(-1)
current.insert(index, value)
_set_helper(obj.settings, path, current)
@config.command(name="remove_value")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--json", "as_json", is_flag=True)
@pass_octoprint_ctx
@click.pass_context
def remove_value_command(ctx, obj, path, value, as_json=False):
"""Removes value from list at config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
if not value in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
current.remove(value)
_set_helper(obj.settings, path, current)
@config.command(name="get")
@click.argument("path", type=click.STRING)
@click.option("--json", "as_json", is_flag=True,
help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True,
help="Output value formatted as YAML")
@click.option("--raw", "as_raw", is_flag=True,
help="Output value as raw string representation")
@standard_options(hidden=True)
@pass_octoprint_ctx
def get_command(obj, path, as_json=False, as_yaml=False, as_raw=False):
"""Retrieves value from config path."""
path = _to_settings_path(path)
value = obj.settings.get(path, merged=True)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
click.echo(output)
+1 -1
View File
@@ -51,7 +51,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
from octoprint import init_settings, init_pluginsystem, FatalStartupError
try:
self.settings = init_settings(ctx.obj.basedir, ctx.obj.configfile)
self.plugin_manager = init_pluginsystem(self.settings)
self.plugin_manager = init_pluginsystem(self.settings, safe_mode=ctx.obj.safe_mode)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings or the plugin system.", err=True)
+34 -15
View File
@@ -11,13 +11,26 @@ import sys
from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, octoprint_daemon = None):
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, octoprint_daemon=None):
"""Initializes the environment and starts up the server."""
from octoprint import init_platform, __display_version__, FatalStartupError
def log_startup(_):
logging.getLogger("octoprint.server").info("Starting OctoPrint {}".format(__display_version__))
def log_startup(recorder=None, safe_mode=None, **kwargs):
logger = logging.getLogger("octoprint.server")
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if recorder and len(recorder):
logger.info("--- Logged during platform initialization: ---")
from octoprint.logging.handlers import CombinedLogHandler
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
logger.info("----------------------------------------------")
from octoprint import urllib3_ssl
if not urllib3_ssl:
@@ -30,13 +43,14 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
try:
settings, _, plugin_manager = init_platform(basedir,
configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
after_logging=log_startup)
settings, _, safe_mode, plugin_manager = init_platform(basedir,
configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
after_safe_mode=log_startup)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error starting up OctoPrint.", err=True)
@@ -47,6 +61,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
host=host,
port=port,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
octoprint_daemon=octoprint_daemon)
octoprint_server.run()
@@ -62,7 +77,7 @@ server_options = bulk_options([
help="Specify the config file to use for configuring logging."),
click.option("--iknowwhatimdoing", "allow_root", is_flag=True,
help="Allow OctoPrint to run as user root."),
click.option("--debug", is_flag=True, help="Enable debug mode"),
click.option("--debug", is_flag=True, help="Enable debug mode.")
])
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
@@ -82,7 +97,7 @@ def server_commands(obj):
def serve_command(obj, host, port, logging, allow_root, debug):
"""Starts the OctoPrint server."""
run_server(obj.basedir, obj.configfile, host, port, debug,
allow_root, logging, obj.verbosity)
allow_root, logging, obj.verbosity, obj.safe_mode)
@server_commands.command(name="daemon")
@@ -111,7 +126,7 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
Daemon.__init__(self, pidfile)
self._basedir = basedir
@@ -122,12 +137,16 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity, self)
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
octoprint_daemon=self)
octoprint_daemon = OctoPrintDaemon(pid, octoprint_ctx.basedir, octoprint_ctx.configfile,
host, port, debug, allow_root, logging, octoprint_ctx.verbosity)
host, port, debug, allow_root, logging, octoprint_ctx.verbosity,
octoprint_ctx.safe_mode)
if command == "start":
octoprint_daemon.start()
+53
View File
@@ -81,3 +81,56 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
self.cleanupFiles()
if not self.delay:
self.stream = self._open()
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
self._buffer = []
self._target = target
def emit(self, record):
self._buffer.append(record)
def setTarget(self, target):
self._target = target
def flush(self):
if not self._target:
return
self.acquire()
try:
for record in self._buffer:
self._target.handle(record)
self._buffer = []
finally:
self.release()
def close(self):
self.flush()
self.acquire()
try:
self._buffer = []
finally:
self.release()
def __len__(self):
return len(self._buffer)
class CombinedLogHandler(logging.Handler):
def __init__(self, *handlers):
logging.Handler.__init__(self)
self._handlers = handlers
def setHandlers(self, *handlers):
self._handlers = handlers
def handle(self, record):
self.acquire()
try:
if self._handlers:
for handler in self._handlers:
handler.handle(record)
finally:
self.release()
+21 -33
View File
@@ -42,9 +42,10 @@ def _validate_plugin(phase, plugin_info):
if not "octoprint.accesscontrol.appkey" in hooks:
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
return True
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None, settings=None):
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -87,14 +88,6 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
else:
if init:
if settings is None:
settings = s()
if plugin_folders is None:
plugin_folders = (
settings.getBaseFolder("plugins"),
(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True)
)
if plugin_types is None:
plugin_types = [StartupPlugin,
ShutdownPlugin,
@@ -109,22 +102,17 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
ProgressPlugin,
WizardPlugin,
UiPlugin]
if plugin_entry_points is None:
plugin_entry_points = "octoprint.plugin"
if plugin_disabled_list is None:
plugin_disabled_list = settings.get(["plugins", "_disabled"])
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = [
"octoprint.server.http"
]
plugin_restart_needing_hooks = ["octoprint.server.http"]
if plugin_obsolete_hooks is None:
plugin_obsolete_hooks = [
"octoprint.comm.protocol.gcode"
]
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
if plugin_validators is None:
plugin_validators = [
_validate_plugin
]
plugin_validators = [_validate_plugin]
else:
plugin_validators.append(_validate_plugin)
_instance = PluginManager(plugin_folders,
plugin_types,
@@ -145,7 +133,7 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr
Arguments:
plugin_key (string): The plugin identifier for which to create the settings instance.
defaults (dict): The default settings for the plugin.
defaults (dict): The default settings for the plugin, if different from get_settings_defaults.
get_preprocessors (dict): The getter preprocessors for the plugin.
set_preprocessors (dict): The setter preprocessors for the plugin.
settings (octoprint.settings.Settings): The settings instance to use.
@@ -180,13 +168,12 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return None
try:
defaults = instance.get_settings_defaults()
get_preprocessors, set_preprocessors = instance.get_settings_preprocessors()
except:
logging.getLogger(__name__).exception("Error while retrieving defaults or preprocessors for plugin {}".format(plugin_key))
logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key))
return None
return plugin_settings(plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
@@ -315,11 +302,12 @@ class PluginSettings(object):
self.settings = settings
self.plugin_key = plugin_key
if defaults is None:
defaults = dict()
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
self.defaults["plugins"][plugin_key]["_config_version"] = None
if defaults is not None:
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
self.defaults["plugins"][plugin_key]["_config_version"] = None
else:
self.defaults = None
if get_preprocessors is None:
get_preprocessors = dict()
@@ -345,14 +333,14 @@ class PluginSettings(object):
return result
def add_getter_kwargs(kwargs):
if not "defaults" in kwargs:
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
return kwargs
def add_setter_kwargs(kwargs):
if not "defaults" in kwargs:
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
+17 -2
View File
@@ -149,6 +149,8 @@ class PluginInfo(object):
self._license = license
def validate(self, phase, additional_validators=None):
result = True
if phase == "before_load":
# if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__
if hasattr(self.instance, self.__class__.attr_init):
@@ -183,7 +185,9 @@ class PluginInfo(object):
if additional_validators is not None:
for validator in additional_validators:
validator(phase, self)
result = result and validator(phase, self)
return result
def __str__(self):
if self.version:
@@ -448,6 +452,12 @@ class PluginManager(object):
if logging_prefix is None:
logging_prefix = ""
if plugin_folders is None:
plugin_folders = []
if plugin_types is None:
plugin_types = []
if plugin_entry_points is None:
plugin_entry_points = []
if plugin_disabled_list is None:
plugin_disabled_list = []
@@ -740,7 +750,9 @@ class PluginManager(object):
plugin = self.plugins[name]
try:
plugin.validate("before_load", additional_validators=self.plugin_validators)
if not plugin.validate("before_load", additional_validators=self.plugin_validators):
return
plugin.load()
plugin.validate("after_load", additional_validators=self.plugin_validators)
self.on_plugin_loaded(name, plugin)
@@ -802,6 +814,9 @@ class PluginManager(object):
raise PluginCantEnable(name, "Dependency on obsolete hooks detected, full functionality cannot be guaranteed")
try:
if not plugin.validate("before_enable", additional_validators=self.plugin_validators):
return False
plugin.enable()
self._activate_plugin(name, plugin)
except PluginLifecycleException as e:
+23 -3
View File
@@ -1368,14 +1368,17 @@ class SettingsPlugin(OctoPrintPlugin):
to retrieve the data in the correct format.
The default implementation will also replace any paths that have been restricted by your plugin through
:func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with ``None`` values where necessary.
:func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with either the provided
default value (if one was provided), an empty dictionary (as fallback for restricted dictionaries), an
empty list (as fallback for restricted lists) or ``None`` values where necessary.
Make sure to do your own restriction if you decide to fully overload this method.
:return: the current settings of the plugin, as a dictionary
"""
from flask_login import current_user
import copy
data = self._settings.get_all_data()
data = copy.deepcopy(self._settings.get_all_data(merged=True))
if self.config_version_key in data:
del data[self.config_version_key]
@@ -1397,8 +1400,25 @@ class SettingsPlugin(OctoPrintPlugin):
node = node[entry]
key = path[-1]
default_value_available = False
default_value = None
if isinstance(key, (list, tuple)):
# key, default_value tuple
key, default_value = key
default_value_available = True
if key in node:
node[key] = None
if default_value_available:
if callable(default_value):
default_value = default_value()
node[key] = default_value
else:
if isinstance(node[key], dict):
node[key] = dict()
elif isinstance(node[key], (list, tuple)):
node[key] = []
else:
node[key] = None
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous,
admin=lambda: current_user is not None and not current_user.is_anonymous and current_user.is_admin,
@@ -71,7 +71,7 @@ $(function() {
});
};
self.onWizardTabChange = function(current, next) {
self.onBeforeWizardTabChange = function(next, current) {
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
return true;
}
@@ -13,19 +13,19 @@ to OctoPrint, you can also configure additional printer profiles under Settings
<div class="tab-content scrollable">
<!-- ko with: editor -->
<div id="wizard_plugin_corewizard_printerprofile_general" class="tab-pane active">
{% include '_snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
</div>
<div id="wizard_plugin_corewizard_printerprofile_buildvolume" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
</div>
<div id="wizard_plugin_corewizard_printerprofile_axes" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
</div>
<div id="wizard_plugin_corewizard_printerprofile_extruder" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
</div>
<!-- /ko -->
</div>
@@ -8,12 +8,12 @@
<h4>{{ _('OctoPrint related commands') }}</h4>
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/server/serverCommandServerRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
</form>
<h4>{{ _('System related commands') }}</h4>
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "_snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
</form>
@@ -26,8 +26,8 @@
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
</form>
<h4>{{ _('Timelapse Recordings') }}</h4>
@@ -38,5 +38,5 @@
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/webcam/ffmpegPath.jinja2" %}
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
</form>
@@ -8,13 +8,13 @@
{% endtrans %}</p>
<form class="form-horizontal">
{% include "_snippets/settings/cura/enginePath.jinja2" %}
{% include "_snippets/settings/cura/engineLog.jinja2" %}
{% include "snippets/settings/cura/enginePath.jinja2" %}
{% include "snippets/settings/cura/engineLog.jinja2" %}
</form>
<h4>{{ _('Profiles') }}</h4>
{% include "_snippets/settings/cura/profiles.jinja2" %}
{% include "snippets/settings/cura/profiles.jinja2" %}
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
@@ -22,4 +22,4 @@
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
</div>
{% include "_snippets/settings/cura/profileImporter.jinja2" %}
{% include "snippets/settings/cura/profileImporter.jinja2" %}
@@ -7,7 +7,7 @@
<div style="margin-top: 1em">
<form class="form-horizontal">
{% include "_snippets/settings/cura/enginePath.jinja2" %}
{% include "snippets/settings/cura/enginePath.jinja2" %}
</form>
</div>
</div>
@@ -15,10 +15,11 @@
<div data-bind="visible: unconfiguredSlicingProfile">
<h3>{{ _('Set up a slicing profile') }}</h3>
<p>{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine
yet. You should do this now.{% endtrans %}</p>
yet. If you plan on slicing from within OctoPrint then you should do this now.
Otherwise just skip this step.{% endtrans %}</p>
<div>
{% include "_snippets/settings/cura/profiles.jinja2" %}
{% include "snippets/settings/cura/profiles.jinja2" %}
</div>
<button class="btn btn-block" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
+26 -10
View File
@@ -34,6 +34,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
pip_inapplicable_arguments = dict(uninstall=["--user"])
def __init__(self):
self._pending_enable = set()
self._pending_disable = set()
@@ -180,6 +182,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if not admin_permission.can():
return make_response("Insufficient rights", 403)
from octoprint.server import safe_mode
refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues
if refresh_repository:
self._repository_available = self._refresh_repository()
@@ -200,7 +204,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
virtual_env=self._pip_caller.virtual_env,
additional_args=self._settings.get(["pip_args"]),
python=sys.executable
))
),
safe_mode=safe_mode)
def etag():
import hashlib
@@ -208,6 +213,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
hash.update(repr(self._get_plugins()))
hash.update(str(self._repository_available))
hash.update(repr(self._repository_plugins))
hash.update(repr(safe_mode))
return hash.hexdigest()
def condition():
@@ -450,7 +456,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
needs_restart_api = needs_restart and not pending
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
try:
@@ -482,8 +489,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
additional_args = self._settings.get(["pip_args"])
if additional_args:
args.append(additional_args)
if additional_args is not None:
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)
if additional_args:
args.append(additional_args)
return self._pip_caller.execute(*args)
@@ -514,12 +528,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
if not needs_restart:
if not needs_restart and not getattr(plugin, "safe_mode_victim", False):
self._plugin_manager.enable_plugin(plugin.key)
else:
if plugin.key in self._pending_disable:
self._pending_disable.remove(plugin.key)
elif not plugin.enabled and plugin.key not in self._pending_enable:
elif (not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_enable:
self._pending_enable.add(plugin.key)
def _mark_plugin_disabled(self, plugin, needs_restart=False):
@@ -529,12 +543,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
if not needs_restart:
if not needs_restart and not getattr(plugin, "safe_mode_victim", False):
self._plugin_manager.disable_plugin(plugin.key)
else:
if plugin.key in self._pending_enable:
self._pending_enable.remove(plugin.key)
elif plugin.enabled and plugin.key not in self._pending_disable:
elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key)
def _fetch_repository_from_disk(self):
@@ -688,8 +702,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
bundled=plugin.bundled,
managable=plugin.managable,
enabled=plugin.enabled,
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
safe_mode_victim=getattr(plugin, "safe_mode_victim", False),
safe_mode_enabled=getattr(plugin, "safe_mode_enabled", False),
pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False) and plugin.key in self._pending_enable),
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable),
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
origin=plugin.origin.type
@@ -155,6 +155,8 @@ $(function() {
self.pipAdditionalArgs = ko.observable();
self.pipPython = ko.observable();
self.safeMode = ko.observable();
self.pipUseUserString = ko.pureComputed(function() {
return self.pipUseUser() ? "yes" : "no";
});
@@ -186,7 +188,8 @@ $(function() {
});
self.enableToggle = function(data) {
return self.enableManagement() && data.key != 'pluginmanager';
var command = self._getToggleCommand(data);
return self.enableManagement() && (command == "disable" || !data.safe_mode_victim || data.safe_mode_enabled) && data.key != 'pluginmanager';
};
self.enableUninstall = function(data) {
@@ -199,7 +202,7 @@ $(function() {
};
self.enableRepoInstall = function(data) {
return self.enableManagement() && self.pipAvailable() && self.isCompatible(data);
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data);
};
self.invalidUrl = ko.pureComputed(function() {
@@ -209,7 +212,7 @@ $(function() {
self.enableUrlInstall = ko.pureComputed(function() {
var url = self.installUrl();
return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl();
});
self.invalidArchive = ko.pureComputed(function() {
@@ -219,7 +222,7 @@ $(function() {
self.enableArchiveInstall = ko.pureComputed(function() {
var name = self.uploadFilename();
return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && name !== undefined && name.trim() != "" && !self.invalidArchive();
});
self.uploadElement.fileupload({
@@ -246,7 +249,7 @@ $(function() {
done: function(e, data) {
self._markDone();
self.uploadButton.unbind("click");
self.uploadFilename("");
self.uploadFilename(undefined);
},
fail: function(e, data) {
new PNotify({
@@ -257,7 +260,7 @@ $(function() {
});
self._markDone();
self.uploadButton.unbind("click");
self.uploadFilename("");
self.uploadFilename(undefined);
}
});
@@ -278,6 +281,8 @@ $(function() {
self._fromPluginsResponse(data.plugins);
self._fromRepositoryResponse(data.repository);
self._fromPipResponse(data.pip);
self.safeMode(data.safe_mode || false);
};
self._fromPluginsResponse = function(data) {
@@ -347,6 +352,7 @@ $(function() {
};
if (self._getToggleCommand(data) == "enable") {
if (data.safe_mode_victim && !data.safe_mode_enabled) return;
OctoPrint.plugins.pluginmanager.enable(data.key)
.done(onSuccess)
.fail(onError);
@@ -547,7 +553,7 @@ $(function() {
title: titleSuccess,
text: textRestart,
buttons: {
closer: false,
closer: true,
sticker: false
},
callbacks: {
@@ -600,7 +606,7 @@ $(function() {
}]
},
buttons: {
closer: false,
closer: true,
sticker: false
},
callbacks: {
@@ -640,8 +646,9 @@ $(function() {
self.loglines.removeAll();
self.loglines.push({line: line, stream: "message"});
self._scrollWorkingOutputToEnd();
self.workingDialog.modal("show");
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
self._markDone = function() {
@@ -655,7 +662,8 @@ $(function() {
};
self._getToggleCommand = function(data) {
return ((!data.enabled || data.pending_disable) && !data.pending_enable) ? "enable" : "disable";
var disable = (data.enabled || data.pending_enable || (data.safe_mode_victim && data.safe_mode_enabled)) && !data.pending_disable;
return disable ? "disable" : "enable";
};
self.toggleButtonCss = function(data) {
@@ -666,7 +674,16 @@ $(function() {
};
self.toggleButtonTitle = function(data) {
return self._getToggleCommand(data) == "enable" ? gettext("Enable Plugin") : gettext("Disable Plugin");
var command = self._getToggleCommand(data);
if (command == "enable") {
if (data.safe_mode_victim && !data.safe_mode_enabled) {
return gettext("Disabled due to active safe mode");
} else {
return gettext("Enable Plugin");
}
} else {
return gettext("Disable Plugin");
}
};
self.onBeforeBinding = function() {
@@ -682,6 +699,10 @@ $(function() {
};
self.onUserLoggedOut = function() {
self._closeAllNotifications();
};
self._closeAllNotifications = function() {
if (self.notifications) {
_.each(self.notifications, function(notification) {
notification.remove();
@@ -689,6 +710,11 @@ $(function() {
}
};
self.onServerDisconnect = function() {
self._closeAllNotifications();
return true;
};
self.onStartup = function() {
self.workingDialog = $("#settings_plugin_pluginmanager_workingdialog");
self.workingOutput = $("#settings_plugin_pluginmanager_workingdialog_output");
@@ -721,7 +747,7 @@ $(function() {
if (messageType == "loglines" && self.working()) {
_.each(data.loglines, function(line) {
self.loglines.push(line);
self.loglines.push(self._preprocessLine(line));
});
self._scrollWorkingOutputToEnd();
} else if (messageType == "result") {
@@ -836,6 +862,14 @@ $(function() {
self.requestData();
}
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function(line) {
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
}
}
// view model class, parameters for constructor, container to bind to
@@ -13,8 +13,16 @@
{% endtrans %}</div>
{% endmacro %}
{% macro pluginmanager_safemode() %}
<div class="alert" data-bind="visible: safeMode">{% trans %}
Safe mode is currently active. All third party plugins are disabled and cannot be
enabled. Installation of plugin packages is disabled.
{% endtrans %}</div>
{% endmacro %}
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ 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>
@@ -32,7 +40,7 @@
<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></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="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></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>
@@ -80,7 +88,6 @@
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
@@ -99,6 +106,7 @@
<div class="modal-body">
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
<h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
<div class="dropdown pull-right">
@@ -794,9 +794,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
try:
util.execute(restart_command)
except exceptions.ScriptError as e:
self._logger.exception("Error while restarting")
self._logger.warn("Restart stdout:\n%s" % e.stdout)
self._logger.warn("Restart stderr:\n%s" % e.stderr)
self._logger.exception("Error while restarting via command {}".format(restart_command))
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
self._logger.warn("Restart stderr:\n{}".format(e.stderr))
raise exceptions.RestartFailed()
def _populated_check(self, target, check):
@@ -882,7 +882,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines]))
for line in lines:
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
self._console_logger.debug(u"{} {}".format(prefix, line))
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data))
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import errno
import sys
import traceback
import time
def _log_call(*lines):
_log(lines, prefix=">", stream="call")
@@ -27,7 +29,9 @@ def _log(lines, prefix=None, stream=None):
output_stream = sys.stderr
for line in lines:
print(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), file=output_stream)
to_print = _to_str(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")),
errors="replace")
print(to_print, file=output_stream)
def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
@@ -38,6 +42,14 @@ def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
return s_or_u
def _to_str(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a str."""
if isinstance(s_or_u, unicode):
return s_or_u.encode(encoding, errors=errors)
else:
return s_or_u
def _execute(command, **kwargs):
import sarge
@@ -51,39 +63,54 @@ def _execute(command, **kwargs):
try:
p = sarge.run(command, **kwargs)
p.wait_events()
except Exception as e:
import traceback
exception_lines = traceback.format_exc()
error = "Error while trying to run command {}: {}\n{}".format(joined_command, str(e), exception_lines)
return None, "", error
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
print("Error while trying to run command {}".format(joined_command), file=sys.stderr)
return None, [], []
except:
print("Error while trying to run command {}".format(joined_command), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
all_stdout = []
all_stderr = []
try:
while p.returncode is None:
while p.commands[0].poll() is None:
lines = p.stderr.readlines(timeout=0.5)
if lines:
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
_log_stderr(*lines)
all_stderr += list(lines)
lines = p.stdout.readlines(timeout=0.5)
if lines:
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
_log_stdout(*lines)
all_stdout += list(lines)
p.commands[0].poll()
finally:
p.close()
lines = p.stderr.readlines()
if lines:
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
_log_stderr(*lines)
all_stderr += lines
lines = p.stdout.readlines()
if lines:
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
_log_stdout(*lines)
all_stdout += lines
@@ -97,27 +124,31 @@ def _get_git_executables():
return GITS
def _git(args, cwd, verbose=False, git_executable=None):
def _git(args, cwd, git_executable=None):
if git_executable is not None:
commands = [git_executable]
else:
commands = _get_git_executables()
for c in commands:
command = [c] + args
try:
return _execute([c] + args, cwd=cwd)
return _execute(command, cwd=cwd)
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % args[0])
print(e)
return None, None, None
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
except:
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None, None, None
print("Unable to find git command, tried {}".format(", ".join(commands)), file=sys.stderr)
return None, [], []
def _python(args, cwd, python_executable, sudo=False):
@@ -127,31 +158,40 @@ def _python(args, cwd, python_executable, sudo=False):
try:
return _execute(command, cwd=cwd)
except:
return None, None, None
import traceback
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
def _to_error(*lines):
return u"".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
if len(lines) == 1:
if isinstance(lines[0], (list, tuple)):
lines = lines[0]
elif not isinstance(lines[0], (str, unicode)):
lines = [repr(lines[0]),]
return u"\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
def _rescue_changes(git_executable, folder):
print(">>> Running: git diff --shortstat")
returncode, stdout, stderr = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git diff\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if stdout and "".join(stdout).strip():
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git diff\" failed with returncode {}".format(returncode))
if stdout and u"".join(stdout).strip():
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
import time
import os
timestamp = time.strftime("%Y%m%d%H%M")
patch = os.path.join(folder, "%s-preupdate.patch" % timestamp)
patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp))
print(">>> Running: git diff and saving output to %s" % timestamp)
print(">>> Running: git diff and saving output to {}".format(patch))
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to %s" % patch)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format(patch))
with open(patch, "wb") as f:
import codecs
with codecs.open(patch, "w", encoding="utf-8", errors="replace") as f:
for line in stdout:
f.write(line)
@@ -164,46 +204,45 @@ def update_source(git_executable, folder, target, force=False, branch=None):
if _rescue_changes(git_executable, folder):
print(">>> Running: git reset --hard")
returncode, stdout, stderr = _git(["reset", "--hard"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode {}".format(returncode))
print(">>> Running: git clean -f -d -e *-preupdate.patch")
returncode, stdout, stderr = _git(["clean", "-f", "-d", "-e", "*-preupdate.patch"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git clean -f\" failed with returcode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git clean -f\" failed with returncode {}".format(returncode))
print(">>> Running: git fetch")
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git fetch\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
print(stdout)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git fetch\" failed with returncode {}".format(returncode))
if branch is not None and branch.strip() != "":
print(">>> Running: git checkout {}".format(branch))
returncode, stdout, stderr = _git(["checkout", branch], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git checkout\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git checkout\" failed with returncode {}".format(returncode))
print(">>> Running: git pull")
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git pull\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git pull\" failed with returncode {}".format(returncode))
if force:
reset_command = ["reset", "--hard"]
reset_command += [target]
print(">>> Running: git %s" % " ".join(reset_command))
print(">>> Running: git {}".format(" ".join(reset_command)))
returncode, stdout, stderr = _git(reset_command, folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Error while updating, \"git %s\" failed with returncode %d: %s" % (" ".join(reset_command), returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Error while updating, \"git {}\" failed with returncode {}".format(" ".join(reset_command), returncode))
def install_source(python_executable, folder, user=False, sudo=False):
print(">>> Running: python setup.py clean")
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
if returncode != 0:
print("\"python setup.py clean\" failed with returncode %d: %s" % (returncode, stdout))
if returncode is None or returncode != 0:
print("\"python setup.py clean\" failed with returncode {}".format(returncode))
print("Continuing anyways")
print(">>> Running: python setup.py install")
@@ -211,15 +250,14 @@ def install_source(python_executable, folder, user=False, sudo=False):
if user:
args.append("--user")
returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo)
if returncode != 0:
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode {}".format(returncode))
def parse_arguments():
import argparse
boolean_trues = ["true", "yes", "1"]
boolean_falses = ["false", "no", "0"]
parser = argparse.ArgumentParser(prog="update-octoprint.py")
@@ -103,6 +103,8 @@ $(function() {
self.workingOutput = undefined;
self.loglines = ko.observableArray([]);
self.checking = ko.observable(false);
self.octoprintUnconfigured = ko.observable();
self.octoprintUnreleased = ko.observable();
@@ -333,7 +335,7 @@ $(function() {
};
}
if (ignoreSeen || !self._hasNotificationBeenSeen(data.information)) {
if ((ignoreSeen || !self._hasNotificationBeenSeen(data.information)) && !OctoPrint.coreui.wizardOpen) {
self._showPopup(options, eventListeners);
}
} else if (data.status == "current") {
@@ -351,9 +353,13 @@ $(function() {
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
if (!self.loginState.isUser()) return;
self.checking(true);
OctoPrint.plugins.softwareupdate.check(force)
.done(function(data) {
self.fromCheckResponse(data, ignoreSeen, showIfNothingNew);
})
.always(function() {
self.checking(false);
});
};
@@ -454,7 +460,7 @@ $(function() {
self.working(true);
self.workingTitle(title);
self.workingDialog.modal("show");
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
self._markWorking = function(title, line, stream) {
@@ -482,7 +488,7 @@ $(function() {
self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight - self.workingOutput.height());
};
self.onWizardTabChange = function(current, next) {
self.onBeforeWizardTabChange = function(next, current) {
if (next && _.startsWith(next, "wizard_plugin_softwareupdate")) {
// switching to the plugin wizard tab
self._copyConfig();
@@ -539,7 +545,7 @@ $(function() {
case "loglines": {
if (self.working()) {
_.each(messageData.loglines, function(line) {
self.loglines.push(line);
self.loglines.push(self._preprocessLine(line));
});
self._scrollWorkingOutputToEnd();
}
@@ -557,6 +563,7 @@ $(function() {
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
self.loglines.push({line: text, stream: "message"});
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
self._scrollWorkingOutputToEnd();
self._updatePopup({
text: text,
hide: false,
@@ -584,6 +591,7 @@ $(function() {
};
self.loglines.push({line: text, stream: "message"});
self._scrollWorkingOutputToEnd();
self.waitingForRestart = true;
self.restartTimeout = setTimeout(function() {
@@ -694,6 +702,13 @@ $(function() {
}
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function(line) {
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
}
}
// view model class, parameters for constructor, container to bind to
@@ -57,12 +57,12 @@
</ul>
</div>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }">{{ _('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="icon-spinner icon-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 class="hide">
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }">{{ _('Force check for update (overrides cache used for update checks)') }}</button>
<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>
</div>
</div>
@@ -74,9 +74,9 @@
</div>
<div class="modal-body">
<form class="form-horizontal">
{% include "_snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
{% include "_snippets/plugins/softwareupdate/versionTracking.jinja2" %}
{% include "_snippets/plugins/softwareupdate/releaseChannel.jinja2" %}
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
{% include "snippets/plugins/softwareupdate/releaseChannel.jinja2" %}
<div class="control-group">
<label class="control-label">{{ _('Version cache TTL') }}</label>
<div class="controls">
@@ -96,7 +96,6 @@
<div id="settings_plugin_softwareupdate_workingdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
@@ -6,8 +6,8 @@
</p>{% endtrans %}
<form class="form-horizontal">
{% include "_snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
{% include "_snippets/plugins/softwareupdate/versionTracking.jinja2" %}
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
</form>
{% trans %}<p>
@@ -59,15 +59,17 @@ class VirtualPrinter(object):
self.lastTempAt = time.time()
self.bedTemp = 1.0
self.bedTargetTemp = 1.0
self.speeds = settings().get(["devel", "virtualPrinter", "movementSpeed"])
self._relative = True
self._lastX = 0.0
self._lastY = 0.0
self._lastZ = 0.0
self._lastE = 0.0
self._lastF = 200
self._unitModifier = 1
self._feedrate_multiplier = 100
self._flowrate_multiplier = 100
self._virtualSd = settings().getBaseFolder("virtualSd")
self._sdCardReady = True
@@ -92,6 +94,8 @@ class VirtualPrinter(object):
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"])
self.currentLine = 0
self.lastN = 0
@@ -317,7 +321,7 @@ class VirtualPrinter(object):
def _gcode_M140(self, data):
self._parseBedCommand(data)
def _gcode_M140(self, data):
def _gcode_M190(self, data):
self._parseBedCommand(data, wait=True, support_r=True)
def _gcode_M105(self, data):
@@ -378,11 +382,21 @@ class VirtualPrinter(object):
self._send(output)
return True
def _gcode_M115(self, data):
output = "FIRMWARE_NAME:{} PROTOCOL_VERSION:1.0".format(self._firmwareName)
self._send(output)
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_M220(self, data):
self._feedrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
def _gcode_M221(self, data):
self._flowrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
def _gcode_M400(self, data):
self.buffered.join()
@@ -631,16 +645,18 @@ class VirtualPrinter(object):
if settings().getBoolean(["devel", "virtualPrinter", "includeCurrentToolInTemps"]):
if includeTarget:
output = "T:%.2f /%.2f %s @:64\n" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder] + 1, allTempsString)
output = "T:%.2f /%.2f %s" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder] + 1, allTempsString)
else:
output = "T:%.2f %s @:64\n" % (self.temp[self.currentExtruder], allTempsString)
output = "T:%.2f %s" % (self.temp[self.currentExtruder], allTempsString)
else:
output = "%s @:64\n" % allTempsString
output = allTempsString
else:
if includeTarget:
output = "T:%.2f /%.2f B:%.2f /%.2f @:64\n" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp)
output = "T:%.2f /%.2f B:%.2f /%.2f" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp)
else:
output = "T:%.2f B:%.2f @:64\n" % (self.temp[0], self.bedTemp)
output = "T:%.2f B:%.2f" % (self.temp[0], self.bedTemp)
output += " @:64\n"
if includeOk:
output = "ok " + output
@@ -696,46 +712,72 @@ class VirtualPrinter(object):
matchY = re.search("Y([0-9.]+)", line)
matchZ = re.search("Z([0-9.]+)", line)
matchE = re.search("E([0-9.]+)", line)
matchF = re.search("F([0-9.]+)", line)
duration = 0
if matchF is not None:
try:
self._lastF = float(matchF.group(1))
except:
pass
speedXYZ = self._lastF * (self._feedrate_multiplier / 100.0)
speedE = self._lastF * (self._flowrate_multiplier / 100.0)
if matchX is not None:
try:
x = float(matchX.group(1))
if self._relative or self._lastX is None:
duration = max(duration, x * self._unitModifier / float(self.speeds["x"]) * 60.0)
duration = max(duration, x * self._unitModifier / speedXYZ * 60.0)
else:
duration = max(duration, (x - self._lastX) * self._unitModifier / float(self.speeds["x"]) * 60.0)
self._lastX = x
duration = max(duration, (x - self._lastX) * self._unitModifier / speedXYZ * 60.0)
if self._relative and self._lastX is not None:
self._lastX += x
else:
self._lastX = x
except:
pass
if matchY is not None:
try:
y = float(matchY.group(1))
if self._relative or self._lastY is None:
duration = max(duration, y * self._unitModifier / float(self.speeds["y"]) * 60.0)
duration = max(duration, y * self._unitModifier / speedXYZ * 60.0)
else:
duration = max(duration, (y - self._lastY) * self._unitModifier / float(self.speeds["y"]) * 60.0)
self._lastY = y
duration = max(duration, (y - self._lastY) * self._unitModifier / speedXYZ * 60.0)
if self._relative and self._lastY is not None:
self._lastY += y
else:
self._lastY = y
except:
pass
if matchZ is not None:
try:
z = float(matchZ.group(1))
if self._relative or self._lastZ is None:
duration = max(duration, z * self._unitModifier / float(self.speeds["z"]) * 60.0)
duration = max(duration, z * self._unitModifier / speedXYZ * 60.0)
else:
duration = max(duration, (z - self._lastZ) * self._unitModifier / float(self.speeds["z"]) * 60.0)
self._lastZ = z
duration = max(duration, (z - self._lastZ) * self._unitModifier / speedXYZ * 60.0)
if self._relative and self._lastZ is not None:
self._lastZ += z
else:
self._lastZ = z
except:
pass
if matchE is not None:
try:
e = float(matchE.group(1))
if self._relative or self._lastE is None:
duration = max(duration, e * self._unitModifier / float(self.speeds["e"]) * 60.0)
duration = max(duration, e * self._unitModifier / speedE * 60.0)
else:
duration = max(duration, (e - self._lastE) * self._unitModifier / float(self.speeds["e"]) * 60.0)
self._lastE = e
duration = max(duration, (e - self._lastE) * self._unitModifier / speedE * 60.0)
if self._relative and self._lastE is not None:
self._lastE += e
else:
self._lastE = e
except:
pass
+30 -19
View File
@@ -393,7 +393,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd and not settings().getBoolean(["feature", "sdRelativePath"]) else path, sd)
self._comm.selectFile("/" + path if sd else path, sd)
self._setProgressData(completion=0)
self._setCurrentZ(None)
@@ -405,6 +405,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setProgressData(completion=0)
self._setCurrentZ(None)
def get_file_position(self):
if self._comm is None:
return None
if self._selectedFile is None:
return None
return self._comm.getFilePosition()
def start_print(self, pos=None):
"""
Starts the currently loaded print job.
@@ -478,12 +487,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# mark print as failure
if self._selectedFile is not None:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
payload = {
"file": self._selectedFile["filename"],
"origin": FileDestinations.LOCAL
}
if self._selectedFile["sd"]:
payload["origin"] = FileDestinations.SDCARD
payload = self._payload_for_print_job_event()
eventManager().fire(Events.PRINT_FAILED, payload)
def get_state_string(self, state=None):
@@ -754,7 +758,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
if progress is None or printTime is None or cleanedPrintTime is None:
return None
return None, None
dumbTotalPrintTime = printTime / progress
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
@@ -956,8 +960,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def on_comm_temperature_update(self, temp, bedTemp):
self._addTemperatureData(copy.deepcopy(temp), copy.deepcopy(bedTemp))
def on_comm_position_update(self, position):
eventManager().fire(Events.POSITION_UPDATE, position)
def on_comm_position_update(self, position, reason=None):
payload = dict(reason=reason)
payload.update(position)
eventManager().fire(Events.POSITION_UPDATE, payload)
def on_comm_state_change(self, state):
"""
@@ -1066,7 +1072,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
eventManager().fire(Events.PRINT_FAILED, payload)
def on_comm_print_job_cancelled(self):
payload = self._payload_for_print_job_event()
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
if payload:
eventManager().fire(Events.PRINT_CANCELLED, payload)
self.script("afterPrintCancelled",
@@ -1074,7 +1080,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
must_be_set=False)
def on_comm_print_job_paused(self):
payload = self._payload_for_print_job_event()
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
if payload:
eventManager().fire(Events.PRINT_PAUSED, payload)
self.script("afterPrintPaused",
@@ -1120,7 +1126,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):
def _payload_for_print_job_event(self, location=None, print_job_file=None, position=None):
if print_job_file is None:
selected_file = self._selectedFile
if not selected_file:
@@ -1145,13 +1151,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
_, name = self._fileManager.split_path(FileDestinations.LOCAL, path)
origin = FileDestinations.LOCAL
return dict(name=name,
path=path,
origin=origin,
result= dict(name=name,
path=path,
origin=origin,
# TODO deprecated, remove in 1.4.0
file=full_path,
filename=name)
# TODO deprecated, remove in 1.4.0
file=full_path,
filename=name)
if position is not None:
result["position"] = position
return result
class StateMonitor(object):
+23 -3
View File
@@ -33,6 +33,7 @@ app = Flask("octoprint")
assets = None
babel = None
debug = False
safe_mode = False
printer = None
printerProfileManager = None
@@ -112,12 +113,13 @@ def load_user(id):
class Server(object):
def __init__(self, settings=None, plugin_manager=None, host="0.0.0.0", port=5000, debug=False, allow_root=False, octoprint_daemon=None):
def __init__(self, settings=None, plugin_manager=None, host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False, octoprint_daemon=None):
self._settings = settings
self._plugin_manager = plugin_manager
self._host = host
self._port = port
self._debug = debug
self._safe_mode = safe_mode
self._allow_root = allow_root
self._octoprint_daemon = octoprint_daemon
self._server = None
@@ -155,11 +157,13 @@ class Server(object):
global pluginLifecycleManager
global preemptiveCache
global debug
global safe_mode
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
debug = self._debug
safe_mode = self._safe_mode
self._logger = logging.getLogger(__name__)
pluginManager = self._plugin_manager
@@ -245,7 +249,14 @@ class Server(object):
return props
def settings_plugin_inject_factory(name, implementation):
"""Factory for additional injections depending on plugin type"""
"""Factory for additional injections/initializations depending on plugin type"""
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
return
default_settings_overlay = dict(plugins=dict())
default_settings_overlay["plugins"][name] = implementation.get_settings_defaults()
self._settings.add_overlay(default_settings_overlay, at_end=True)
plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin(name, implementation)
if plugin_settings is None:
return
@@ -272,7 +283,8 @@ class Server(object):
implementation.on_settings_initialized()
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory]
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory,
settings_plugin_inject_factory]
pluginManager.initialize_implementations()
settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
@@ -487,6 +499,11 @@ class Server(object):
def on_after_startup():
self._logger.info("Listening on http://%s:%d" % (self._host, self._port))
if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]):
self._logger.info("Server started successfully in safe mode as requested from config, removing flag")
self._settings.setBoolean(["server", "startOnceInSafeMode"], False)
self._settings.save()
# now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
# which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
# or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
@@ -567,6 +584,9 @@ class Server(object):
if "l10n" in request.values:
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
if "X-Locale" in request.headers:
return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES)
if hasattr(g, "identity") and g.identity and userManager.enabled:
userid = g.identity.id
try:
+11 -7
View File
@@ -40,6 +40,7 @@ def _etag(lm=None):
import hashlib
hash = hashlib.sha1()
hash.update(str(lm))
hash.update(repr(settings().effective))
hash.update(repr(connection_options))
hash.update(repr(plugins))
hash.update(repr(roles))
@@ -103,7 +104,8 @@ def getSettings():
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]),
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"])
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
"firmwareDetection": s.getBoolean(["feature", "firmwareDetection"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -273,6 +275,7 @@ def _saveSettings(data):
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"])
if "serial" in data.keys():
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
@@ -356,9 +359,10 @@ def _saveSettings(data):
except:
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
if s.save():
payload = dict(
config_hash=s.config_hash,
effective_hash=s.effective_hash
)
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
s.save()
payload = dict(
config_hash=s.config_hash,
effective_hash=s.effective_hash
)
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
+5 -5
View File
@@ -129,19 +129,19 @@ def _get_core_command_specs():
commands = collections.OrderedDict(
shutdown=dict(
command=s().get(["server", "commands", "systemShutdownCommand"]),
name=gettext("Shutdown"),
name=gettext("Shutdown system"),
confirm=gettext("You are about to shutdown the system.")),
reboot=dict(
command=s().get(["server", "commands", "systemRestartCommand"]),
name=gettext("Reboot"),
name=gettext("Reboot system"),
confirm=gettext("You are about to reboot the system.")),
restart=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name="Restart OctoPrint",
confirm="You are about to restart the OctoPrint server.")
name=gettext("Restart OctoPrint"),
confirm=gettext("You are about to restart the OctoPrint server."))
)
available_commands = dict()
available_commands = collections.OrderedDict()
for action, spec in commands.items():
if not spec["command"]:
continue
+12 -1
View File
@@ -40,7 +40,8 @@ def _config_for_timelapse(timelapse):
return dict(type="timed",
postRoll=timelapse.post_roll,
fps=timelapse.fps,
interval=timelapse.interval)
interval=timelapse.interval,
capturePostRoll=timelapse.capture_post_roll)
else:
return dict(type="off")
@@ -210,6 +211,15 @@ def setTimelapseConfig():
else:
return make_response("Invalid value for interval: %d" % interval)
if "capturePostRoll" in data:
config["options"]["capturePostRoll"] = True
try:
capturePostRoll = bool(data["capturePostRoll"])
except ValueError:
return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"])
else:
config["options"]["capturePostRoll"] = capturePostRoll
if "retractionZHop" in data:
config["options"] = {
"retractionZHop": 0
@@ -225,6 +235,7 @@ def setTimelapseConfig():
else:
return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop)
if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
octoprint.timelapse.configure_timelapse(config, True)
else:
+3 -1
View File
@@ -77,7 +77,9 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
display_version=octoprint.server.DISPLAY_VERSION,
branch=octoprint.server.BRANCH,
plugin_hash=plugin_hash.hexdigest(),
config_hash=config_hash
config_hash=config_hash,
debug=octoprint.server.debug,
safe_mode=octoprint.server.safe_mode
))
self._printer.register_callback(self)
+8 -6
View File
@@ -27,7 +27,7 @@ from . import util
import logging
_logger = logging.getLogger(__name__)
_templates = None
_templates = dict()
_plugin_names = None
_plugin_vars = None
@@ -159,19 +159,21 @@ def index():
preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"])
locale = g.locale.language if g.locale else "en"
# helper to check if wizards are active
def wizard_active(templates):
return templates is not None and bool(templates["wizard"]["order"])
# we force a refresh if the client forces one or if we have wizards cached
force_refresh = util.flask.cache_check_headers() or "_refresh" in request.values or wizard_active(_templates)
force_refresh = util.flask.cache_check_headers() or "_refresh" in request.values or wizard_active(_templates.get(locale))
# if we need to refresh our template cache or it's not yet set, process it
if force_refresh or _templates is None or _plugin_names is None or _plugin_vars is None:
_templates, _plugin_names, _plugin_vars = _process_templates()
if force_refresh or _templates.get(locale) is None or _plugin_names is None or _plugin_vars is None:
_templates[locale], _plugin_names, _plugin_vars = _process_templates()
now = datetime.datetime.utcnow()
render_kwargs = _get_render_kwargs(_templates, _plugin_names, _plugin_vars, now)
render_kwargs = _get_render_kwargs(_templates[locale], _plugin_names, _plugin_vars, now)
def get_preemptively_cached_view(key, view, data=None, additional_request_data=None, additional_unless=None):
if (data is None and additional_request_data is None) or g.locale is None:
@@ -304,7 +306,7 @@ def index():
return view(now, request, render_kwargs)
def default_view():
wizard = wizard_active(_templates)
wizard = wizard_active(_templates[locale])
enable_accesscontrol = userManager.enabled
accesscontrol_active = enable_accesscontrol and userManager.hasBeenCustomized()
render_kwargs.update(dict(
+98 -28
View File
@@ -103,7 +103,7 @@ default_settings = {
"maxWritePasses": 5,
"additionalPorts": [],
"additionalBaudrates": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
"checksumRequiringCommands": ["M110"],
"helloCommand": "M110 N0",
"disconnectOnErrors": True,
@@ -118,6 +118,7 @@ default_settings = {
"host": "0.0.0.0",
"port": 5000,
"firstRun": True,
"startOnceInSafeMode": False,
"seenWizards": {},
"secretKey": None,
"reverseProxy": {
@@ -166,7 +167,8 @@ default_settings = {
"type": "off",
"options": {},
"postRoll": 0,
"fps": 25
"fps": 25,
"capturePostRoll": True
},
"cleanTmpAfterDays": 7
},
@@ -197,7 +199,8 @@ default_settings = {
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7,
"supportFAsCommand": False,
"modelSizeDetection": True
"modelSizeDetection": True,
"firmwareDetection": True
},
"folder": {
"uploads": None,
@@ -332,12 +335,6 @@ default_settings = {
"numExtruders": 1,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"movementSpeed": {
"x": 6000,
"y": 6000,
"z": 200,
"e": 300
},
"hasBed": True,
"repetierStyleTargetTemperature": False,
"repetierStyleResends": False,
@@ -354,7 +351,8 @@ default_settings = {
"supportM112": True,
"echoOnM117": True,
"brokenM29": True,
"supportF": False
"supportF": False,
"firmwareName": "Virtual Marlin 1.0"
}
}
}
@@ -835,12 +833,17 @@ class Settings(object):
self._migrate_config(config)
return config
def add_overlay(self, overlay):
self._map.maps.insert(1, overlay)
def add_overlay(self, overlay, at_end=False):
if at_end:
pos = len(self._map.maps) - 1
self._map.maps.insert(pos, overlay)
else:
self._map.maps.insert(1, overlay)
def _migrate_config(self, config=None):
def _migrate_config(self, config=None, persist=False):
if config is None:
config = self._config
persist = True
dirty = False
@@ -848,12 +851,14 @@ class Settings(object):
self._migrate_event_config,
self._migrate_reverse_proxy_config,
self._migrate_printer_parameters,
self._migrate_gcode_scripts
self._migrate_gcode_scripts,
self._migrate_core_system_commands
)
for migrate in migrators:
dirty = migrate(config) or dirty
if dirty:
if dirty and persist:
self.save(force=True)
def _migrate_gcode_scripts(self, config):
@@ -1062,6 +1067,67 @@ class Settings(object):
else:
return False
def _migrate_core_system_commands(self, config):
"""
Migrates system commands for restart, reboot and shutdown as defined on OctoPi or
according to the official setup guide to new core system commands to remove
duplication.
If server commands for action is not yet set, migrates command. Otherwise only
deletes definition from custom system commands.
"""
changed = False
migration_map = dict(shutdown="systemShutdownCommand",
reboot="systemRestartCommand",
restart="serverRestartCommand")
if "system" in config and "actions" in config["system"]:
actions = config["system"]["actions"]
to_delete = []
for index, spec in enumerate(actions):
action = spec.get("action")
command = spec.get("command")
if action is None or command is None:
continue
migrate_to = migration_map.get(action)
if migrate_to is not None:
if not "server" in config or not "commands" in config["server"] or not migrate_to in config["server"]["commands"]:
if not "server" in config:
config["server"] = dict()
if not "commands" in config["server"]:
config["server"]["commands"] = dict()
config["server"]["commands"][migrate_to] = command
self._logger.info("Migrated {} action to server.commands.{}".format(action, migrate_to))
to_delete.append(index)
self._logger.info("Deleting {} action from configured system commands, superseeded by server.commands.{}".format(action, migrate_to))
for index in reversed(to_delete):
actions.pop(index)
changed = True
if changed:
# let's make a backup of our current config, in case someone wants to roll back to an
# earlier version and needs to recover the former system commands for that
backup_path = self.backup("system_command_migration")
self._logger.info("Made a copy of the current config at {} to allow recovery of manual system command configuration".format(backup_path))
return changed
def backup(self, suffix, path=None):
import shutil
if path is None:
path = os.path.dirname(self._configfile)
basename = os.path.basename(self._configfile)
name, ext = os.path.splitext(basename)
backup = os.path.join(path, "{}.{}{}".format(name, suffix, ext))
shutil.copy(self._configfile, backup)
return backup
def save(self, force=False):
if not self._dirty and not force:
return False
@@ -1105,12 +1171,14 @@ class Settings(object):
else:
chain = self._map
if preprocessors is None:
preprocessors = self._get_preprocessors
preprocessor = None
if preprocessors is not None:
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
parent_path = path[:-1]
last = path[-1]
@@ -1310,15 +1378,17 @@ class Settings(object):
else:
chain = self._map
preprocessor = None
if preprocessors is not None:
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
if preprocessors is None:
preprocessors = self._set_preprocessors
if callable(preprocessor):
value = preprocessor(value)
preprocessor = None
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
if callable(preprocessor):
value = preprocessor(value)
try:
current = chain.get_by_path(path)
+6 -1
View File
@@ -46,7 +46,8 @@
OctoPrint.options = {
"baseurl": undefined,
"apikey": undefined
"apikey": undefined,
"locale": undefined
};
OctoPrint.plugins = {};
@@ -65,6 +66,10 @@
var headers = $.extend({}, additional);
headers["X-Api-Key"] = OctoPrint.options.apikey;
if (OctoPrint.options.locale !== undefined) {
headers["X-Locale"] = OctoPrint.options.locale;
}
return headers;
};
+15 -4
View File
@@ -13,6 +13,8 @@ function DataUpdater(allViewModels) {
self._lastProcessingTimes = [];
self._lastProcessingTimesSize = 20;
self._safeModePopup = undefined;
self.increaseThrottle = function() {
self.setThrottle(self._throttleFactor + 1);
};
@@ -115,16 +117,25 @@ 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._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");
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
}
} else {
callViewModels(self.allViewModels, "onServerConnect");
}
+26 -9
View File
@@ -832,17 +832,21 @@ function callViewModelsIf(allViewModels, method, condition, callback) {
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty(method) && condition(viewModel, method)) {
if (callback == undefined) {
if (parameters != undefined) {
// call the method with the provided parameters
viewModel[method].apply(viewModel, parameters);
try {
if (callback == undefined) {
if (parameters != undefined) {
// call the method with the provided parameters
viewModel[method].apply(viewModel, parameters);
} else {
// call the method without parameters
viewModel[method]();
}
} else {
// call the method without parameters
viewModel[method]();
// provide the method to the callback
callback(viewModel[method], viewModel);
}
} else {
// provide the method to the callback
callback(viewModel[method], viewModel);
} catch (exc) {
log.error("Error calling", method, "on view model", viewModel.constructor.name, ":", (exc.stack || exc));
}
}
});
@@ -861,3 +865,16 @@ var sizeObservable = function(observable) {
}
})
};
var getQueryParameterByName = function(name, url) {
// from http://stackoverflow.com/a/901144/2028598
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
+8 -1
View File
@@ -13,6 +13,11 @@ $(function() {
OctoPrint.options.baseurl = BASEURL;
OctoPrint.options.apikey = UI_API_KEY;
var l10n = getQueryParameterByName("l10n");
if (l10n) {
OctoPrint.options.locale = l10n;
}
OctoPrint.socket.onMessage("connected", function(data) {
var payload = data.data;
OctoPrint.options.apikey = payload.apikey;
@@ -31,7 +36,9 @@ $(function() {
OctoPrint.coreui = (function() {
var exports = {
browserTabVisibility: undefined,
selectedTab: undefined
selectedTab: undefined,
settingsOpen: false,
wizardOpen: false
};
var browserVisibilityCallbacks = [];
@@ -91,6 +91,8 @@ $(function() {
};
self.onEventSettingsUpdated = function (payload) {
// the webcam url might have changed, make sure we replace it now if the tab is focused
self._enableWebcam();
self.requestData();
};
@@ -378,9 +380,9 @@ $(function() {
}
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
if (currentSrc === undefined || currentSrc.trim() == "") {
var newSrc = CONFIG_WEBCAM_STREAM;
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
var newSrc = self.settings.webcam_streamUrl();
if (currentSrc != newSrc) {
if (newSrc.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
@@ -402,13 +402,10 @@ $(function() {
if (!file) {
return;
}
OctoPrint.files.select(file.origin, file.path)
.done(function() {
var withinPrintDimensions = self.evaluatePrintDimensions(file, true);
if (withinPrintDimensions && printAfterLoad) {
OctoPrint.job.start();
}
});
var withinPrintDimensions = self.evaluatePrintDimensions(file, true);
var print = printAfterLoad && withinPrintDimensions;
OctoPrint.files.select(file.origin, file.path, print);
};
self.removeFile = function(file, event) {
@@ -444,20 +441,6 @@ $(function() {
};
self._removeEntry = function(entry, event) {
var index = self.listHelper.paginatedItems().indexOf(entry) + 1;
if (index >= self.listHelper.paginatedItems().length) {
index = index - 2;
}
if (index < 0) {
index = 0;
}
var focus = undefined;
var fileToFocus = self.listHelper.paginatedItems()[index];
if (fileToFocus) {
focus = {location: fileToFocus.origin, path: fileToFocus.path};
}
self.activeRemovals.push(entry.origin + ":" + entry.path);
var finishActiveRemoval = function() {
self.activeRemovals(_.filter(self.activeRemovals(), function(e) {
@@ -488,10 +471,7 @@ $(function() {
var deferred = $.Deferred();
OctoPrint.files.delete(entry.origin, entry.path)
.done(function() {
self.requestData({
focus: focus,
switchToPath: (entry.parent ? entry.parent.path : "")
})
self.requestData()
.done(function() {
deferred.resolve();
})
@@ -16,6 +16,10 @@ $(function() {
});
self.outstanding = [];
self.active = false;
self.sawUpdateEventWhileActive = false;
self.ignoreNextUpdateEvent = false;
self.settingsDialog = undefined;
self.settings_dialog_update_detected = undefined;
self.translationManagerDialog = undefined;
@@ -133,6 +137,7 @@ $(function() {
self.feature_pollWatched = ko.observable(undefined);
self.feature_ignoreIdenticalResends = ko.observable(undefined);
self.feature_modelSizeDetection = ko.observable(undefined);
self.feature_firmwareDetection = ko.observable(undefined);
self.serial_port = ko.observable();
self.serial_baudrate = ko.observable();
@@ -355,12 +360,14 @@ $(function() {
self.allViewModels = allViewModels;
self.settingsDialog.on('show', function(event) {
OctoPrint.coreui.settingsOpen = true;
if (event.target.id == "settings_dialog") {
self.requestTranslationData();
callViewModels(allViewModels, "onSettingsShown");
}
});
self.settingsDialog.on('hidden', function(event) {
OctoPrint.coreui.settingsOpen = false;
if (event.target.id == "settings_dialog") {
callViewModels(allViewModels, "onSettingsHidden");
}
@@ -727,6 +734,7 @@ $(function() {
self.settingsDialog.trigger("beforeSave");
self.sawUpdateEventWhileSending = false;
self.sending(data == undefined || options.sending || false);
if (data == undefined) {
@@ -734,10 +742,15 @@ $(function() {
data = getOnlyChangedData(self.getLocalData(), self.lastReceivedSettings);
}
self.active = true;
return OctoPrint.settings.save(data)
.done(function(data, status, xhr) {
self.ignoreNextUpdateEvent = !self.sawUpdateEventWhileSending;
self.active = false;
self.receiving(true);
self.sending(false);
try {
self.fromResponse(data);
if (options.success) options.success(data, status, xhr);
@@ -747,6 +760,7 @@ $(function() {
})
.fail(function(xhr, status, error) {
self.sending(false);
self.active = false;
if (options.error) options.error(xhr, status, error);
})
.always(function(xhr, status) {
@@ -755,6 +769,10 @@ $(function() {
};
self.onEventSettingsUpdated = function() {
if (self.active) {
self.sawUpdateEventWhileActive = true;
}
var preventSettingsRefresh = _.any(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onSettingsPreventRefresh")) {
try {
@@ -775,7 +793,8 @@ $(function() {
if (self.isDialogActive()) {
// dialog is open and not currently busy...
if (self.sending() || self.receiving()) {
if (self.sending() || self.receiving() || self.active || self.ignoreNextUpdateEvent) {
self.ignoreNextUpdateEvent = false;
return;
}
@@ -806,6 +825,12 @@ $(function() {
$('ul.nav-list a:first', self.settingsDialog).tab("show");
}
};
self.onServerReconnect = function() {
// the settings might have changed if the server was just restarted,
// better refresh them now
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push([
@@ -28,7 +28,9 @@ $(function() {
action.actionSource = "core";
actions.push(action);
});
actions.push({action: "divider"});
if (response.custom && response.custom.length) {
actions.push({action: "divider"});
}
}
_.each(response.custom, function(data) {
var action = _.extend({}, data);
@@ -10,12 +10,14 @@ $(function() {
self.defaultPostRoll = 0;
self.defaultInterval = 10;
self.defaultRetractionZHop = 0;
self.defaultCapturePostroll = true;
self.timelapseType = ko.observable(undefined);
self.timelapseTimedInterval = ko.observable(self.defaultInterval);
self.timelapsePostRoll = ko.observable(self.defaultPostRoll);
self.timelapseFps = ko.observable(self.defaultFps);
self.timelapseRetractionZHop = ko.observable(self.defaultRetractionZHop);
self.timelapseCapturePostRoll = ko.observable(self.defaultCapturePostRoll);
self.persist = ko.observable(false);
self.isDirty = ko.observable(false);
@@ -61,6 +63,9 @@ $(function() {
self.timelapseRetractionZHop.subscribe(function(newValue) {
self.isDirty(true);
});
self.timelapseCapturePostRoll.subscribe(function() {
self.isDirty(true);
});
// initialize list helper
self.listHelper = new ItemListHelper(
@@ -167,6 +172,12 @@ $(function() {
self.timelapseFps(self.defaultFps);
}
if (config.capturePostRoll != undefined){
self.timelapseCapturePostRoll(config.capturePostRoll);
} else {
self.timelapseCapturePostRoll(self.defaultCapturePostRoll);
}
self.persist(false);
self.isDirty(false);
};
@@ -214,6 +225,7 @@ $(function() {
if (self.timelapseType() == "timed") {
payload["interval"] = self.timelapseTimedInterval();
payload["capturePostRoll"] = self.timelapseCapturePostRoll();
}
if (self.timelapseType() == "zchange") {
@@ -43,6 +43,13 @@ $(function() {
self.onStartup = function() {
self.wizardDialog = $("#wizard_dialog");
self.wizardDialog.on('show', function(event) {
OctoPrint.coreui.wizardOpen = true;
});
self.wizardDialog.on('hidden', function(event) {
OctoPrint.coreui.wizardOpen = false;
});
self.reloadOverlay = $("#reloadui_overlay");
};
+1 -1
View File
@@ -1,7 +1,7 @@
<div id="add_folder_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>Create Folder</h3>
<h3>{{ _('Create Folder') }}</h3>
</div>
<div class="modal-body">
<p>{{ _('Please specify the name of the folder to create.') }}</p>
@@ -34,53 +34,67 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
<input type="checkbox" data-bind="checked: feature_firmwareDetection" id="settings-firmwareDetection"> {{ _('Enable automatic firmware detection') }}
<span class="help-inline">{% trans %}
If enabled, OctoPrint will try to figure out your printer's firmware automatically and adjust a couple of communication parameters based on that.
If that doesn't work out, or you want more granular control, uncheck this and the parameters in question will become visible for you to adjust.
{% endtrans %}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<div data-bind="visible: !feature_firmwareDetection()">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_disableExternalHeatupDetection" id="settings-featureExternalHeatupDetection"> {{ _('Disable detection of external heatups') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Send a checksum with the command')}}</label>
<div class="controls">
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="print" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumPrint"> {{ _('When printing') }}
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="always" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumAlways"> {{ _('Always') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="never" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumNever"> {{ _('Never') }}
</label>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_disableExternalHeatupDetection" id="settings-featureExternalHeatupDetection"> {{ _('Disable detection of external heatups') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Send a checksum with the command')}}</label>
<div class="controls">
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="print" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumPrint"> {{ _('When printing') }}
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="always" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumAlways"> {{ _('Always') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="never" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumNever"> {{ _('Never') }}
</label>
</div>
</div>
</div>
</form>
@@ -1,7 +1,7 @@
<h3>{{ _('Printer Profiles') }}</h3>
{% include "_snippets/settings/printerprofiles/profiles.jinja2" %}
{% include "snippets/settings/printerprofiles/profiles.jinja2" %}
<button class="btn pull-right" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog(); }">{{ _('Add Profile...') }}</button>
{% include "_snippets/settings/printerprofiles/profileEditor.jinja2" %}
{% include "snippets/settings/printerprofiles/profileEditor.jinja2" %}
@@ -1,7 +1,7 @@
<form class="form-horizontal">
<h3>{{ _('Commands') }}</h3>
{% include "_snippets/settings/server/serverCommandServerRestart.jinja2" %}
{% include "_snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "_snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
</form>
@@ -1,21 +1,21 @@
<h3>{{ _('Webcam') }}</h3>
<form class="form-horizontal">
{% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "_snippets/settings/webcam/webcamOrientation.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamOrientation.jinja2" %}
</form>
<h3>{{ _('Timelapse Recordings') }}</h3>
<form class="form-horizontal">
{% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
{% include "_snippets/settings/webcam/ffmpegPath.jinja2" %}
{% include "_snippets/settings/webcam/watermark.jinja2" %}
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
{% include "snippets/settings/webcam/watermark.jinja2" %}
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'icon-caret-right icon-caret-down', parent: '.form-horizontal', container: '.hide' }"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
{% include "_snippets/settings/webcam/ffmpegBitrate.jinja2" %}
{% include "_snippets/settings/webcam/ffmpegThreads.jinja2" %}
{% include "snippets/settings/webcam/ffmpegBitrate.jinja2" %}
{% include "snippets/settings/webcam/ffmpegThreads.jinja2" %}
</div>
</div>
</form>
+1 -1
View File
@@ -10,7 +10,7 @@
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
var CONFIG_LOGFILESPERPAGE = 10;
var CONFIG_USERSPERPAGE = 10;
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}";
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %}
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
@@ -15,19 +15,19 @@
<!-- ko with: printerProfiles.editor -->
<div class="tab-content">
<div id="settings_printerProfiles_editDialog_general" class="tab-pane active">
{% include '_snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
</div>
<div id="settings_printerProfiles_editDialog_buildvolume" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
</div>
<div id="settings_printerProfiles_editDialog_axes" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
</div>
<div id="settings_printerProfiles_editDialog_extruder" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
</div>
</div>
<!-- /ko -->
@@ -24,6 +24,13 @@
<input type="text" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<div id="webcam_timelapse_capturePostRoll" data-bind="visible: timelapseType() == 'timed'">
<label class="checkbox">
<input type="checkbox" data-bind="checked: timelapseCapturePostRoll, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser()"> {{ _('Capture post roll images') }}
<span class="help-block">{{ _('If this is unchecked, OctoPrint will simply repeat the last frame for the post roll instead of continuing to capture new frames.') }}</span>
</label>
</div>
<div id="webcam_timelapse_timedsettings" data-bind="visible: intervalInputEnabled">
<label for="webcam_timelapse_interval">{{ _('Interval') }}</label>
+45 -17
View File
@@ -303,7 +303,10 @@ def configure_timelapse(config=None, persist=False):
interval = 10
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
interval = config["options"]["interval"]
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps)
capture_post_roll = True
if "options" in config and "capturePostRoll" in config["options"] and isinstance(config["options"]["capturePostRoll"], bool):
capture_post_roll = config["options"]["capturePostRoll"]
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps, capture_post_roll=capture_post_roll)
notify_callbacks(current)
@@ -572,6 +575,19 @@ class Timelapse(object):
self._capture_success += 1
return True
def _copying_postroll(self):
with self._capture_mutex:
filename = os.path.join(self._capture_dir,
_capture_format.format(prefix=self._file_prefix) % self._image_number)
self._image_number += 1
if self._perform_capture(filename):
for _ in range(self._post_roll * self._fps):
newFile = os.path.join(self._capture_dir,
_capture_format.format(prefix=self._file_prefix) % self._image_number)
self._image_number += 1
shutil.copyfile(filename, newFile)
def clean_capture_dir(self):
if not os.path.isdir(self._capture_dir):
self._logger.warn("Cannot clean capture directory, it is unset")
@@ -604,16 +620,9 @@ class ZTimelapse(Timelapse):
}
def process_post_roll(self):
with self._capture_mutex:
filename = os.path.join(self._capture_dir, _capture_format.format(prefix=self._file_prefix) % self._image_number)
self._image_number += 1
if self._perform_capture(filename):
for _ in range(self._post_roll * self._fps):
newFile = os.path.join(self._capture_dir, _capture_format.format(prefix=self._file_prefix) % self._image_number)
self._image_number += 1
shutil.copyfile(filename, newFile)
# we always copy the final image for the whole post roll
# for z based timelapses
self._copying_postroll()
Timelapse.process_post_roll(self)
def _on_z_change(self, event, payload):
@@ -628,11 +637,12 @@ class ZTimelapse(Timelapse):
class TimedTimelapse(Timelapse):
def __init__(self, post_roll=0, interval=1, fps=25):
def __init__(self, post_roll=0, interval=1, fps=25, capture_post_roll=True):
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
self._interval = interval
if self._interval < 1:
self._interval = 1 # force minimum interval of 1s
self._capture_post_roll = capture_post_roll
self._postroll_captures = 0
self._timer = None
self._logger.debug("TimedTimelapse initialized")
@@ -641,11 +651,16 @@ class TimedTimelapse(Timelapse):
def interval(self):
return self._interval
@property
def capture_post_roll(self):
return self._capture_post_roll
def config_data(self):
return {
"type": "timed",
"options": {
"interval": self._interval
"interval": self._interval,
"capture_post_roll": self._capture_post_roll
}
}
@@ -662,14 +677,26 @@ class TimedTimelapse(Timelapse):
self._timer.start()
def on_print_done(self, event, payload):
self._postroll_captures = self._post_roll * self._fps
if self._capture_post_roll:
self._postroll_captures = self._post_roll * self._fps
else:
self._postroll_captures = 0
Timelapse.on_print_done(self, event, payload)
def calculate_post_roll(self):
return self._post_roll * self._fps * self._interval
if self._capture_post_roll:
return self._post_roll * self._fps * self._interval
else:
return Timelapse.calculate_post_roll(self)
def process_post_roll(self):
pass
if self._capture_post_roll:
return
# we only use the final image as post roll if we
# are not supposed to capture it
self._copying_postroll()
self.post_roll_finished()
def post_roll_finished(self):
Timelapse.post_roll_finished(self)
@@ -684,7 +711,8 @@ class TimedTimelapse(Timelapse):
self._postroll_captures -= 1
def _on_timer_finished(self):
self.post_roll_finished()
if self._capture_post_roll:
self.post_roll_finished()
class TimelapseRenderJob(object):
File diff suppressed because it is too large. Load diff
+10
View File
@@ -442,6 +442,16 @@ def to_unicode(s_or_u, encoding="utf-8", errors="strict"):
return s_or_u
def chunks(l, n):
"""
Yield successive n-sized chunks from l.
Taken from http://stackoverflow.com/a/312464/2028598
"""
for i in range(0, len(l), n):
yield l[i:i+n]
def is_running_from_source():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
return os.path.isdir(os.path.join(root, "src")) and os.path.isfile(os.path.join(root, "setup.py"))
+149 -27
View File
@@ -28,7 +28,7 @@ from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue
to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue, chunks
try:
import _winreg
@@ -113,7 +113,7 @@ Groups will be as follows:
* ``target``: new target temperature (float)
"""
regex_position = re.compile("X:(?P<x>{float})\s+Y:(?P<y>{float})\s+Z:(?P<z>{float})\s+E:(?P<e>{float})".format(float=regex_float_pattern))
regex_position = re.compile("X:(?P<x>{float})\s*Y:(?P<y>{float})\s*Z:(?P<z>{float})\s*E:(?P<e>{float})".format(float=regex_float_pattern))
"""Regex for matching position reporting.
Groups will be as follows:
@@ -124,6 +124,9 @@ Groups will be as follows:
* ``e``: E coordinate
"""
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):")
"""Regex to use for splitting M115 responses."""
def serialList():
baselist=[]
if os.name=="nt":
@@ -310,6 +313,8 @@ class MachineCom(object):
self._neverSendChecksum = settings().getBoolean(["feature", "neverSendChecksum"])
self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"])
self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"])
self._sdAlwaysAvailable = settings().getBoolean(["feature", "sdAlwaysAvailable"])
self._sdRelativePath = settings().getBoolean(["feature", "sdRelativePath"])
self._currentLine = 1
self._line_mutex = threading.RLock()
self._resendDelta = None
@@ -319,7 +324,9 @@ class MachineCom(object):
self._currentResendCount = 0
self._resendSwallowRepetitions = settings().getBoolean(["feature", "ignoreIdenticalResends"])
self._resendSwallowRepetitionsCounter = 0
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
self._firmwareDetection = settings().getBoolean(["feature", "firmwareDetection"])
self._firmwareInfoReceived = not self._firmwareDetection
self._supportResendsWithoutOk = settings().getBoolean(["serial", "supportResendsWithoutOk"])
@@ -370,9 +377,11 @@ class MachineCom(object):
self._ignore_select = False
self._manualStreaming = False
self._last_position = PositionRecord()
self._pause_position = PositionRecord()
self.last_position = PositionRecord()
self.pause_position = PositionRecord()
self._record_pause_position = False
self.cancel_position = PositionRecord()
self._record_cancel_position = False
# print job
self._currentFile = None
@@ -669,10 +678,14 @@ class MachineCom(object):
context.update(replacements)
context.update(dict(
printer_profile=self._printerProfileManager.get_current_or_default(),
last_position=self._last_position,
pause_position=self._pause_position
last_position=self.last_position
))
if scriptName == "afterPrintPaused" or scriptName == "beforePrintResumed":
context.update(dict(pause_position=self.pause_position))
elif scriptName == "afterPrintCancelled":
context.update(dict(cancel_position=self.cancel_position))
template = settings().loadScript("gcode", scriptName, context=context)
if template is None:
scriptLines = []
@@ -793,6 +806,10 @@ class MachineCom(object):
if not self.isOperational():
# printer is not connected, can't use SD
return
if filename.startswith("/") and self._sdRelativePath:
filename = filename[1:]
self._sdFileToSelect = filename
self.sendCommand("M23 %s" % filename)
else:
@@ -806,6 +823,10 @@ class MachineCom(object):
self._currentFile = None
self._callback.on_comm_file_selected(None, None, False)
def _cancel_preparation_done(self):
self._recordFilePosition()
self._callback.on_comm_print_job_cancelled()
def cancelPrint(self, firmware_error=None):
if not self.isOperational() or self.isStreaming():
return
@@ -818,6 +839,7 @@ class MachineCom(object):
if self.isSdFileSelected():
self.sendCommand("M25") # pause print
self.sendCommand("M27") # get current byte position in file
self.sendCommand("M26 S0") # reset position in file to byte 0
if self._sd_status_timer is not None:
try:
@@ -825,8 +847,14 @@ class MachineCom(object):
except:
pass
self._recordFilePosition()
self._callback.on_comm_print_job_cancelled()
def _on_M400_sent():
# we don't call on_print_job_cancelled on our callback here
# because we do this only after our M114 has been answered
# by the firmware
self._record_cancel_position = True
self.sendCommand("M114")
self.sendCommand("M400", on_sent=_on_M400_sent)
def _pause_preparation_done(self):
self._callback.on_comm_print_job_paused()
@@ -907,7 +935,7 @@ class MachineCom(object):
return
self.sendCommand("M21")
if settings().getBoolean(["feature", "sdAlwaysAvailable"]):
if self._sdAlwaysAvailable:
self._sdAvailable = True
self.refreshSdFiles()
self._callback.on_comm_sd_state_change(self._sdAvailable)
@@ -939,15 +967,23 @@ class MachineCom(object):
##~~ record aborted file positions
def _recordFilePosition(self):
def getFilePosition(self):
if self._currentFile is None:
return
return None
origin = self._currentFile.getFileLocation()
filename = self._currentFile.getFilename()
pos = self._currentFile.getFilepos()
self._callback.on_comm_record_fileposition(origin, filename, pos)
return dict(origin=origin,
filename=filename,
pos=pos)
def _recordFilePosition(self):
if self._currentFile is None:
return
data = self.getFilePosition()
self._callback.on_comm_record_fileposition(data["origin"], data["filename"], data["pos"])
##~~ communication monitoring and handling
@@ -1101,7 +1137,9 @@ class MachineCom(object):
# ok only considered handled if it's alone on the line, might be
# a response to an M105 or an M114
self._handle_ok()
handled = (line == "wait" or line == "ok" or not ("T:" in line or "T0:" in line or "B:" in line or "C:" in line))
needs_further_handling = "T:" in line or "T0:" in line or "B:" in line or "C:" in line or \
"X:" in line or "FIRMWARE_NAME:" in line
handled = (line == "wait" or line == "ok" or not needs_further_handling)
# process resends
elif lower_line.startswith("resend") or lower_line.startswith("rs"):
@@ -1126,19 +1164,28 @@ class MachineCom(object):
# there's no way to query it from the firmware and
# no way to track it ourselves when not streaming
# the file - this all sucks sooo much
self._last_position.x = float(match.group("x"))
self._last_position.y = float(match.group("y"))
self._last_position.z = float(match.group("z"))
self._last_position.e = float(match.group("e"))
self._last_position.t = self._currentTool if not self.isSdFileSelected() else None
self._last_position.f = self._currentF if not self.isSdFileSelected() else None
self.last_position.x = float(match.group("x"))
self.last_position.y = float(match.group("y"))
self.last_position.z = float(match.group("z"))
self.last_position.e = float(match.group("e"))
self.last_position.t = self._currentTool if not self.isSdFileSelected() else None
self.last_position.f = self._currentF if not self.isSdFileSelected() else None
reason = None
if self._record_pause_position:
reason = "pause"
self._record_pause_position = False
self._pause_position.copy_from(self._last_position)
self.pause_position.copy_from(self.last_position)
self._pause_preparation_done()
self._callback.on_comm_position_update(self._last_position.as_dict())
if self._record_cancel_position:
reason = "cancel"
self._record_cancel_position = False
self.cancel_position.copy_from(self.last_position)
self._cancel_preparation_done()
self._callback.on_comm_position_update(self.last_position.as_dict(), reason=reason)
# temperature processing
elif ' T:' in line or line.startswith('T:') or ' T0:' in line or line.startswith('T0:') or ((' B:' in line or line.startswith('B:')) and not 'A:' in line):
@@ -1177,6 +1224,33 @@ class MachineCom(object):
except ValueError:
pass
##~~ firmware name & version
elif "FIRMWARE_NAME:" in line:
# looks like a response to M115
data = parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name))
if not self._firmwareInfoReceived and firmware_name:
if "repetier" in firmware_name.lower():
self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication")
self._alwaysSendChecksum = True
self._resendSwallowRepetitions = True
supportRepetierTargetTemp = True
disable_external_heatup_detection = True
sd_always_available = self._sdAlwaysAvailable
self._sdAlwaysAvailable = True
if not sd_always_available and not self._sdAvailable:
self.initSdCard()
elif "reprapfirmware" in firmware_name.lower():
self._logger.info("Detected RepRapFirmware, enabling relevant features for issue free communication")
self._sdRelativePath = True
self._firmwareInfoReceived = True
##~~ SD Card handling
elif 'SD init fail' in line or 'volume.init failed' in line or 'openRoot failed' in line:
self._sdAvailable = False
@@ -1498,6 +1572,8 @@ class MachineCom(object):
self._changeState(self.STATE_OPERATIONAL)
self.resetLineNumbers()
if self._firmwareDetection:
self.sendCommand("M115")
if self._sdAvailable:
self.refreshSdFiles()
@@ -1982,7 +2058,9 @@ class MachineCom(object):
# now comes the part where we increase line numbers and send stuff - no turning back now
command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands
command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands
checksum_enabled = self.isPrinting() or self._alwaysSendChecksum
checksum_enabled = not self._neverSendChecksum and (self.isPrinting() or
self._alwaysSendChecksum or
not self._firmwareInfoReceived)
command_to_send = command.encode("ascii", errors="replace")
if command_requiring_checksum or (command_allowing_checksum and checksum_enabled):
@@ -2188,6 +2266,16 @@ class MachineCom(object):
pass
_gcode_G1_sent = _gcode_G0_sent
def _gcode_G28_sent(self, cmd, cmd_type=None):
if "F" in cmd:
match = regexes_parameters["floatF"].search(cmd)
if match:
try:
f = float(match.group("value"))
self._currentF = f
except ValueError:
pass
def _gcode_M0_queuing(self, cmd, cmd_type=None):
self.setPause(True)
return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
@@ -2351,7 +2439,7 @@ class MachineComPrintCallback(object):
def on_comm_temperature_update(self, temp, bedTemp):
pass
def on_comm_position_update(self, position):
def on_comm_position_update(self, position, reason=None):
pass
def on_comm_state_change(self, state):
@@ -2515,8 +2603,16 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
Opens the file for reading and determines the file size.
"""
PrintingFileInformation.start(self)
self._read_lines = 0
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
self._pos = self._handle.tell()
if self._handle.encoding.endswith("-sig"):
# Apparently we found an utf-8 bom in the file.
# We need to add its length to our pos because it will
# be stripped transparently and we'll have no chance
# catching that.
import codecs
self._pos += len(codecs.BOM_UTF8)
self._read_lines = 0
def close(self):
"""
@@ -2548,11 +2644,17 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
self._pos = self._size
self._report_stats()
return None
line = to_unicode(self._handle.readline())
# we need to manually keep track of our pos here since
# codecs' readline will make our handle's tell not
# return the actual number of bytes read, but also the
# already buffered bytes (for detecting the newlines)
line = self._handle.readline()
self._pos += len(line.encode("utf-8"))
if not line:
self.close()
processed = self._process(line, offsets, current_tool)
self._pos = self._handle.tell()
self._read_lines += 1
return processed
except Exception as e:
@@ -2862,6 +2964,26 @@ def parse_temperature_line(line, current):
return max(maxToolNum, current), canonicalize_temperatures(result, current)
def parse_firmware_line(line):
"""
Parses the provided firmware info line.
The result will be a dictionary mapping from the contained keys to the contained
values.
Arguments:
line (str): the line to parse
Returns:
dict: a dictionary with the parsed data
"""
result = dict()
split_line = regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
for key, value in chunks(split_line, 2):
result[key] = value
return result
def gcode_command_for_cmd(cmd):
"""
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
+36 -24
View File
@@ -9,6 +9,9 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import sarge
import logging
import re
import time
from . import to_unicode
# These regexes are based on the colorama package
@@ -78,40 +81,49 @@ class CommandlineCaller(object):
kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
p = sarge.run(command, **kwargs)
p.wait_events()
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
self._logger.error(u"Error while trying to run command {}".format(joined_command))
return None, [], []
all_stdout = []
all_stderr = []
def process_lines(lines, logger):
if not lines:
return []
l = self._preprocess_lines(*map(lambda x: to_unicode(x, errors="replace"), lines))
logger(*l)
return list(l)
def process_stdout(lines):
return process_lines(lines, self._log_stdout)
def process_stderr(lines):
return process_lines(lines, self._log_stderr)
try:
while p.returncode is None:
lines = p.stderr.readlines(timeout=0.5)
if lines:
lines = self._preprocess_lines(*lines)
self._log_stderr(*lines)
all_stderr += list(lines)
lines = p.stdout.readlines(timeout=0.5)
if lines:
lines = self._preprocess_lines(*lines)
self._log_stdout(*lines)
all_stdout += list(lines)
all_stderr += process_stderr(p.stderr.readlines(timeout=0.5))
all_stdout += process_stdout(p.stdout.readlines(timeout=0.5))
p.commands[0].poll()
finally:
p.close()
lines = p.stderr.readlines()
if lines:
lines = self._preprocess_lines(*lines)
self._log_stderr(*lines)
all_stderr += lines
lines = p.stdout.readlines()
if lines:
lines = self._preprocess_lines(*lines)
self._log_stdout(*lines)
all_stdout += lines
all_stderr += process_stderr(p.stderr.readlines())
all_stdout += process_stdout(p.stdout.readlines())
return p.returncode, all_stdout, all_stderr
Binary file not shown.
File diff suppressed because it is too large. Load diff
+799 -629
View File
File diff suppressed because it is too large. Load diff