diff --git a/.versioneer-lookup b/.versioneer-lookup index 640949a91..ea536c2c1 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -24,10 +24,10 @@ maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -# staging/maintenance is currently the branch for preparation of 1.3.7rc5 +# staging/maintenance is currently the branch for preparation of 1.3.9rc2 # so is regressionfix/... -staging/maintenance 1.3.9rc2 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -regressionfix/.* 1.3.9rc2 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev +staging/maintenance 1.3.9rc3 fd94fc94a09dd91deeb2f59a6b3b00b37eb1f145 pep440-dev +regressionfix/.* 1.3.9rc3 fd94fc94a09dd91deeb2f59a6b3b00b37eb1f145 pep440-dev # every other branch is a development branch and thus gets resolved to 1.4.0-dev for now .* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev diff --git a/CHANGELOG.md b/CHANGELOG.md index c780ca0c3..12c01b817 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # OctoPrint Changelog +## 1.3.9rc2 (2018-07-06) + +### Improvements + + * Add sanity check for disabled plugin list (see also [#2687 (comment)](https://github.com/foosel/OctoPrint/issues/2687#issuecomment-399797596)). + * Improve logging of exceptions triggered inside the state update worker (see also [#2715](https://github.com/foosel/OctoPrint/issues/2715)). + +### Bug fixes + + * [#2715](https://github.com/foosel/OctoPrint/issues/2715) (regression) - Fix broken estimator initialization on SD print start and resulting crash of the state update worker. + +### More information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.9rc1...1.3.9rc2) + ## 1.3.9rc1 (2018-06-20) ### Note for upgraders running NGINX as reverse proxy: Be sure to configure HTTP protocol version 1.1 diff --git a/README.md b/README.md index b44dfe19e..fc9f7e0f1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,12 @@ # OctoPrint -[![GitHub version](https://badge.fury.io/gh/foosel%2FOctoPrint.svg)](https://badge.fury.io/gh/foosel%2FOctoPrint) + +![GitHub release](https://img.shields.io/github/release/foosel/OctoPrint.svg?colorB=brightgreen) +[![Travis build status](https://img.shields.io/travis/foosel/OctoPrint.svg)](https://travis-ci.org/foosel/OctoPrint) +[![Discourse topics](https://img.shields.io/discourse/https/discourse.octoprint.org/users.svg)](https://discourse.octoprint.org) +[![IRC](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://chat.octoprint.org) +[![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d) + OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html). @@ -9,6 +15,8 @@ Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=gi The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme). +The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint). + The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme). The documentation is located at [docs.octoprint.org](http://docs.octoprint.org). diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 3448ce8d2..320f12706 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -1,7 +1,7 @@ # Supporters Development of this version of OctoPrint wouldn't have been possible without -[financial support by the community](http://octoprint.org/support-octoprint/) - +[the financial support by the community](https://octoprint.org/support-octoprint/) - thanks to everyone who contributed! ## Patreon Patrons @@ -30,10 +30,12 @@ thanks to everyone who contributed! * Jeremiah Avery * Josh Daniels * Joshua Wills + * Justin Kaufman * Kaile Riser * Kale Stedman * Kazuhiro Ogura * Kodama Inc. + * Lewis Newby * LulzBot® * Makespace Madrid * Mark Walker @@ -51,11 +53,10 @@ thanks to everyone who contributed! * Samer Najia * Simon Hallam * Stefan Krister - * Stephane Schittly * Sven Mueller * Symbiotic Devices * Thomas Hatley * Timothy D Hoogland * Trent Shumay -and 1334 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file +and 1332 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 5fed71e5a..dc9ff6cbf 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -82,7 +82,6 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi ignore_blacklist=ignore_blacklist, after_safe_mode=log_startup, after_environment_detector=log_register_rollover) - settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components except FatalStartupError as e: diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index ad24a3e4f..65bd5f849 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -298,7 +298,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): - * **Key** * **Description** - * ``estimatedPrintTime`` - * Estimated time the file take to print, in minutes + * Estimated time the file take to print, in seconds - * ``filament`` * Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for the second and so on. For each tool extruded length and volume (based on diameter) are provided. diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index c8b9488cc..b96a9af46 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1986,7 +1986,7 @@ class SlicerPlugin(OctoPrintPlugin): For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information about the slicing job under the following keys: - _analysis + analysis Analysis result of the generated machine code as returned by the slicer itself. This should match the data structure described for the analysis queue of the matching machine code format, e.g. :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files. diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 44c684290..ff245b6c0 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -477,6 +477,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.log_all_plugins() self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) + self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key, + version=new_plugin.version, + source=source, + source_type=source_type)) + result = dict(result=True, source=source, source_type=source_type, @@ -567,6 +572,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.reload_plugins() + self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key, + version=plugin.version)) + result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, @@ -685,12 +693,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if strip: lines = map(lambda x: x.strip(), lines) - self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines])) + self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", + loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: self._console_logger.debug(u"{prefix} {line}".format(**locals())) def _mark_plugin_enabled(self, plugin, needs_restart=False): - disabled_list = list(self._settings.global_get(["plugins", "_disabled"])) + disabled_list = list(self._settings.global_get(["plugins", "_disabled"], + validator=lambda x: isinstance(x, list), + fallback=[])) if plugin.key in disabled_list: disabled_list.remove(plugin.key) self._settings.global_set(["plugins", "_disabled"], disabled_list) @@ -704,8 +715,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif not plugin.enabled and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) + self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key, + version=plugin.version)) + def _mark_plugin_disabled(self, plugin, needs_restart=False): - disabled_list = list(self._settings.global_get(["plugins", "_disabled"])) + disabled_list = list(self._settings.global_get(["plugins", "_disabled"], + validator=lambda x: isinstance(x, list), + fallback=[])) if not plugin.key in disabled_list: disabled_list.append(plugin.key) self._settings.global_set(["plugins", "_disabled"], disabled_list) @@ -719,6 +735,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) + self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key, + version=plugin.version)) + def _fetch_all_data(self, async=False): def run(): self._repository_available = self._fetch_repository_from_disk() diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py index 6372da151..08dfed097 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -80,7 +80,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc install_arg = check["pip"].format(target_version=target_version, target=target_version) logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg)) - pip_args = ["install", install_arg] + pip_args = ["install", install_arg, "--no-cache-dir"] pip_kwargs = dict() if pip_working_directory is not None: pip_kwargs.update(cwd=pip_working_directory) diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py new file mode 100644 index 000000000..08ed7855d --- /dev/null +++ b/src/octoprint/plugins/tracking/__init__.py @@ -0,0 +1,186 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from flask.ext.babel import gettext + +import requests +import hashlib +import logging + +# noinspection PyCompatibility +import concurrent.futures + +from octoprint.util import RepeatedTimer +from octoprint.util.version import get_octoprint_version_string +from octoprint.events import Events + +TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/?{args}" + +# noinspection PyMissingConstructor +class TrackingPlugin(octoprint.plugin.SettingsPlugin, + octoprint.plugin.EnvironmentDetectionPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.WizardPlugin, + octoprint.plugin.EventHandlerPlugin): + + def __init__(self): + self._environment = None + self._url = None + self._ping_worker = None + self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + + def initialize(self): + self._init_tracking() + + ##~~ SettingsPlugin + + def get_settings_defaults(self): + return dict(enabled=None, + unique_id=None, + server=TRACKING_URL, + ping=15*60) + + def on_settings_save(self, data): + enabled = self._settings.get([b"enabled"]) + + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + + if enabled is None and self._settings.get([b"enabled"]): + # tracking was just enabled, let's init it and send a startup event + self._init_tracking() + self._track_startup() + + ##~~ EnvironmentDetectionPlugin + + def on_environment_detected(self, environment, *args, **kwargs): + self._environment = environment + + ##~~ StartupPlugin + + def on_after_startup(self): + self._track_startup() + + ping = self._settings.get_int(["ping"]) + if ping: + self._ping_worker = RepeatedTimer(ping, self._track_ping) + self._ping_worker.start() + + ##~~ EventHandlerPlugin + + def on_event(self, event, payload): + if event.startswith("plugin_pluginmanager_"): + self._track_plugin_event(event, payload) + elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): + self._track_printjob_event(event, payload) + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + dict(type="settings", name=gettext("Anonymous Usage Tracking"), template="tracking_settings.jinja2", custom_bindings=False), + dict(type="wizard", name=gettext("Anonymous Usage Tracking"), template="tracking_wizard.jinja2", custom_bindings=True, mandatory=True) + ] + + ##~~ AssetPlugin + + def get_assets(self): + return dict(js=["js/tracking.js"]) + + ##~~ WizardPlugin + + def is_wizard_required(self): + return self._settings.get([b"enabled"]) is None + + ##~~ helpers + + def _init_tracking(self): + if not self._settings.get_boolean([b"enabled"]): + return + self._init_id() + self._logger.info("Initialized anonymous tracking") + + def _init_id(self): + if self._settings.get_boolean([b"enabled"]) and not self._settings.get([b"unique_id"]): + import uuid + self._settings.set([b"unique_id"], str(uuid.uuid4())) + self._settings.save() + + def _track_startup(self): + self._track("startup", + version=get_octoprint_version_string(), + os=self._environment[b"os"][b"id"]) + + def _track_ping(self): + self._track("ping") + + def _track_plugin_event(self, event, payload): + if event.endswith("_installplugin"): + self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_uninstallplugin"): + self._track("uninstall_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_enableplugin"): + self._track("enable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_disableplugin"): + self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + + def _track_printjob_event(self, event, payload): + sha = hashlib.sha1() + sha.update(payload.get("name")) + + event = None + args = dict(origin=payload.get(b"origin"), file=sha.hexdigest()) + + if event == Events.PRINT_STARTED: + event = "print_started" + elif event == Events.PRINT_DONE: + try: + elapsed = int(payload.get(b"time")) + except ValueError: + elapsed = "unknown" + args[b"elapsed"] = elapsed + event = "print_done" + elif event == Events.PRINT_FAILED: + event = "print_failed" + elif event == Events.PRINT_CANCELLED: + event = "print_cancelled" + + if event is not None: + self._track(event, **args) + + def _track(self, event, **kwargs): + if not self._settings.get_boolean([b"enabled"]): + return + + self._executor.submit(self._do_track, event, **kwargs) + + def _do_track(self, event, **kwargs): + server = self._settings.get([b"server"]) + url = server.format(id=self._settings.get([b"unique_id"]), + event=event, + args="&".join(map(lambda x: "{}={}".format(x[0], x[1]), kwargs.items()))) + + headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())} + try: + requests.get(url, + timeout=3.1, + headers=headers) + self._logger.debug("Sent tracking event to {}".format(url)) + except: + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.exception("Error while sending event to anonymous usage tracking".format(url)) + else: + pass + +__plugin_name__ = "Anonymous Usage Tracking" +__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked" +__plugin_homepage__ = "https://tracking.octoprint.org" +__plugin_author__ = "Gina Häußge" + +__plugin_implementation__ = TrackingPlugin() diff --git a/src/octoprint/plugins/tracking/static/js/tracking.js b/src/octoprint/plugins/tracking/static/js/tracking.js new file mode 100644 index 000000000..6855450b6 --- /dev/null +++ b/src/octoprint/plugins/tracking/static/js/tracking.js @@ -0,0 +1,85 @@ +$(function() { + function TrackingViewModel(parameters) { + var self = this; + + self.settingsViewModel = parameters[0]; + + self.setup = ko.observable(false); + + self.decision = ko.observable(); + self.required = false; + self.active = false; + + self.enableTracking = function() { + self.settingsViewModel.settings.plugins.tracking.enabled(true); + self.decision(true); + self._sendData(); + }; + + self.disableTracking = function() { + self.settingsViewModel.settings.plugins.tracking.enabled(false); + self.decision(false); + self._sendData(); + }; + + self.onBeforeWizardTabChange = function(next, current) { + if (!self.required) return true; + + if (!current || !_.startsWith(current, "wizard_plugin_tracking") || self.setup()) { + return true; + } + + self._showDecisionNeededDialog(); + return false; + }; + + self.onBeforeWizardFinish = function() { + if (!self.required) return true; + + if (self.setup()) { + return true; + } + + self._showDecisionNeededDialog(); + return false; + }; + + self.onWizardPreventSettingsRefreshDialog = function() { + return self.active; + }; + + self.onWizardDetails = function(response) { + self.required = response && response.tracking && response.tracking.required; + }; + + self._showDecisionNeededDialog = function() { + showMessageDialog({ + title: gettext("Please set up anonymous usage tracking"), + message: gettext("You haven't yet decided on whether to enable or disable anonymous usage tracking. You need to either enable or disable it before continuing.") + }); + }; + + self._sendData = function() { + var data = { + plugins: { + tracking: { + enabled: self.settingsViewModel.settings.plugins.tracking.enabled() + } + } + }; + + self.active = true; + self.settingsViewModel.saveData(data) + .done(function() { + self.setup(true); + self.active = false; + }); + }; + } + + OCTOPRINT_VIEWMODELS.push([ + TrackingViewModel, + ["settingsViewModel"], + "#wizard_plugin_tracking" + ]); +}); diff --git a/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 new file mode 100644 index 000000000..524a6f4f2 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 @@ -0,0 +1,10 @@ +{% trans %} +

+ Anonymous usage tracking provides valuable insights into how many instances running what versions of OctoPrint are out there, + whether they are successfully completing print jobs and various other metrics. +

+

+ By enabling it you help to identify problems with new releases and release candidates early on, and to better + tailor OctoPrint's future development to actual use. +

+{% endtrans %} diff --git a/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 new file mode 100644 index 000000000..d1fc0d990 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 @@ -0,0 +1,4 @@ +

{% trans %} + For details on what gets tracked, please refer to tracking.octoprint.org + and also the Privacy Policy at tracking.octoprint.org. +{% endtrans %}

diff --git a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 new file mode 100644 index 000000000..4c43e27cc --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 @@ -0,0 +1,21 @@ +

{{ _('Anonymous Usage Tracking') }}

+ +{% include "snippets/plugins/tracking/trackingDescription.jinja2" %} + +
+
+
+ +
+
+
+ +
+ +
+
+
+ +{% include "snippets/plugins/tracking/trackingDetails.jinja2" %} diff --git a/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 new file mode 100644 index 000000000..cbc6c12d7 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 @@ -0,0 +1,19 @@ +

{{ _('Configure Anonymous Usage Tracking') }}

+ +{% include "snippets/plugins/tracking/trackingDescription.jinja2" %} + +{% include "snippets/plugins/tracking/trackingDetails.jinja2" %} + +
+ {{ _('Disable Anonymous Usage Tracking') }} + {{ _('Enable Anonymous Usage Tracking') }} +
+ + diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index eace14bae..15f59e0bd 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -82,6 +82,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._selectedFile = None self._estimator_factory = PrintTimeEstimator + self._estimator = None analysis_queue_hooks = plugin_manager().get_hooks("octoprint.printer.estimation.factory") for name, hook in analysis_queue_hooks.items(): try: @@ -134,7 +135,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished) eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated) - def _create_estimator(self, job_type): + def _create_estimator(self, job_type=None): + if job_type is None: + with self._selectedFileMutex: + if self._selectedFile is None: + return + + if self._selectedFile["sd"]: + job_type = "sdcard" + else: + job_type = "local" + self._estimator = self._estimator_factory(job_type) #~~ handling of PrinterCallbacks @@ -499,12 +510,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if self._selectedFile is None: return - if self._selectedFile["sd"]: - job_type = "sdcard" - else: - job_type = "local" - - self._create_estimator(job_type) self._fileManager.delete_recovery_data() self._lastProgressReport = None @@ -754,6 +759,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): cleanedPrintTime = self._comm.getCleanedPrintTime() printTimeLeft = printTimeLeftOrigin = None + estimator = self._estimator if progress is not None: progress_int = int(progress * 100) if self._lastProgressReport != progress_int: @@ -766,7 +772,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): elif progress == 1.0: printTimeLeft = 0 printTimeLeftOrigin = None - else: + elif estimator is not None: statisticalTotalPrintTime = None statisticalTotalPrintTimeType = None with self._selectedFileMutex: @@ -775,11 +781,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"] statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None) - printTimeLeft, printTimeLeftOrigin = self._estimator.estimate(progress, - printTime, - cleanedPrintTime, - statisticalTotalPrintTime, - statisticalTotalPrintTimeType) + printTimeLeft, printTimeLeftOrigin = estimator.estimate(progress, + printTime, + cleanedPrintTime, + statisticalTotalPrintTime, + statisticalTotalPrintTimeType) return self._dict(completion=progress * 100 if progress is not None else None, filepos=filepos, @@ -1036,14 +1042,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): else: eventManager().fire(Events.FILE_DESELECTED) + self._create_estimator() + self._setJobData(full_path, size, sd, user=user) self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags())) + self._create_estimator() + if self._printAfterSelect: self._printAfterSelect = False self.start_print(pos=self._posAfterSelect, user=user) def on_comm_print_job_started(self, suppress_script=False): + self._stateMonitor.trigger_progress_update() payload = self._payload_for_print_job_event() if payload: eventManager().fire(Events.PRINT_STARTED, payload) @@ -1310,20 +1321,23 @@ class StateMonitor(object): self._change_event.set() def _work(self): - while True: - self._change_event.wait() + try: + while True: + self._change_event.wait() - now = time.time() - delta = now - self._last_update - additional_wait_time = self._interval - delta - if additional_wait_time > 0: - time.sleep(additional_wait_time) + now = time.time() + delta = now - self._last_update + additional_wait_time = self._interval - delta + if additional_wait_time > 0: + time.sleep(additional_wait_time) - with self._state_lock: - data = self.get_current_data() - self._update_callback(data) - self._last_update = time.time() - self._change_event.clear() + with self._state_lock: + data = self.get_current_data() + self._update_callback(data) + self._last_update = time.time() + self._change_event.clear() + except: + logging.getLogger(__name__).exception("Looks like something crashed inside the state update worker. Please report this on the OctoPrint issue tracker (make sure to include logs!)") def get_current_data(self): with self._progress_lock: diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 253fafb42..4cb401603 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -92,6 +92,7 @@ def getSettings(): "name": s.get(["appearance", "name"]), "color": s.get(["appearance", "color"]), "colorTransparent": s.getBoolean(["appearance", "colorTransparent"]), + "colorIcon": s.getBoolean(["appearance", "colorIcon"]), "defaultLanguage": s.get(["appearance", "defaultLanguage"]), "showFahrenheitAlso": s.getBoolean(["appearance", "showFahrenheitAlso"]) }, @@ -378,6 +379,7 @@ def _saveSettings(data): if "name" in data["appearance"]: s.set(["appearance", "name"], data["appearance"]["name"]) if "color" in data["appearance"]: s.set(["appearance", "color"], data["appearance"]["color"]) if "colorTransparent" in data["appearance"]: s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"]) + if "colorIcon" in data["appearance"]: s.setBoolean(["appearance", "colorIcon"], data["appearance"]["colorIcon"]) if "defaultLanguage" in data["appearance"]: s.set(["appearance", "defaultLanguage"], data["appearance"]["defaultLanguage"]) if "showFahrenheitAlso" in data["appearance"]: s.setBoolean(["appearance", "showFahrenheitAlso"], data["appearance"]["showFahrenheitAlso"]) diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 118f54006..2fe2a1707 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -43,7 +43,7 @@ def enforceApiKeyRequestHandler(): apikey = get_api_key(_flask.request) - if apikey is None and settings().getBoolean(["api", "keyEnforced"]): + if not apikey and settings().getBoolean(["api", "keyEnforced"]): return _flask.make_response("No API key provided", 403) if apikey != octoprint.server.UI_API_KEY and not settings().getBoolean(["api", "enabled"]): diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 00c88b0e9..e8dd65f86 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -279,6 +279,7 @@ default_settings = { "name": "", "color": "default", "colorTransparent": False, + "colorIcon": True, "defaultLanguage": "_default", "showFahrenheitAlso": False, "components": { @@ -1429,17 +1430,22 @@ class Settings(object): #~~ getter def get(self, path, **kwargs): - error_on_path = kwargs.get("error_on_path", False) - new_kwargs = dict(kwargs) - if "error_on_path" in new_kwargs: - del new_kwargs["error_on_path"] + error_on_path = kwargs.pop("error_on_path", False) + validator = kwargs.pop("validator", None) + fallback = kwargs.pop("fallback", None) - try: - return self._get_value(path, **new_kwargs) - except NoSuchSettingsPath: - if error_on_path: - raise - return None + def process(): + try: + return self._get_value(path, **kwargs) + except NoSuchSettingsPath: + if error_on_path: + raise + return None + + result = process() + if callable(validator) and not validator(result): + result = fallback + return result def getInt(self, path, **kwargs): minimum = kwargs.pop("min", None) diff --git a/src/octoprint/static/img/mask-theme.svg b/src/octoprint/static/img/mask-theme.svg new file mode 100644 index 000000000..1d09f4d45 --- /dev/null +++ b/src/octoprint/static/img/mask-theme.svg @@ -0,0 +1,30 @@ + + + + +mask-theme + + + + + + + + + diff --git a/src/octoprint/static/img/favicon.svg b/src/octoprint/static/img/mask.svg similarity index 100% rename from src/octoprint/static/img/favicon.svg rename to src/octoprint/static/img/mask.svg diff --git a/src/octoprint/static/js/app/viewmodels/appearance.js b/src/octoprint/static/js/app/viewmodels/appearance.js index 75c1c527a..81282ba78 100644 --- a/src/octoprint/static/js/app/viewmodels/appearance.js +++ b/src/octoprint/static/js/app/viewmodels/appearance.js @@ -1,10 +1,96 @@ $(function() { + var save = {}; + + // Using the theme color (for the top bar), also recolor the favicon tentacle. + function themeFavicon(colorname) { + save.colorName = colorname; + + // the following is from an Apache licensed snippet: + // http://blog.roomanna.com/09-24-2011/dynamically-coloring-a-favicon + var link = document.querySelector("link[rel='shortcut icon']"); + if (!link) { + link = document.createElement("link"); + link.setAttribute("rel", "shortcut icon"); + document.head.appendChild(link); + } + + // try to get the best quality ico possible; prefer svg, the apple-touch pngs are more difficult, + // but all three of the others give a high-quality ico. + var faviconUrl = document.querySelector("link[rel~='mask-icon-theme']").href + || link.href + || window.location.origin + "/favicon.ico"; + + function onImageLoaded() { + var icosize = 256; + + var canvas = document.createElement("canvas"); + canvas.width = icosize; + canvas.height = icosize; + + var context = canvas.getContext("2d"); + + function grayscale() { + var imageData = context.getImageData(0, 0, canvas.width, canvas.height), + pixels = imageData.data, + i, l, r, g, b, a, luma; + + for (i = 0, l = pixels.length; i < l; i += 4) { + a = pixels[i + 3]; + if (a === 0) { continue; } + + r = pixels[i]; + g = pixels[i + 1]; + b = pixels[i + 2]; + + luma = r * 0.2126 + g * 0.7152 + b * 0.0722; + + pixels[i] = pixels[i + 1] = pixels[i + 2] = luma; + } + + context.putImageData(imageData, 0, 0); + } + + function colorize(color, alpha) { + context.globalCompositeOperation = "source-atop"; + context.globalAlpha = alpha; + context.fillStyle = color; + context.fillRect(0, 0, canvas.width, canvas.height); + context.globalCompositeOperation = "source-over"; + context.globalAlpha = 1.0; + } + + context.drawImage(img, 0, 0, canvas.width, canvas.height); + if (save.colorName !== "default") { + grayscale(); + colorize(save.colorName, .3); + } + link.type = "image/x-icon"; + link.href = canvas.toDataURL(); + } + + var img = document.createElement("img"); + img.addEventListener("load", onImageLoaded); + img.src = faviconUrl; + } + function AppearanceViewModel(parameters) { var self = this; self.name = parameters[0].appearance_name; self.color = parameters[0].appearance_color; self.colorTransparent = parameters[0].appearance_colorTransparent; + self.colorIcon = parameters[0].appearance_colorIcon; + + function updateIcon() { + if (self.colorIcon()) { + themeFavicon(self.color()); + } else { + themeFavicon("default"); + } + } + self.color.subscribe(updateIcon); + self.colorIcon.subscribe(updateIcon); + updateIcon(); self.brand = ko.pureComputed(function() { if (self.name()) diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 7bd3bd19b..d31ed6af8 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -116,6 +116,7 @@ $(function() { self.appearance_name = ko.observable(undefined); self.appearance_color = ko.observable(undefined); self.appearance_colorTransparent = ko.observable(); + self.appearance_colorIcon = ko.observable(); self.appearance_defaultLanguage = ko.observable(); self.appearance_showFahrenheitAlso = ko.observable(undefined); diff --git a/src/octoprint/templates/dialogs/settings/appearance.jinja2 b/src/octoprint/templates/dialogs/settings/appearance.jinja2 index b50a93735..b20a91573 100644 --- a/src/octoprint/templates/dialogs/settings/appearance.jinja2 +++ b/src/octoprint/templates/dialogs/settings/appearance.jinja2 @@ -15,7 +15,14 @@
+
+
+
+
+
diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index 8482cad05..13cb76e82 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -4,7 +4,8 @@ OctoPrint - + + diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 5d59ca8c4..918ac1a4b 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -405,15 +405,15 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= u'test_123.gco' >>> find_collision_free_name("test1234", "g o", []) u'test1234.g_o' - >>> find_collision_free_name("test12345", "gco", ["test12~1.gco"]) + >>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) u'test12~2.gco' - >>> many_files = ["test12~{}.gco".format(x) for x in range(10)[1:]] + >>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]] >>> find_collision_free_name("test12345", "gco", many_files) u'test1~10.gco' - >>> many_more_files = many_files + ["test1~{}.gco".format(x) for x in range(10, 99)] + >>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)] >>> find_collision_free_name("test12345", "gco", many_more_files) u'test1~99.gco' - >>> many_more_files_plus_one = many_more_files + ["test1~99.gco"] + >>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"] >>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) Traceback (most recent call last): ... @@ -423,13 +423,15 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= """ - if not isinstance(filename, unicode): - filename = unicode(filename) - if not isinstance(extension, unicode): - extension = unicode(extension) + filename = to_unicode(filename) + extension = to_unicode(extension) + + if filename.startswith(u"/"): + filename = filename[1:] + existing_filenames = [to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames] def make_valid(text): - return re.sub(r"\s+", "_", text.translate({ord(i):None for i in ".\"/\\[]:;=,"})).lower() + return re.sub(u"\s+", u"_", text.translate({ord(i):None for i in ".\"/\\[]:;=,"})).lower() filename = make_valid(filename) extension = make_valid(extension) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 985f0c918..967bda48f 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -1012,11 +1012,6 @@ class MachineCom(object): self._callback.on_comm_print_job_started() if self.isSdFileSelected(): - interval = self._timeout_intervals.get("sdStatus", 1.0) - if interval <= 0: - interval = 1.0 - self._sd_status_timer = RepeatedTimer(interval, self._poll_sd_status, run_first=True) - if not external_sd: # make sure to ignore the "file selected" later on, otherwise we'll reset our progress data self._ignore_select = True @@ -1032,15 +1027,9 @@ class MachineCom(object): else: self._currentFile.pos = 0 - def start_polling(): - self._sd_status_timer.start() - self.sendCommand("M24", - on_sent=start_polling, part_of_job=True, tags=tags | {"trigger:comm.start_print",}) - else: - self._sd_status_timer.start() else: if pos is not None and isinstance(pos, int) and pos > 0: self._currentFile.seek(pos) @@ -1155,6 +1144,7 @@ class MachineCom(object): elif check_timer: return + self._currentFile.done = True self._recordFilePosition() self._callback.on_comm_print_job_cancelled() @@ -1205,11 +1195,6 @@ class MachineCom(object): self.sendCommand("M25", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # pause print self.sendCommand("M27", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # get current byte position in file self.sendCommand("M26 S0", part_of_job=True, tags=tags | {"trigger:comm.cancel",}) # reset position in file to byte 0 - if self._sd_status_timer is not None: - try: - self._sd_status_timer.cancel() - except: - pass if self._log_position_on_cancel and not disable_log_position: self.sendCommand("M400", @@ -1885,17 +1870,19 @@ class MachineCom(object): total = int(match.group("total")) if self.isSdPrinting() and current == total == 0: - # apparently not SD printing - newer Marlin reports it like that for some reason + # apparently not SD printing - some Marlin versions report it like that for some reason self.cancelPrint(external_sd=True) elif self.isSdFileSelected(): - if not self.isSdPrinting() and current != total: + if not self.isSdPrinting() and current != total and current > 0: self.startPrint(external_sd=True) self._currentFile.pos = current if self._currentFile.size == 0: self._currentFile.size = total - self._callback.on_comm_progress() + + if not self._currentFile.done: + self._callback.on_comm_progress() elif 'Not SD printing' in line and self.isSdFileSelected() and self.isPrinting() and not self.isFinishing(): # something went wrong, printer is reporting that we actually are not printing right now... @@ -1911,9 +1898,7 @@ class MachineCom(object): size = 0 user = None - expected = False if self._sdFileToSelect: - expected = True name = self._sdFileToSelect user = self._sdFileToSelectUser @@ -1921,12 +1906,6 @@ class MachineCom(object): self._sdFileToSelectUser = None self._currentFile = PrintingSdFileInformation(name, size, user=user) - - if not expected: - # It doesn't look like we expected this, so it might be that someone just started a print - # job from SD via the printer's controller. Let's query the printing status and see if that's - # indeed the case and if so switch states accordingly - self.sendCommand("M27", tags={"trigger:unexpected_file_open"}) elif 'File selected' in line: if self._ignore_select: self._ignore_select = False @@ -1945,12 +1924,6 @@ class MachineCom(object): self._currentFile.done = True self._currentFile.pos = 0 - if self._sd_status_timer is not None: - try: - self._sd_status_timer.cancel() - except: - pass - self.sendCommand("M400", part_of_job=True) self._callback.on_comm_print_job_done() def finalize(): @@ -2267,7 +2240,7 @@ class MachineCom(object): command or heating, no poll will be done. """ - if self.isOperational() and not self._sdstatus_autoreporting and not self._connection_closing and self.isSdPrinting() and not self._long_running_command and not self._dwelling_until and not self._heating: + if self.isOperational() and not self._sdstatus_autoreporting and not self._connection_closing and self.isSdFileSelected() and not self._long_running_command and not self._dwelling_until and not self._heating: self.sendCommand("M27", cmd_type="sd_status_poll", tags={"trigger:comm.poll_sd_status"}) def _set_autoreport_temperature_interval(self, interval=None): @@ -2296,9 +2269,12 @@ class MachineCom(object): def _onConnected(self): self._serial.timeout = settings().getFloat(["serial", "timeout", "communication"]) - self._temperature_timer = RepeatedTimer(self._getTemperatureTimerInterval, self._poll_temperature, run_first=True) + self._temperature_timer = RepeatedTimer(self._get_temperature_timer_interval, self._poll_temperature, run_first=True) self._temperature_timer.start() + self._sd_status_timer = RepeatedTimer(self._get_sd_status_timer_interval, self._poll_sd_status, run_first=True) + self._sd_status_timer.start() + self._changeState(self.STATE_OPERATIONAL) self.resetLineNumbers(tags={"trigger:comm.on_connected",}) @@ -2335,7 +2311,7 @@ class MachineCom(object): if self._busy_protocol_detected: self._set_busy_protocol_interval() - def _getTemperatureTimerInterval(self): + def _get_temperature_timer_interval(self): busy_default = 4.0 target_default = 2.0 @@ -2359,6 +2335,12 @@ class MachineCom(object): return get("temperature", busy_default) + def _get_sd_status_timer_interval(self): + interval = self._timeout_intervals.get("sdStatus", 1.0) + if interval <= 0: + interval = 1.0 + return interval + def _send_from_command_queue(self): # We loop here to make sure that if we do NOT send the first command # from the queue, we'll send the second (if there is one). We do not @@ -3636,6 +3618,10 @@ class PrintingFileInformation(object): def done(self): return self._done + @done.setter + def done(self, value): + self._done = value + class PrintingSdFileInformation(PrintingFileInformation): """ Encapsulates information regarding an ongoing print from SD. @@ -3650,14 +3636,6 @@ class PrintingSdFileInformation(PrintingFileInformation): def getFileLocation(self): return FileDestinations.SDCARD - @property - def done(self): - return self._done - - @done.setter - def done(self, value): - self._done = value - @property def size(self): return self._size