From fbbb5b4d7e97b1e7b826e9fb92fea55250838c50 Mon Sep 17 00:00:00 2001 From: Paul de Vries Date: Tue, 16 Feb 2016 20:46:02 +0000 Subject: [PATCH 01/44] Simplefy debug message with lodash/underscore --- src/octoprint/static/js/app/main.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 402933a6e..bfb5f0305 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -199,11 +199,8 @@ $(function() { constructorParameters = []; } - if (_.some(constructorParameters, function(parameter) { return parameter === undefined; })) { - var _extractName = function(entry) { return entry[0]; }; - var _onlyUnresolved = function(entry) { return entry[1] === undefined; }; - var missingParameters = _.map(_.filter(_.zip(viewModelParameters, constructorParameters), _onlyUnresolved), _extractName); - log.debug("Postponing", viewModel[0].name, "due to missing parameters:", missingParameters); + if (constructorParameters.indexOf(undefined) !== -1) { + log.debug("Postponing", viewModel[0].name, "due to missing parameters:", _.keys(_.pick(_.object(viewModelParameters, constructorParameters), _.isUndefined))); return; } From f5fbd773dcbb53bb11b745abc9e247583e2ea779 Mon Sep 17 00:00:00 2001 From: Paul de Vries Date: Wed, 17 Feb 2016 00:19:14 +0000 Subject: [PATCH 02/44] 1. Objectify the OCTOPRINT_VIEWMODEL pool 2. Add optional viewmodel(s) by pushing an extra array or by using object.optional 3. Add format option and return dependencies as object, by default it will return an array --- src/octoprint/static/js/app/main.js | 87 ++++++++++++++++++----------- 1 file changed, 54 insertions(+), 33 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index bfb5f0305..de085f2db 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -182,31 +182,33 @@ $(function() { } // helper to create a view model instance with injected constructor parameters from the view model map - var _createViewModelInstance = function(viewModel, viewModelMap){ - var viewModelClass = viewModel[0]; - var viewModelParameters = viewModel[1]; + var _createViewModelInstance = function(viewModel, viewModelMap) { - if (viewModelParameters != undefined) { - if (!_.isArray(viewModelParameters)) { - viewModelParameters = [viewModelParameters]; + var viewModelParametersMap = function(parameter) { + + // Check if parameter is found within optional array and if all conditions are met return null + if (optionalDependencyPass && viewModel.optional.indexOf(parameter) !== -1 && !viewModelMap[parameter]) { + log.debug("Resolving optional parameter", [parameter], "without viewmodel"); + return null } - // now we'll try to resolve all of the view model's constructor parameters via our view model map - var constructorParameters = _.map(viewModelParameters, function(parameter){ - return viewModelMap[parameter] - }); - } else { - constructorParameters = []; - } + return viewModelMap[parameter] + }; + + // try to resolve all of the view model's constructor parameters via our view model map + var constructorParameters = _.map(viewModel.dependencies, viewModelParametersMap) || []; if (constructorParameters.indexOf(undefined) !== -1) { - log.debug("Postponing", viewModel[0].name, "due to missing parameters:", _.keys(_.pick(_.object(viewModelParameters, constructorParameters), _.isUndefined))); + log.debug("Postponing", viewModel.name, "due to missing parameters:", _.keys(_.pick(_.object(viewModel.dependencies, constructorParameters), _.isUndefined))); return; } + // transform array into object if a plugin wants it as an object + constructorParameters = (viewModel.format === "object") ? _.object(viewModel.dependencies, constructorParameters) : constructorParameters; + // if we came this far then we could resolve all constructor parameters, so let's construct that view model - log.debug("Constructing", viewModel[0].name, "with parameters:", viewModelParameters); - return new viewModelClass(constructorParameters); + log.debug("Constructing", viewModel.name, "with parameters:", viewModel.dependencies); + return new viewModel.construct(constructorParameters); }; // map any additional view model bindings we might need to make @@ -226,8 +228,7 @@ $(function() { }); // helper for translating the name of a view model class into an identifier for the view model map - var _getViewModelId = function(viewModel){ - var name = viewModel[0].name; + var _getViewModelId = function(name){ return name.substr(0, 1).toLowerCase() + name.substr(1); // FooBarViewModel => fooBarViewModel }; @@ -240,20 +241,39 @@ $(function() { var allViewModels = []; var allViewModelData = []; var pass = 1; + var optionalDependencyPass = false; log.info("Starting dependency resolution..."); while (unprocessedViewModels.length > 0) { log.debug("Dependency resolution, pass #" + pass); var startLength = unprocessedViewModels.length; var postponed = []; + if(optionalDependencyPass) { + log.debug("Resolving dependencies with optional flag"); + } + // now try to instantiate every one of our as of yet unprocessed view model descriptors while (unprocessedViewModels.length > 0){ var viewModel = unprocessedViewModels.shift(); - var viewModelId = _getViewModelId(viewModel); + + // Wrap anything not object related into a object + if(!(viewModel.constructor === Object)) { + viewModel = { + construct: viewModel[0], + dependencies: viewModel[1] || [], + elements: viewModel[2] || [], + optional: viewModel[3] || [] + }; + } + + viewModel.name = viewModel.name || _getViewModelId(viewModel.construct.name); + viewModel.dependencies = (_.isArray(viewModel.dependencies)) ? viewModel.dependencies : [viewModel.dependencies]; + viewModel.elements = (_.isArray(viewModel.elements)) ? viewModel.elements : [viewModel.elements]; + viewModel.optional = (_.isArray(viewModel.optional)) ? viewModel.optional : [viewModel.optional]; // make sure that we don't have two view models going by the same name - if (_.has(viewModelMap, viewModelId)) { - log.error("Duplicate name while instantiating " + viewModelId); + if (_.has(viewModelMap, viewModel.name)) { + log.error("Duplicate name while instantiating " + viewModel.name); continue; } @@ -266,18 +286,15 @@ $(function() { } // we could resolve the depdendencies and the view model is not defined yet => add it, it's now fully processed - var viewModelBindTargets = viewModel[2]; - if (!_.isArray(viewModelBindTargets)) { - viewModelBindTargets = [viewModelBindTargets]; - } + var viewModelBindTargets = viewModel.elements; - if (additionalBindings.hasOwnProperty(viewModelId)) { - viewModelBindTargets = viewModelBindTargets.concat(additionalBindings[viewModelId]); + if (additionalBindings.hasOwnProperty(viewModel.name)) { + viewModelBindTargets = viewModelBindTargets.concat(additionalBindings[viewModel.name]); } allViewModelData.push([viewModelInstance, viewModelBindTargets]); allViewModels.push(viewModelInstance); - viewModelMap[viewModelId] = viewModelInstance; + viewModelMap[viewModel.name] = viewModelInstance; } // anything that's now in the postponed list has to be readded to the unprocessedViewModels @@ -287,11 +304,15 @@ $(function() { // couldn't instantiate any more view models over a whole iteration, which in turn mean we can't resolve the // dependencies of remaining ones, so log that as an error and then quit the loop if (unprocessedViewModels.length == startLength) { - log.error("Could not instantiate the following view models due to unresolvable dependencies:"); - _.each(unprocessedViewModels, function(entry) { - log.error(entry[0].name + " (missing: " + _.filter(entry[1], function(id) { return !_.has(viewModelMap, id); }).join(", ") + " )"); - }); - break; + if(!optionalDependencyPass) { + optionalDependencyPass = true; + } else { + log.error("Could not instantiate the following view models due to unresolvable dependencies:"); + _.each(unprocessedViewModels, function(entry) { + log.error(entry.name + " (missing: " + _.filter(entry.dependencies, function(id) { return !_.has(viewModelMap, id); }).join(", ") + " )"); + }); + break; + } } log.debug("Dependency resolution pass #" + pass + " finished, " + unprocessedViewModels.length + " view models left to process"); From ef411298e28b44eebdd59c762bbff0ada6007394 Mon Sep 17 00:00:00 2001 From: Paul de Vries Date: Thu, 18 Feb 2016 21:27:36 +0000 Subject: [PATCH 03/44] Add ability to push only a function in the OCTOPRINT_VIEWMODELS array Add more comments Fine tweak code: - Remove vanilla Object check with jQuery (lodash gives invalid result on arrays with isObject) - Add function check on constructor - Generate function name on anonymous functions --- src/octoprint/static/js/app/main.js | 37 +++++++++++++++++------------ 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index de085f2db..341af3bbf 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -184,15 +184,15 @@ $(function() { // helper to create a view model instance with injected constructor parameters from the view model map var _createViewModelInstance = function(viewModel, viewModelMap) { + // mirror the requested dependencies with an array of the viewModels var viewModelParametersMap = function(parameter) { - - // Check if parameter is found within optional array and if all conditions are met return null + // check if parameter is found within optional array and if all conditions are met return null instead of undefined if (optionalDependencyPass && viewModel.optional.indexOf(parameter) !== -1 && !viewModelMap[parameter]) { log.debug("Resolving optional parameter", [parameter], "without viewmodel"); return null } - return viewModelMap[parameter] + return viewModelMap[parameter] || undefined }; // try to resolve all of the view model's constructor parameters via our view model map @@ -248,25 +248,30 @@ $(function() { var startLength = unprocessedViewModels.length; var postponed = []; - if(optionalDependencyPass) { - log.debug("Resolving dependencies with optional flag"); - } - // now try to instantiate every one of our as of yet unprocessed view model descriptors while (unprocessedViewModels.length > 0){ var viewModel = unprocessedViewModels.shift(); - // Wrap anything not object related into a object - if(!(viewModel.constructor === Object)) { + // wrap anything not object related into a object (use jQuery since lodash returns invalid results) + if(!$.isPlainObject(viewModel)) { viewModel = { - construct: viewModel[0], - dependencies: viewModel[1] || [], - elements: viewModel[2] || [], - optional: viewModel[3] || [] + construct: (_.isArray(viewModel)) ? viewModel[0] : viewModel, + dependencies: viewModel[1] || [], + elements: viewModel[2] || [], + optional: viewModel[3] || [] }; } - viewModel.name = viewModel.name || _getViewModelId(viewModel.construct.name); + // make sure we have atleast a function + if (!_.isFunction(viewModel.construct)) { + log.error("No function to instantiate with", viewModel); + continue; + } + + // if name is not set, get name from construct, if it's an anonymous function; generate one + viewModel.name = viewModel.name || _getViewModelId(viewModel.construct.name) || "unnamedViewModel" + _.uniqueId(); + + // make sure all value's are in an array viewModel.dependencies = (_.isArray(viewModel.dependencies)) ? viewModel.dependencies : [viewModel.dependencies]; viewModel.elements = (_.isArray(viewModel.elements)) ? viewModel.elements : [viewModel.elements]; viewModel.optional = (_.isArray(viewModel.optional)) ? viewModel.optional : [viewModel.optional]; @@ -303,8 +308,10 @@ $(function() { // if we still have the same amount of items in our list of unprocessed view models it means that we // couldn't instantiate any more view models over a whole iteration, which in turn mean we can't resolve the // dependencies of remaining ones, so log that as an error and then quit the loop - if (unprocessedViewModels.length == startLength) { + if (unprocessedViewModels.length === startLength) { + // I'm gonna let you finish but we will do another pass with the optional dependencies flag enabled if(!optionalDependencyPass) { + log.debug("Resolving next pass with optional dependencies flag enabled"); optionalDependencyPass = true; } else { log.error("Could not instantiate the following view models due to unresolvable dependencies:"); From f67da6507f5e83723b1393ad492d11191e136aa7 Mon Sep 17 00:00:00 2001 From: Paul de Vries Date: Thu, 18 Feb 2016 21:55:22 +0000 Subject: [PATCH 04/44] Fix typo and move prefix into function call --- src/octoprint/static/js/app/main.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 341af3bbf..aac260339 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -252,7 +252,7 @@ $(function() { while (unprocessedViewModels.length > 0){ var viewModel = unprocessedViewModels.shift(); - // wrap anything not object related into a object (use jQuery since lodash returns invalid results) + // wrap anything not object related into an object (use jQuery since lodash returns invalid results) if(!$.isPlainObject(viewModel)) { viewModel = { construct: (_.isArray(viewModel)) ? viewModel[0] : viewModel, @@ -268,8 +268,8 @@ $(function() { continue; } - // if name is not set, get name from construct, if it's an anonymous function; generate one - viewModel.name = viewModel.name || _getViewModelId(viewModel.construct.name) || "unnamedViewModel" + _.uniqueId(); + // if name is not set, get name from constructor, if it's an anonymous function generate one + viewModel.name = viewModel.name || _getViewModelId(viewModel.construct.name) || _.uniqueId("unnamedViewModel"); // make sure all value's are in an array viewModel.dependencies = (_.isArray(viewModel.dependencies)) ? viewModel.dependencies : [viewModel.dependencies]; From 0827ae10f206910b4fd82a5d987790f2fe784ae5 Mon Sep 17 00:00:00 2001 From: Paul de Vries Date: Thu, 18 Feb 2016 22:41:53 +0000 Subject: [PATCH 05/44] Rename format into returnObject w/ (true/false/undefined) --- src/octoprint/static/js/app/main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index aac260339..3608188e3 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -204,7 +204,7 @@ $(function() { } // transform array into object if a plugin wants it as an object - constructorParameters = (viewModel.format === "object") ? _.object(viewModel.dependencies, constructorParameters) : constructorParameters; + constructorParameters = (viewModel.returnObject) ? _.object(viewModel.dependencies, constructorParameters) : constructorParameters; // if we came this far then we could resolve all constructor parameters, so let's construct that view model log.debug("Constructing", viewModel.name, "with parameters:", viewModel.dependencies); From 5c83aef52d9a3164f7aa7612b691238db1e691b1 Mon Sep 17 00:00:00 2001 From: Paul de Vries Date: Fri, 4 Mar 2016 18:29:05 +0000 Subject: [PATCH 06/44] Use _.isPlainObject over $.isPlainObject --- src/octoprint/static/js/app/main.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 3608188e3..d0d5fef2a 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -252,8 +252,8 @@ $(function() { while (unprocessedViewModels.length > 0){ var viewModel = unprocessedViewModels.shift(); - // wrap anything not object related into an object (use jQuery since lodash returns invalid results) - if(!$.isPlainObject(viewModel)) { + // wrap anything not object related into an object + if(!_.isPlainObject(viewModel)) { viewModel = { construct: (_.isArray(viewModel)) ? viewModel[0] : viewModel, dependencies: viewModel[1] || [], From 0bb467e884db60ae7baa5df3666c27ec65267932 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 9 Jun 2016 13:41:14 +0200 Subject: [PATCH 07/44] Ensure temperature graph to be properly initialized --- .../static/js/app/viewmodels/temperature.js | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/temperature.js b/src/octoprint/static/js/app/viewmodels/temperature.js index e05cfd6a9..b4b6edebc 100644 --- a/src/octoprint/static/js/app/viewmodels/temperature.js +++ b/src/octoprint/static/js/app/viewmodels/temperature.js @@ -40,13 +40,15 @@ $(function() { var graphColors = ["red", "orange", "green", "brown", "purple"]; var heaterOptions = {}; var tools = self.tools(); + var color; // tools - var numExtruders = self.settingsViewModel.printerProfiles.currentProfileData().extruder.count(); + var currentProfileData = self.settingsViewModel.printerProfiles.currentProfileData(); + var numExtruders = (currentProfileData ? currentProfileData.extruder.count() : 0); if (numExtruders && numExtruders > 1) { // multiple extruders for (var extruder = 0; extruder < numExtruders; extruder++) { - var color = graphColors.shift(); + color = graphColors.shift(); if (!color) color = "black"; heaterOptions["tool" + extruder] = {name: "T" + extruder, color: color}; @@ -56,9 +58,9 @@ $(function() { tools[extruder]["name"](gettext("Tool") + " " + extruder); tools[extruder]["key"]("tool" + extruder); } - } else { + } else if (numExtruders == 1) { // only one extruder, no need to add numbers - var color = graphColors[0]; + color = graphColors[0]; heaterOptions["tool0"] = {name: "T", color: color}; if (tools.length < 1 || !tools[0]) { @@ -69,7 +71,7 @@ $(function() { } // print bed - if (self.settingsViewModel.printerProfiles.currentProfileData().heatedBed()) { + if (currentProfileData && currentProfileData.heatedBed()) { self.hasBed(true); heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"}; } else { @@ -79,11 +81,12 @@ $(function() { // write back self.heaterOptions(heaterOptions); self.tools(tools); + self.updatePlot(); }; self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() { self._printerProfileUpdated(); self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated); - self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated()); + self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated); }); self.temperatures = []; @@ -367,7 +370,11 @@ $(function() { return; } self.updatePlot(); - } + }; + + self.onStartupComplete = function() { + self._printerProfileUpdated(); + }; } From 8616bc13cb7325ab581988ccb5d147dbf42722dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Jun 2016 10:41:59 +0200 Subject: [PATCH 08/44] Made optional pass flag a parameter to viewmodel factory Also some minor whitespace related stuff and some comments --- src/octoprint/static/js/app/main.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 49e718add..8f55cdd29 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -182,17 +182,17 @@ $(function() { } // helper to create a view model instance with injected constructor parameters from the view model map - var _createViewModelInstance = function(viewModel, viewModelMap) { + var _createViewModelInstance = function(viewModel, viewModelMap, optionalDependencyPass) { // mirror the requested dependencies with an array of the viewModels var viewModelParametersMap = function(parameter) { // check if parameter is found within optional array and if all conditions are met return null instead of undefined if (optionalDependencyPass && viewModel.optional.indexOf(parameter) !== -1 && !viewModelMap[parameter]) { log.debug("Resolving optional parameter", [parameter], "without viewmodel"); - return null + return null; // null == "optional but not available" } - return viewModelMap[parameter] || undefined + return viewModelMap[parameter] || undefined; // undefined == "not available" }; // try to resolve all of the view model's constructor parameters via our view model map @@ -282,7 +282,7 @@ $(function() { continue; } - var viewModelInstance = _createViewModelInstance(viewModel, viewModelMap); + var viewModelInstance = _createViewModelInstance(viewModel, viewModelMap, optionalDependencyPass); // our view model couldn't yet be instantiated, so postpone it for a bit if (viewModelInstance === undefined) { @@ -310,7 +310,7 @@ $(function() { // dependencies of remaining ones, so log that as an error and then quit the loop if (unprocessedViewModels.length === startLength) { // I'm gonna let you finish but we will do another pass with the optional dependencies flag enabled - if(!optionalDependencyPass) { + if (!optionalDependencyPass) { log.debug("Resolving next pass with optional dependencies flag enabled"); optionalDependencyPass = true; } else { From 65c1415d4b880919a9b399a36b686ae98642fcb4 Mon Sep 17 00:00:00 2001 From: MirceaDan Date: Thu, 9 Jun 2016 09:55:50 +0200 Subject: [PATCH 09/44] added () to print statements for python 3.x compatibility some print already have () some did not , for consistency and compatibility i added () to all prints. (cherry picked from commit b601239) --- src/octoprint_setuptools/__init__.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py index f683e2e36..6e840adde 100644 --- a/src/octoprint_setuptools/__init__.py +++ b/src/octoprint_setuptools/__init__.py @@ -78,14 +78,14 @@ class CleanCommand(Command): def run(self): # build folder if os.path.exists(self.__class__.build_folder): - print "Deleting build directory" + print("Deleting build directory") shutil.rmtree(self.__class__.build_folder) # eggs for egg in self.__class__.eggs: globbed_eggs = glob.glob(egg) for globbed_egg in globbed_eggs: - print "Deleting %s directory" % globbed_egg + print("Deleting %s directory" % globbed_egg) shutil.rmtree(globbed_egg) # pyc files @@ -94,11 +94,11 @@ class CleanCommand(Command): return if len(os.listdir(path)) == 0: shutil.rmtree(path) - print "Deleted %s since it was empty" % path + print("Deleted %s since it was empty" % path) def delete_file(path): os.remove(path) - print "Deleted %s" % path + print("Deleted %s" % path) import fnmatch recursively_handle_files( From 9c89d45c10027416e2c016dc8f3c7706b87f2d50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Jun 2016 10:49:30 +0200 Subject: [PATCH 10/44] Use print_function import + added @MirceDan to AUTHORS.md --- AUTHORS.md | 1 + src/octoprint_setuptools/__init__.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/AUTHORS.md b/AUTHORS.md index 9f51ea1a3..51edad30a 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -68,6 +68,7 @@ date of first contribution): * [Philipp Baum](https://github.com/philphilphil) * [Kyle Evans](https://github.com/kevans91) * [Javier Martínez Arrieta](https://github.com/Javierma) + * ["MirceaDan"](https://github.com/ByReaL) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py index 6e840adde..1f160c72d 100644 --- a/src/octoprint_setuptools/__init__.py +++ b/src/octoprint_setuptools/__init__.py @@ -1,5 +1,5 @@ # coding=utf-8 -from __future__ import absolute_import +from __future__ import absolute_import, print_function __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' From 0274b0f25b34afa13b797fadb48f7180d3077ed8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Jun 2016 16:22:37 +0200 Subject: [PATCH 11/44] Have virtual printer report back with "B:" in line Similar to Marlin with enabled COREXY. Useful for testing parser behaviour. --- src/octoprint/plugins/virtual_printer/virtual.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 0f80967ee..0ad7adec5 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -254,7 +254,7 @@ class VirtualPrinter(): self._deleteSdFile(filename) elif "M114" in data: # send dummy position report - output = "C: X:10.00 Y:3.20 Z:5.20 E:1.24" + output = "X:10.00 Y:3.20 Z:5.20 E:1.24 Count: A:1000 B:320 C:1040" if not self._okBeforeCommandOutput: output = "ok " + output self.outgoing.put(output) From ad201b040d3d76a8de8177de563deaff20894476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Jun 2016 16:27:51 +0200 Subject: [PATCH 12/44] Don't parse B: in position as bed temperature Closes #1373 --- src/octoprint/util/comm.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 5d8d1c4af..dc88d71f9 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -1046,8 +1046,17 @@ class MachineCom(object): if handled and self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE): continue - ##~~ Temperature processing - if ' T:' in line or line.startswith('T:') or ' T0:' in line or line.startswith('T0:') or ' B:' in line or line.startswith('B:'): + # position report processing + if 'X:' in line and 'Y:' in line and 'Z:' in line: + # currently only here to prevent any "B:"s in a position report from + # triggering temperature processing and being interpreted as a bed + # temperature - can happen with COREXY in current Marlin + # + # see also issue #1373 + pass + + # 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): if not disable_external_heatup_detection and not line.strip().startswith("ok") and not self._heating: self._logger.debug("Externally triggered heatup detected") self._heating = True From 397f7621824a389b49861fb881d8fd7a49bc8317 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Jun 2016 17:15:57 +0200 Subject: [PATCH 13/44] Don't trigger initial passive login before viewmodels are available Closes #1374 --- src/octoprint/static/js/app/viewmodels/loginstate.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index 0064439b0..0747e2df2 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -129,7 +129,8 @@ $(function() { self.allViewModels = allViewModels; }; - self.onServerConnect = self.onServerReconnect = function() { + self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() { + if (self.allViewModels == undefined) return; self.requestData(); }; } From 611c1ccf4a2e3076dae7638a5238212adb28d3cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 16 Jun 2016 12:08:46 +0200 Subject: [PATCH 14/44] Disable GCODE viewer if browser is unsupported --- src/octoprint/static/gcodeviewer/js/ui.js | 19 +++++++++++++------ .../static/js/app/viewmodels/gcode.js | 8 +++++++- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/octoprint/static/gcodeviewer/js/ui.js b/src/octoprint/static/gcodeviewer/js/ui.js index 47d539fd9..31a4aeefa 100644 --- a/src/octoprint/static/gcodeviewer/js/ui.js +++ b/src/octoprint/static/gcodeviewer/js/ui.js @@ -104,8 +104,11 @@ GCODE.ui = (function(){ if(!Modernizr.webworkers)fatal.push("
  • Your browser doesn't seem to support HTML5 Web Workers, this application won't work without it.
  • "); if(!Modernizr.svg)fatal.push("
  • Your browser doesn't seem to support HTML5 SVG, this application won't work without it.
  • "); + var errorList = document.getElementById("errorList"); if(fatal.length>0){ - document.getElementById('errorList').innerHTML = '
      ' + fatal.join('') + '
    '; + if (errorList) { + errorList.innerHTML = '
      ' + fatal.join('') + '
    '; + } console.log("Initialization failed: unsupported browser.") return false; } @@ -117,8 +120,10 @@ GCODE.ui = (function(){ if(!Modernizr.draganddrop)warnings.push("
  • Your browser doesn't seem to support HTML5 Drag'n'Drop, Drop area will not work.
  • "); if(warnings.length>0){ - document.getElementById('errorList').innerHTML = '
      ' + wanings.join('') + '
    '; - console.log("Initialization succeeded with warnings.") + if (errorList) { + errorList.innerHTML = '
      ' + warnings.join('') + '
    '; + } + console.log("Initialization succeeded with warnings.", warnings); } return true; }; @@ -138,12 +143,12 @@ GCODE.ui = (function(){ init: function(options){ if (options) setOptions(options); if (!options.container) { - return; + return false; } var capabilitiesResult = checkCapabilities(); if (!capabilitiesResult) { - return; + return false; } setProgress("", 0); @@ -159,6 +164,8 @@ GCODE.ui = (function(){ toolOffsets: options.toolOffsets }); GCODE.renderer.render(0, 0); + + return true; }, clear: function() { @@ -196,4 +203,4 @@ GCODE.ui = (function(){ switchCommands(layerNum, first, last); } } -}()); \ No newline at end of file +}()); diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index 30f132002..e51592f59 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -235,7 +235,7 @@ $(function() { self._configureLayerCommandSlider(commandSliderElement); self.settings.requestData(function() { - GCODE.ui.init({ + var initResult = GCODE.ui.init({ container: "#gcode_canvas", onProgress: self._onProgress, onModelLoaded: self._onModelLoaded, @@ -244,6 +244,12 @@ $(function() { toolOffsets: self._retrieveToolOffsets(), invertAxes: self._retrieveAxesConfiguration() }); + + if (!initResult) { + log.info("Could not initialize GCODE viewer component"); + return; + } + self.synchronizeOptions(); self.enabled = true; }); From 6c20e5852924ed16ec9ef4ec67fcf28c185e27d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 16 Jun 2016 12:10:14 +0200 Subject: [PATCH 15/44] Handle browsers w/o support for visibility tracking --- src/octoprint/static/js/app/main.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 2ead5fc7d..65c9af310 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -56,12 +56,12 @@ $(function() { // register for browser visibility tracking var prop = getHiddenProp(); - if (!prop) return undefined; + if (prop) { + var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange"; + document.addEventListener(eventName, updateBrowserVisibility); - var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange"; - document.addEventListener(eventName, updateBrowserVisibility); - - updateBrowserVisibility(); + updateBrowserVisibility(); + } // exports From cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 16 Jun 2016 12:19:17 +0200 Subject: [PATCH 16/44] Preparing release of 1.2.13 --- CHANGELOG.md | 10 +++ translations/de/LC_MESSAGES/messages.po | 94 ++++++++++++------------- translations/messages.pot | 90 +++++++++++------------ 3 files changed, 102 insertions(+), 92 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee49675ac..73cd647a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # OctoPrint Changelog +## 1.2.13 (2016-06-16) + +### Bug Fixes + + * [#1373](https://github.com/foosel/OctoPrint/issues/1373): Don't parse `B:` as bed temperature when it shows up as part of a position report from `M114`. + * [#1374](https://github.com/foosel/OctoPrint/issues/1374): Don't try to perform a passive login when the components we'd need to inform about a change in login state aren't yet available. Solves a bug that lead - among other things - to the Plugin Manager and the Software Update Plugin not showing anything but misleading errors until the user logged out and back in. + * Fixed the temperature graph looking staying uninitialized until a connection to a printer was established. + +([Commits](https://github.com/foosel/OctoPrint/compare/1.2.12...1.2.13)) + ## 1.2.12 (2016-06-09) ### Improvements diff --git a/translations/de/LC_MESSAGES/messages.po b/translations/de/LC_MESSAGES/messages.po index 1aaf23894..42e8da642 100644 --- a/translations/de/LC_MESSAGES/messages.po +++ b/translations/de/LC_MESSAGES/messages.po @@ -5,21 +5,20 @@ # msgid "" msgstr "" -"Project-Id-Version: OctoPrint\n" +"Project-Id-Version: OctoPrint\n" "Report-Msgid-Bugs-To: i18n@octoprint.org\n" -"POT-Creation-Date: 2016-06-08 11:03+0200\n" +"POT-Creation-Date: 2016-06-16 12:18+0200\n" "PO-Revision-Date: 2016-06-08 11:04+0100\n" "Last-Translator: Gina Häußge \n" "Language: de\n" "Language-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"Plural-Forms: nplurals=2; plural=(n != 1)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.2.0\n" -"X-Generator: Poedit 1.6.8\n" -#: src/octoprint/plugins/announcements/__init__.py:85 +#: src/octoprint/plugins/announcements/__init__.py:89 #: src/octoprint/plugins/announcements/templates/announcements.jinja2:4 #: src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2:1 msgid "Announcements" @@ -976,73 +975,73 @@ msgstr "Zugriff" msgid "Interface" msgstr "Interface" -#: src/octoprint/static/js/app/dataupdater.js:92 -#: src/octoprint/static/js/app/dataupdater.js:127 +#: src/octoprint/static/js/app/dataupdater.js:96 +#: src/octoprint/static/js/app/dataupdater.js:131 #: src/octoprint/static/js/app/helpers.js:451 #: src/octoprint/templates/overlays/offline.jinja2:6 msgid "Server is offline" msgstr "Der Server ist offline" -#: src/octoprint/static/js/app/dataupdater.js:93 +#: src/octoprint/static/js/app/dataupdater.js:97 msgid "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below." msgstr "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde in den nächsten Minuten versuchen mich erneut zu verbinden, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Verbindungsversuch anstoßen." -#: src/octoprint/static/js/app/dataupdater.js:128 +#: src/octoprint/static/js/app/dataupdater.js:132 msgid "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below." msgstr "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich konnte mich nicht automatisch neu verbinden, aber Du kannst mittels des folgenden Buttons einen manuellen Verbindungsversuch anstoßen." -#: src/octoprint/static/js/app/dataupdater.js:206 -#: src/octoprint/static/js/app/dataupdater.js:226 +#: src/octoprint/static/js/app/dataupdater.js:217 +#: src/octoprint/static/js/app/dataupdater.js:237 #, python-format msgid "Slicing ... (%(percentage)d%%)" msgstr "Slice ... (%(percentage)d%%)" -#: src/octoprint/static/js/app/dataupdater.js:228 +#: src/octoprint/static/js/app/dataupdater.js:239 msgid "Slicing ..." msgstr "Slice ..." -#: src/octoprint/static/js/app/dataupdater.js:234 +#: src/octoprint/static/js/app/dataupdater.js:245 msgid "Slicing done" msgstr "Slicing abgeschlossen" -#: src/octoprint/static/js/app/dataupdater.js:234 +#: src/octoprint/static/js/app/dataupdater.js:245 #, python-format msgid "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds" msgstr "%(stl)s nach %(gcode)s geslicet, dauerte %(time).2f Sekunden" -#: src/octoprint/static/js/app/dataupdater.js:244 +#: src/octoprint/static/js/app/dataupdater.js:255 #, python-format msgid "Could not slice %(stl)s to %(gcode)s: %(reason)s" msgstr "Konnte %(stl)s nicht nach %(gcode)s slicen: %(reason)s" -#: src/octoprint/static/js/app/dataupdater.js:245 +#: src/octoprint/static/js/app/dataupdater.js:256 msgid "Slicing failed" msgstr "Slicing fehlgeschlagen" -#: src/octoprint/static/js/app/dataupdater.js:249 +#: src/octoprint/static/js/app/dataupdater.js:260 msgid "Streaming ..." msgstr "Streaming ..." -#: src/octoprint/static/js/app/dataupdater.js:255 +#: src/octoprint/static/js/app/dataupdater.js:266 msgid "Streaming done" msgstr "Streaming abgeschlossen" -#: src/octoprint/static/js/app/dataupdater.js:256 +#: src/octoprint/static/js/app/dataupdater.js:267 #, python-format msgid "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds" msgstr "%(local)s nach %(remote)s gestreamt, dauerte %(time).2f Sekunden" -#: src/octoprint/static/js/app/dataupdater.js:262 -#: src/octoprint/static/js/app/dataupdater.js:270 +#: src/octoprint/static/js/app/dataupdater.js:273 +#: src/octoprint/static/js/app/dataupdater.js:281 msgid "Unhandled communication error" msgstr "Unbehandelter Kommunikationsfehler" -#: src/octoprint/static/js/app/dataupdater.js:263 +#: src/octoprint/static/js/app/dataupdater.js:274 #, python-format msgid "There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s" msgstr "Es gab einen unbehandelten Fehler bei der Kommunikation mit dem Drucker. Daher wurder der laufende Druckauftrag abgebrochen. Fehler: %(firmwareError)s" -#: src/octoprint/static/js/app/dataupdater.js:271 +#: src/octoprint/static/js/app/dataupdater.js:282 #, python-format msgid "The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s" msgstr "Es gab einen unbehandelten Fehler bei der Kommunikation mit dem Drucker. Daher hat OctoPrint die Verbindung getrennt. Fehler: %(error)s" @@ -1120,14 +1119,14 @@ msgstr "Trennen" #: src/octoprint/static/js/app/viewmodels/control.js:65 #: src/octoprint/static/js/app/viewmodels/files.js:329 -#: src/octoprint/static/js/app/viewmodels/gcode.js:465 +#: src/octoprint/static/js/app/viewmodels/gcode.js:471 #: src/octoprint/static/js/app/viewmodels/printerstate.js:177 -#: src/octoprint/static/js/app/viewmodels/temperature.js:56 +#: src/octoprint/static/js/app/viewmodels/temperature.js:58 msgid "Tool" msgstr "Werkzeug" #: src/octoprint/static/js/app/viewmodels/control.js:71 -#: src/octoprint/static/js/app/viewmodels/temperature.js:67 +#: src/octoprint/static/js/app/viewmodels/temperature.js:69 msgid "Hotend" msgstr "Hotend" @@ -1160,15 +1159,15 @@ msgstr "Zuletzt gedruckt" msgid "Last Print Time" msgstr "Letzte Druckdauer" -#: src/octoprint/static/js/app/viewmodels/files.js:520 +#: src/octoprint/static/js/app/viewmodels/files.js:515 msgid "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\"." msgstr "Konnte die Datei nicht hochladen. Bitte stelle sicher, dass es sich um eine GCODE-Datei mit der Extension \".gcode\" oder \".gco\" oder um eine STL-Datei mit der Extension \".stl\" handelt." -#: src/octoprint/static/js/app/viewmodels/files.js:541 +#: src/octoprint/static/js/app/viewmodels/files.js:536 msgid "Uploading ..." msgstr "Uploade ..." -#: src/octoprint/static/js/app/viewmodels/files.js:548 +#: src/octoprint/static/js/app/viewmodels/files.js:543 msgid "Saving ..." msgstr "Speichere ..." @@ -1188,52 +1187,52 @@ msgstr "Analysiere..." msgid "Analyzed" msgstr "Analysiert" -#: src/octoprint/static/js/app/viewmodels/gcode.js:431 +#: src/octoprint/static/js/app/viewmodels/gcode.js:437 msgid "Model size" msgstr "Modelgröße" -#: src/octoprint/static/js/app/viewmodels/gcode.js:432 +#: src/octoprint/static/js/app/viewmodels/gcode.js:438 msgid "Estimated total print time" msgstr "Geschätzte Gesamtdruckdauer" -#: src/octoprint/static/js/app/viewmodels/gcode.js:433 +#: src/octoprint/static/js/app/viewmodels/gcode.js:439 msgid "Estimated layer height" msgstr "Geschätzte Schichthöhe" -#: src/octoprint/static/js/app/viewmodels/gcode.js:433 +#: src/octoprint/static/js/app/viewmodels/gcode.js:439 msgid "mm" msgstr "mm" -#: src/octoprint/static/js/app/viewmodels/gcode.js:434 +#: src/octoprint/static/js/app/viewmodels/gcode.js:440 msgid "Layer count" msgstr "Schichtanzahl" -#: src/octoprint/static/js/app/viewmodels/gcode.js:434 +#: src/octoprint/static/js/app/viewmodels/gcode.js:440 msgid "printed" msgstr "gedruckt" -#: src/octoprint/static/js/app/viewmodels/gcode.js:434 +#: src/octoprint/static/js/app/viewmodels/gcode.js:440 msgid "visited" msgstr "besucht" -#: src/octoprint/static/js/app/viewmodels/gcode.js:457 +#: src/octoprint/static/js/app/viewmodels/gcode.js:463 msgid "Layer number" msgstr "Schichtnummer" -#: src/octoprint/static/js/app/viewmodels/gcode.js:458 +#: src/octoprint/static/js/app/viewmodels/gcode.js:464 msgid "Layer height" msgstr "Schichthöhe" -#: src/octoprint/static/js/app/viewmodels/gcode.js:459 +#: src/octoprint/static/js/app/viewmodels/gcode.js:465 msgid "GCODE commands in layer" msgstr "GCODE Befehle in Schicht" -#: src/octoprint/static/js/app/viewmodels/gcode.js:462 -#: src/octoprint/static/js/app/viewmodels/gcode.js:465 +#: src/octoprint/static/js/app/viewmodels/gcode.js:468 +#: src/octoprint/static/js/app/viewmodels/gcode.js:471 msgid "Filament used by layer" msgstr "Genutztes Filament in Schicht" -#: src/octoprint/static/js/app/viewmodels/gcode.js:469 +#: src/octoprint/static/js/app/viewmodels/gcode.js:475 msgid "Print time for layer" msgstr "Druckdauer für Schicht" @@ -1452,25 +1451,25 @@ msgid "Slicing %(filename)s" msgstr "Slice %(filename)s" #: src/octoprint/static/js/app/viewmodels/temperature.js:23 -#: src/octoprint/static/js/app/viewmodels/temperature.js:74 +#: src/octoprint/static/js/app/viewmodels/temperature.js:76 #: src/octoprint/templates/dialogs/settings/temperatures.jinja2:16 msgid "Bed" msgstr "Bett" -#: src/octoprint/static/js/app/viewmodels/temperature.js:112 +#: src/octoprint/static/js/app/viewmodels/temperature.js:115 msgid "just now" msgstr "gerade eben" -#: src/octoprint/static/js/app/viewmodels/temperature.js:114 +#: src/octoprint/static/js/app/viewmodels/temperature.js:117 msgid "min" msgstr "Min" -#: src/octoprint/static/js/app/viewmodels/temperature.js:253 +#: src/octoprint/static/js/app/viewmodels/temperature.js:256 #: src/octoprint/templates/tabs/temperature.jinja2:11 msgid "Actual" msgstr "Ist" -#: src/octoprint/static/js/app/viewmodels/temperature.js:258 +#: src/octoprint/static/js/app/viewmodels/temperature.js:261 #: src/octoprint/templates/tabs/temperature.jinja2:12 msgid "Target" msgstr "Soll" @@ -2927,3 +2926,4 @@ msgstr "Zeitrafferaufnahme rendern" #~ msgid "Show Announcements..." #~ msgstr "Ankündigungen anzeigen..." + diff --git a/translations/messages.pot b/translations/messages.pot index 1bc5ef396..36190803f 100644 --- a/translations/messages.pot +++ b/translations/messages.pot @@ -6,9 +6,9 @@ #, fuzzy msgid "" msgstr "" -"Project-Id-Version: OctoPrint 1.2.12.dev21+g5006b01.dirty\n" +"Project-Id-Version: OctoPrint 1.2.13.dev7+g6c20e58\n" "Report-Msgid-Bugs-To: i18n@octoprint.org\n" -"POT-Creation-Date: 2016-06-08 11:03+0200\n" +"POT-Creation-Date: 2016-06-16 12:18+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -17,7 +17,7 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.2.0\n" -#: src/octoprint/plugins/announcements/__init__.py:85 +#: src/octoprint/plugins/announcements/__init__.py:89 #: src/octoprint/plugins/announcements/templates/announcements.jinja2:4 #: src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2:1 msgid "Announcements" @@ -1045,14 +1045,14 @@ msgstr "" msgid "Interface" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:92 -#: src/octoprint/static/js/app/dataupdater.js:127 +#: src/octoprint/static/js/app/dataupdater.js:96 +#: src/octoprint/static/js/app/dataupdater.js:131 #: src/octoprint/static/js/app/helpers.js:451 #: src/octoprint/templates/overlays/offline.jinja2:6 msgid "Server is offline" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:93 +#: src/octoprint/static/js/app/dataupdater.js:97 msgid "" "The server appears to be offline, at least I'm not getting any response " "from it. I'll try to reconnect automatically over the next couple" @@ -1060,67 +1060,67 @@ msgid "" "anytime using the button below." msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:128 +#: src/octoprint/static/js/app/dataupdater.js:132 msgid "" "The server appears to be offline, at least I'm not getting any response " "from it. I could not reconnect automatically, but you " "may try a manual reconnect using the button below." msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:206 -#: src/octoprint/static/js/app/dataupdater.js:226 +#: src/octoprint/static/js/app/dataupdater.js:217 +#: src/octoprint/static/js/app/dataupdater.js:237 #, python-format msgid "Slicing ... (%(percentage)d%%)" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:228 +#: src/octoprint/static/js/app/dataupdater.js:239 msgid "Slicing ..." msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:234 +#: src/octoprint/static/js/app/dataupdater.js:245 msgid "Slicing done" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:234 +#: src/octoprint/static/js/app/dataupdater.js:245 #, python-format msgid "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:244 +#: src/octoprint/static/js/app/dataupdater.js:255 #, python-format msgid "Could not slice %(stl)s to %(gcode)s: %(reason)s" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:245 +#: src/octoprint/static/js/app/dataupdater.js:256 msgid "Slicing failed" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:249 +#: src/octoprint/static/js/app/dataupdater.js:260 msgid "Streaming ..." msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:255 +#: src/octoprint/static/js/app/dataupdater.js:266 msgid "Streaming done" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:256 +#: src/octoprint/static/js/app/dataupdater.js:267 #, python-format msgid "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:262 -#: src/octoprint/static/js/app/dataupdater.js:270 +#: src/octoprint/static/js/app/dataupdater.js:273 +#: src/octoprint/static/js/app/dataupdater.js:281 msgid "Unhandled communication error" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:263 +#: src/octoprint/static/js/app/dataupdater.js:274 #, python-format msgid "" "There was an unhandled error while talking to the printer. Due to that " "the ongoing print job was cancelled. Error: %(firmwareError)s" msgstr "" -#: src/octoprint/static/js/app/dataupdater.js:271 +#: src/octoprint/static/js/app/dataupdater.js:282 #, python-format msgid "" "The was an unhandled error while talking to the printer. Due to that " @@ -1200,14 +1200,14 @@ msgstr "" #: src/octoprint/static/js/app/viewmodels/control.js:65 #: src/octoprint/static/js/app/viewmodels/files.js:329 -#: src/octoprint/static/js/app/viewmodels/gcode.js:465 +#: src/octoprint/static/js/app/viewmodels/gcode.js:471 #: src/octoprint/static/js/app/viewmodels/printerstate.js:177 -#: src/octoprint/static/js/app/viewmodels/temperature.js:56 +#: src/octoprint/static/js/app/viewmodels/temperature.js:58 msgid "Tool" msgstr "" #: src/octoprint/static/js/app/viewmodels/control.js:71 -#: src/octoprint/static/js/app/viewmodels/temperature.js:67 +#: src/octoprint/static/js/app/viewmodels/temperature.js:69 msgid "Hotend" msgstr "" @@ -1240,18 +1240,18 @@ msgstr "" msgid "Last Print Time" msgstr "" -#: src/octoprint/static/js/app/viewmodels/files.js:520 +#: src/octoprint/static/js/app/viewmodels/files.js:515 msgid "" "Could not upload the file. Make sure that it is a GCODE file and has the " "extension \".gcode\" or \".gco\" or that it is an STL file with the " "extension \".stl\"." msgstr "" -#: src/octoprint/static/js/app/viewmodels/files.js:541 +#: src/octoprint/static/js/app/viewmodels/files.js:536 msgid "Uploading ..." msgstr "" -#: src/octoprint/static/js/app/viewmodels/files.js:548 +#: src/octoprint/static/js/app/viewmodels/files.js:543 msgid "Saving ..." msgstr "" @@ -1274,52 +1274,52 @@ msgstr "" msgid "Analyzed" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:431 +#: src/octoprint/static/js/app/viewmodels/gcode.js:437 msgid "Model size" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:432 +#: src/octoprint/static/js/app/viewmodels/gcode.js:438 msgid "Estimated total print time" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:433 +#: src/octoprint/static/js/app/viewmodels/gcode.js:439 msgid "Estimated layer height" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:433 +#: src/octoprint/static/js/app/viewmodels/gcode.js:439 msgid "mm" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:434 +#: src/octoprint/static/js/app/viewmodels/gcode.js:440 msgid "Layer count" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:434 +#: src/octoprint/static/js/app/viewmodels/gcode.js:440 msgid "printed" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:434 +#: src/octoprint/static/js/app/viewmodels/gcode.js:440 msgid "visited" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:457 +#: src/octoprint/static/js/app/viewmodels/gcode.js:463 msgid "Layer number" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:458 +#: src/octoprint/static/js/app/viewmodels/gcode.js:464 msgid "Layer height" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:459 +#: src/octoprint/static/js/app/viewmodels/gcode.js:465 msgid "GCODE commands in layer" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:462 -#: src/octoprint/static/js/app/viewmodels/gcode.js:465 +#: src/octoprint/static/js/app/viewmodels/gcode.js:468 +#: src/octoprint/static/js/app/viewmodels/gcode.js:471 msgid "Filament used by layer" msgstr "" -#: src/octoprint/static/js/app/viewmodels/gcode.js:469 +#: src/octoprint/static/js/app/viewmodels/gcode.js:475 msgid "Print time for layer" msgstr "" @@ -1544,25 +1544,25 @@ msgid "Slicing %(filename)s" msgstr "" #: src/octoprint/static/js/app/viewmodels/temperature.js:23 -#: src/octoprint/static/js/app/viewmodels/temperature.js:74 +#: src/octoprint/static/js/app/viewmodels/temperature.js:76 #: src/octoprint/templates/dialogs/settings/temperatures.jinja2:16 msgid "Bed" msgstr "" -#: src/octoprint/static/js/app/viewmodels/temperature.js:112 +#: src/octoprint/static/js/app/viewmodels/temperature.js:115 msgid "just now" msgstr "" -#: src/octoprint/static/js/app/viewmodels/temperature.js:114 +#: src/octoprint/static/js/app/viewmodels/temperature.js:117 msgid "min" msgstr "" -#: src/octoprint/static/js/app/viewmodels/temperature.js:253 +#: src/octoprint/static/js/app/viewmodels/temperature.js:256 #: src/octoprint/templates/tabs/temperature.jinja2:11 msgid "Actual" msgstr "" -#: src/octoprint/static/js/app/viewmodels/temperature.js:258 +#: src/octoprint/static/js/app/viewmodels/temperature.js:261 #: src/octoprint/templates/tabs/temperature.jinja2:12 msgid "Target" msgstr "" From 01c5b77f7bf51158fe286a273beba2e0ea77a1b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 16 Jun 2016 13:14:33 +0200 Subject: [PATCH 17/44] maintenance branch is now 1.2.14.dev --- .versioneer-lookup | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.versioneer-lookup b/.versioneer-lookup index 9bc29b462..3d72f7f77 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -16,11 +16,11 @@ rc HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.2.13 +# maintenance is currently the branch for preparation of maintenance release 1.2.14 # so are any fix/... and improve/... branches -maintenance 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev -fix/.* 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev -improve/.* 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev +maintenance 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev +fix/.* 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev +improve/.* 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev # every other branch is a development branch and thus gets resolved to 1.3.0-dev for now .* 1.3.0 198d3450d94be1a2 pep440-dev From c70708e91585da783c5bd9193f5f560047f4ab52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 16 Jun 2016 13:26:30 +0200 Subject: [PATCH 18/44] Fixed changelog for 1.2.13 Will stay this way now for 1.2.13 though, already released. Follow up versions should reflect the contents of the release notes however. --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 73cd647a3..c39f00611 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,9 @@ * [#1373](https://github.com/foosel/OctoPrint/issues/1373): Don't parse `B:` as bed temperature when it shows up as part of a position report from `M114`. * [#1374](https://github.com/foosel/OctoPrint/issues/1374): Don't try to perform a passive login when the components we'd need to inform about a change in login state aren't yet available. Solves a bug that lead - among other things - to the Plugin Manager and the Software Update Plugin not showing anything but misleading errors until the user logged out and back in. - * Fixed the temperature graph looking staying uninitialized until a connection to a printer was established. + * Fixed the temperature graph staying uninitialized until a connection to a printer was established. + * Fixed an error causing issues during frontend startup if the browser doesn't support tracking browser visibility. + * Fixed an error causing issues during frontend startup if the browser doesn't support the capabilities needed for the GCODE viewer. ([Commits](https://github.com/foosel/OctoPrint/compare/1.2.12...1.2.13)) From f20fdfd4dbf561a50f0dfff96da61ce76e49cf8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Jun 2016 15:57:28 +0200 Subject: [PATCH 19/44] Add octoprint.printer.factory hook --- src/octoprint/server/__init__.py | 50 ++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 5da7ab754..090ba1dbe 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -193,17 +193,43 @@ class Server(object): storage_managers = dict() storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(self._settings.getBaseFolder("uploads")) fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers) - printer = Printer(fileManager, analysisQueue, printerProfileManager) appSessionManager = util.flask.AppSessionManager() pluginLifecycleManager = LifecycleManager(pluginManager) preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml")) + components = dict( + plugin_manager=pluginManager, + printer_profile_manager=printerProfileManager, + event_bus=eventManager, + analysis_queue=analysisQueue, + slicing_manager=slicingManager, + file_manager=fileManager, + app_session_manager=appSessionManager, + plugin_lifecycle_manager=pluginLifecycleManager, + user_manager=userManager, + preemptive_cache=preemptiveCache + ) + + # create printer instance + printer_factories = pluginManager.get_hooks("octoprint.printer.factory") + for name, factory in printer_factories.items(): + try: + printer = factory(components) + if printer is not None: + self._logger.debug("Created printer instance from factory {}".format(name)) + break + except: + self._logger.exception("Error while creating printer instance from factory {}".format(name)) + else: + printer = Printer(fileManager, analysisQueue, printerProfileManager) + components.update(dict(printer=printer)) + # setup access control userManagerName = self._settings.get(["accessControl", "userManager"]) try: clazz = octoprint.util.get_class(userManagerName) userManager = clazz() - except AttributeError, e: + except AttributeError as e: self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName)) userManager = octoprint.users.FilebasedUserManager() finally: @@ -212,20 +238,12 @@ class Server(object): def octoprint_plugin_inject_factory(name, implementation): if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin): return None - return dict( - plugin_manager=pluginManager, - printer_profile_manager=printerProfileManager, - event_bus=eventManager, - analysis_queue=analysisQueue, - slicing_manager=slicingManager, - file_manager=fileManager, - printer=printer, - app_session_manager=appSessionManager, - plugin_lifecycle_manager=pluginLifecycleManager, - data_folder=os.path.join(self._settings.getBaseFolder("data"), name), - user_manager=userManager, - preemptive_cache=preemptiveCache - ) + props = dict() + props.update(components) + props.update(dict( + data_folder=os.path.join(self._settings.getBaseFolder("data"), name) + )) + return props def settings_plugin_inject_factory(name, implementation): plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin(name, implementation) From 4e60c9ff497c7c9882cad5f2faf1ee1e620f4cc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Jun 2016 17:34:30 +0200 Subject: [PATCH 20/44] Added file type path to file manager response --- src/octoprint/filemanager/storage.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 610040dcd..7552e5c1e 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -81,10 +81,12 @@ class StorageInterface(object): "children": { "some_sub_folder": { "type": "folder", + "typePath": ["folder"], "children": { ... } }, "some_file.gcode": { "type": "machinecode", + "typePath": ["machinecode", "gcode"], "hash": "", "links": [ ... ], ... @@ -93,12 +95,14 @@ class StorageInterface(object): } "test.gcode": { "type": "machinecode", + "typePath": ["machinecode", "gcode"], "hash": "", "links": [...], ... }, "test.stl": { "type": "model", + "typePath": ["model", "stl"], "hash": "", "links": [...], ... @@ -1035,12 +1039,12 @@ class LocalFileStorage(StorageInterface): # file handling if os.path.isfile(entry_path): - file_type = octoprint.filemanager.get_file_type(entry) - if not file_type: + type_path = octoprint.filemanager.get_file_type(entry) + if not type_path: # only supported extensions continue else: - file_type = file_type[0] + file_type = type_path[0] if entry in metadata and isinstance(metadata[entry], dict): entry_data = metadata[entry] @@ -1056,6 +1060,7 @@ class LocalFileStorage(StorageInterface): extended_entry_data.update(entry_data) extended_entry_data["name"] = entry extended_entry_data["type"] = file_type + extended_entry_data["typePath"] = type_path stat = os.stat(entry_path) if stat: extended_entry_data["size"] = stat.st_size @@ -1069,13 +1074,14 @@ class LocalFileStorage(StorageInterface): entry_data = dict( name=entry, type="folder", + type_path=["folder"], children=sub_result ) if not filter or filter(entry, entry_data): def get_size(): total_size = 0 - for element in entry_data["children"].itervalues(): + for element in entry_data["children"].values(): if "size" in element: total_size += element["size"] From bf6ce92be2de6534cfb179f8714930a2e6f054aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 21 Jun 2016 17:47:41 +0200 Subject: [PATCH 21/44] Add location for gcode and stl to slicing events --- src/octoprint/filemanager/__init__.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 1dfd46358..d70aad468 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -244,9 +244,16 @@ class FileManager(object): def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None): try: if _error: - eventManager().fire(Events.SLICING_FAILED, {"stl": source_path, "gcode": dest_path, "reason": _error}) + eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path, + stl_location=source_location, + gcode=dest_path, + gcode_location=dest_location, + reason=_error)) elif _cancelled: - eventManager().fire(Events.SLICING_CANCELLED, {"stl": source_path, "gcode": dest_path}) + eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path, + stl_location=source_location, + gcode=dest_path, + gcode_location=dest_location)) else: source_meta = self.get_metadata(source_location, source_path) hash = source_meta["hash"] @@ -262,7 +269,11 @@ class FileManager(object): self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis) end_time = time.time() - eventManager().fire(Events.SLICING_DONE, {"stl": source_path, "gcode": dest_path, "time": end_time - start_time}) + eventManager().fire(Events.SLICING_DONE, dict(stl=source_path, + stl_location=source_location, + gcode=dest_path, + gcode_location=dest_location, + time=end_time - start_time)) if callback is not None: if callback_args is None: From 7d3440b744eac65c50cb14840d09df3429e5fe30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 22 Jun 2016 13:45:17 +0200 Subject: [PATCH 22/44] Set user manager on components dict for plugins --- src/octoprint/server/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 090ba1dbe..37c631e4c 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -234,6 +234,7 @@ class Server(object): userManager = octoprint.users.FilebasedUserManager() finally: userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"]) + components["user_manager"] = userManager def octoprint_plugin_inject_factory(name, implementation): if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin): From 34842d43125ea256cea700e9150549a50ac9cd9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 22 Jun 2016 15:22:47 +0200 Subject: [PATCH 23/44] Use ChainMap for settings --- setup.py | 3 +- src/octoprint/settings.py | 364 +++++++++++++++++++++++++------------- 2 files changed, 247 insertions(+), 120 deletions(-) diff --git a/setup.py b/setup.py index 3ff3246a2..411fb4616 100644 --- a/setup.py +++ b/setup.py @@ -37,7 +37,8 @@ INSTALL_REQUIRES = [ "psutil>=3.2.1,<3.3", "Click>=6.2,<6.3", "awesome-slugify>=1.6.5,<1.7", - "feedparser>=5.2.1,<5.3" + "feedparser>=5.2.1,<5.3", + "chainmap>=1.0.2,<1.1" ] # Additional requirements for optional install options diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 45d172978..700359cdb 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -30,7 +30,12 @@ import logging import re import uuid -from octoprint.util import atomic_write, is_hidden_path +try: + from collections import ChainMap +except ImportError: + from chainmap import ChainMap + +from octoprint.util import atomic_write, is_hidden_path, dict_merge _APPNAME = "OctoPrint" @@ -336,6 +341,95 @@ class NoSuchSettingsPath(BaseException): pass +class HierarchicalChainMap(ChainMap): + + def deep_dict(self, root=None): + if root is None: + root = self + + result = dict() + for key, value in root.items(): + if isinstance(value, dict): + result[key] = self.deep_dict(root=self.__class__._get_next(key, root)) + else: + result[key] = value + return result + + def has_path(self, path, only_local=False, only_defaults=False): + if only_defaults: + current = self.parents + else: + current = self + + try: + for key in path[:-1]: + value = current[key] + if isinstance(value, dict): + current = self.__class__._get_next(key, current, only_local=only_local) + else: + return False + return path[-1] in current + except KeyError: + return False + + def get_by_path(self, path, only_local=False, only_defaults=False): + if only_defaults: + current = self.parents + else: + current = self + + for key in path[:-1]: + value = current[key] + if isinstance(value, dict): + current = self.__class__._get_next(key, current, only_local=only_local) + else: + raise KeyError(key) + + return current[path[-1]] + + def set_by_path(self, path, value): + current = self + + for key in path[:-1]: + if key not in current.maps[0]: + current.maps[0][key] = dict() + if not isinstance(current[key], dict): + raise KeyError(key) + current = self.__class__._hierarchy_for_key(key, current) + + current[path[-1]] = value + + def del_by_path(self, path): + current = self + + for key in path[:-1]: + if not isinstance(current[key], dict): + raise KeyError(key) + current = self.__class__._hierarchy_for_key(key, current) + + del current[path[-1]] + + + @classmethod + def _hierarchy_for_key(cls, key, chain): + wrapped_mappings = list() + for mapping in chain.maps: + if key in mapping: + wrapped_mappings.append(mapping[key]) + else: + wrapped_mappings.append(dict()) + return HierarchicalChainMap(*wrapped_mappings) + + @classmethod + def _get_next(cls, key, node, only_local=False): + if isinstance(node, dict): + return node[key] + elif only_local and not key in node.maps[0]: + raise KeyError(key) + else: + return cls._hierarchy_for_key(key, node) + + class Settings(object): """ The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings @@ -393,6 +487,8 @@ class Settings(object): self._basedir = None + self._map = HierarchicalChainMap(dict(), default_settings) + self._config = None self._dirty = False self._mtime = None @@ -581,8 +677,7 @@ class Settings(object): @property def effective(self): - import octoprint.util - return octoprint.util.dict_merge(default_settings, self._config) + return self._map.deep_dict() @property def effective_yaml(self): @@ -603,6 +698,14 @@ class Settings(object): hash.update(repr(self._config)) return hash.hexdigest() + @property + def _config(self): + return self._map.maps[0] + + @_config.setter + def _config(self, value): + self._map.maps[0] = value + #~~ load and save def load(self, migrate=False): @@ -612,12 +715,15 @@ class Settings(object): self._mtime = self.last_modified # changed from else to handle cases where the file exists, but is empty / 0 bytes if not self._config: - self._config = {} + self._config = dict() if migrate: self._migrate_config() - def _migrate_config(self): + def _migrate_config(self, config=None): + if config is None: + config = self._config + dirty = False migrators = ( @@ -628,20 +734,20 @@ class Settings(object): ) for migrate in migrators: - dirty = migrate() or dirty + dirty = migrate(config) or dirty if dirty: self.save(force=True) - def _migrate_gcode_scripts(self): + def _migrate_gcode_scripts(self, config): """ Migrates an old development version of gcode scripts to the new template based format. """ dirty = False - if "scripts" in self._config: - if "gcode" in self._config["scripts"]: - if "templates" in self._config["scripts"]["gcode"]: - del self._config["scripts"]["gcode"]["templates"] + if "scripts" in config: + if "gcode" in config["scripts"]: + if "templates" in config["scripts"]["gcode"]: + del config["scripts"]["gcode"]["templates"] replacements = dict( disable_steppers="M84", @@ -650,21 +756,21 @@ class Settings(object): disable_fan="M106 S0" ) - for name, script in self._config["scripts"]["gcode"].items(): + for name, script in config["scripts"]["gcode"].items(): self.saveScript("gcode", name, script.format(**replacements)) - del self._config["scripts"] + del config["scripts"] dirty = True return dirty - def _migrate_printer_parameters(self): + def _migrate_printer_parameters(self, config): """ Migrates the old "printer > parameters" data structure to the new printer profile mechanism. """ - default_profile = self._config["printerProfiles"]["defaultProfile"] if "printerProfiles" in self._config and "defaultProfile" in self._config["printerProfiles"] else dict() + default_profile = config["printerProfiles"]["defaultProfile"] if "printerProfiles" in config and "defaultProfile" in config["printerProfiles"] else dict() dirty = False - if "printerParameters" in self._config: - printer_parameters = self._config["printerParameters"] + if "printerParameters" in config: + printer_parameters = config["printerParameters"] if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters: default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict()) @@ -672,12 +778,12 @@ class Settings(object): for axis in ("x", "y", "z", "e"): if axis in printer_parameters["movementSpeed"]: default_profile["axes"][axis]["speed"] = printer_parameters["movementSpeed"][axis] - del self._config["printerParameters"]["movementSpeed"] + del config["printerParameters"]["movementSpeed"] if "invertedAxes" in printer_parameters: for axis in ("x", "y", "z", "e"): if axis in printer_parameters["invertedAxes"]: default_profile["axes"][axis]["inverted"] = True - del self._config["printerParameters"]["invertedAxes"] + del config["printerParameters"]["invertedAxes"] if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters: if not "extruder" in default_profile: @@ -685,14 +791,14 @@ class Settings(object): if "numExtruders" in printer_parameters: default_profile["extruder"]["count"] = printer_parameters["numExtruders"] - del self._config["printerParameters"]["numExtruders"] + del config["printerParameters"]["numExtruders"] if "extruderOffsets" in printer_parameters: extruder_offsets = [] for offset in printer_parameters["extruderOffsets"]: if "x" in offset and "y" in offset: extruder_offsets.append((offset["x"], offset["y"])) default_profile["extruder"]["offsets"] = extruder_offsets - del self._config["printerParameters"]["extruderOffsets"] + del config["printerParameters"]["extruderOffsets"] if "bedDimensions" in printer_parameters: bed_dimensions = printer_parameters["bedDimensions"] @@ -709,49 +815,49 @@ class Settings(object): default_profile["volume"]["width"] = bed_dimensions["x"] if "y" in bed_dimensions: default_profile["volume"]["depth"] = bed_dimensions["y"] - del self._config["printerParameters"]["bedDimensions"] + del config["printerParameters"]["bedDimensions"] dirty = True if dirty: - if not "printerProfiles" in self._config: - self._config["printerProfiles"] = dict() - self._config["printerProfiles"]["defaultProfile"] = default_profile + if not "printerProfiles" in config: + config["printerProfiles"] = dict() + config["printerProfiles"]["defaultProfile"] = default_profile return dirty - def _migrate_reverse_proxy_config(self): + def _migrate_reverse_proxy_config(self, config): """ Migrates the old "server > baseUrl" and "server > scheme" configuration entries to "server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback". """ - if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]): + if "server" in config.keys() and ("baseUrl" in config["server"] or "scheme" in config["server"]): prefix = "" - if "baseUrl" in self._config["server"]: - prefix = self._config["server"]["baseUrl"] - del self._config["server"]["baseUrl"] + if "baseUrl" in config["server"]: + prefix = config["server"]["baseUrl"] + del config["server"]["baseUrl"] scheme = "" - if "scheme" in self._config["server"]: - scheme = self._config["server"]["scheme"] - del self._config["server"]["scheme"] + if "scheme" in config["server"]: + scheme = config["server"]["scheme"] + del config["server"]["scheme"] - if not "reverseProxy" in self._config["server"] or not isinstance(self._config["server"]["reverseProxy"], dict): - self._config["server"]["reverseProxy"] = dict() + if not "reverseProxy" in config["server"] or not isinstance(config["server"]["reverseProxy"], dict): + config["server"]["reverseProxy"] = dict() if prefix: - self._config["server"]["reverseProxy"]["prefixFallback"] = prefix + config["server"]["reverseProxy"]["prefixFallback"] = prefix if scheme: - self._config["server"]["reverseProxy"]["schemeFallback"] = scheme + config["server"]["reverseProxy"]["schemeFallback"] = scheme self._logger.info("Migrated reverse proxy configuration to new structure") return True else: return False - def _migrate_event_config(self): + def _migrate_event_config(self, config): """ Migrates the old event configuration format of type "events > gcodeCommandTrigger" and "event > systemCommandTrigger" to the new events format. """ - if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]): + if "events" in config.keys() and ("gcodeCommandTrigger" in config["events"] or "systemCommandTrigger" in config["events"]): self._logger.info("Migrating config (event subscriptions)...") # migrate event hooks to new format @@ -793,12 +899,12 @@ class Settings(object): return event, command disableSystemCommands = False - if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]: - disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"] + if "systemCommandTrigger" in config["events"] and "enabled" in config["events"]["systemCommandTrigger"]: + disableSystemCommands = not config["events"]["systemCommandTrigger"]["enabled"] disableGcodeCommands = False - if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]: - disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"] + if "gcodeCommandTrigger" in config["events"] and "enabled" in config["events"]["gcodeCommandTrigger"]: + disableGcodeCommands = not config["events"]["gcodeCommandTrigger"]["enabled"] disableAllCommands = disableSystemCommands and disableGcodeCommands newEvents = { @@ -806,8 +912,8 @@ class Settings(object): "subscriptions": [] } - if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]: - for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]: + if "systemCommandTrigger" in config["events"] and "subscriptions" in config["events"]["systemCommandTrigger"]: + for trigger in config["events"]["systemCommandTrigger"]["subscriptions"]: if not ("event" in trigger and "command" in trigger): continue @@ -818,8 +924,8 @@ class Settings(object): newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) newEvents["subscriptions"].append(newTrigger) - if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]: - for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]: + if "gcodeCommandTrigger" in config["events"] and "subscriptions" in config["events"]["gcodeCommandTrigger"]: + for trigger in config["events"]["gcodeCommandTrigger"]["subscriptions"]: if not ("event" in trigger and "command" in trigger): continue @@ -831,7 +937,7 @@ class Settings(object): newTrigger["command"] = newTrigger["command"].split(",") newEvents["subscriptions"].append(newTrigger) - self._config["events"] = newEvents + config["events"] = newEvents self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"])) return True else: @@ -864,63 +970,78 @@ class Settings(object): ##~~ Internal getter - def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True): - import octoprint.util as util + def _get_by_path(self, path, config): + current = config + for key in path: + if key not in current: + raise NoSuchSettingsPath() + current = current[key] + return current + def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True): if len(path) == 0: raise NoSuchSettingsPath() - if config is None: - config = self._config - if defaults is None: - defaults = default_settings - if preprocessors is None: - preprocessors = self._get_preprocessors + if config is not None or defaults is not None: + if config is None: + config = self._config - while len(path) > 1: - key = path.pop(0) - if key in config and key in defaults: - config = config[key] - defaults = defaults[key] - elif incl_defaults and key in defaults: - config = {} - defaults = defaults[key] - else: - raise NoSuchSettingsPath() + if defaults is None: + defaults = dict(self._map.parents) - if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: - preprocessors = preprocessors[key] - - - k = path.pop(0) - if not isinstance(k, (list, tuple)): - keys = [k] + chain = HierarchicalChainMap(config, defaults) else: - keys = k + chain = self._map + + preprocessor = None + if preprocessors is not None: + try: + preprocessor = self._get_by_path(path, preprocessors) + except NoSuchSettingsPath: + pass + + parent_path = path[:-1] + last = path[-1] + + if not isinstance(last, (list, tuple)): + keys = [last] + else: + keys = last if asdict: - results = {} + results = dict() else: - results = [] + results = list() + for key in keys: - if key in config: - value = config[key] - if merged and key in defaults: - value = util.dict_merge(defaults[key], value) - elif incl_defaults and key in defaults: - value = defaults[key] - else: + try: + value = chain.get_by_path(parent_path + [key], only_local=not incl_defaults) + except KeyError: raise NoSuchSettingsPath() - if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): - value = preprocessors[key](value) + if isinstance(value, dict) and merged: + try: + default_value = chain.get_by_path(parent_path + [key], only_defaults=True) + if default_value is not None: + value = dict_merge(default_value, value) + except KeyError: + raise NoSuchSettingsPath() + + if preprocessors is not None: + try: + preprocessor = self._get_by_path(path, preprocessors) + except: + pass + + if callable(preprocessor): + value = preprocessor(value) if asdict: results[key] = value else: results.append(value) - if not isinstance(k, (list, tuple)): + if not isinstance(last, (list, tuple)): if asdict: return results.values().pop() else: @@ -1056,41 +1177,46 @@ class Settings(object): if self._mtime is not None and self.last_modified != self._mtime: self.load() - if config is None: - config = self._config - if defaults is None: - defaults = default_settings - if preprocessors is None: - preprocessors = self._set_preprocessors + if config is not None or defaults is not None: + if config is None: + config = self._config - while len(path) > 1: - key = path.pop(0) - if key in config.keys() and key in defaults.keys(): - config = config[key] - defaults = defaults[key] - elif key in defaults.keys(): - config[key] = {} - config = config[key] - defaults = defaults[key] + if defaults is None: + defaults = dict(self._map.parents) + + chain = HierarchicalChainMap(config, defaults) + else: + chain = self._map + + preprocessor = None + if preprocessors is not 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) + default_value = chain.get_by_path(path, only_defaults=True) + in_local = chain.has_path(path, only_local=True) + in_defaults = chain.has_path(path, only_defaults=True) + except KeyError: + return + + if not force and in_defaults and in_local and default_value == value: + try: + chain.del_by_path(path) + self._dirty = True + except KeyError: + pass + elif force or (not in_local and in_defaults and default_value != value) or (in_local and current != value): + if value is None and in_local: + chain.del_by_path(path) else: - return - - if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: - preprocessors = preprocessors[key] - - key = path.pop(0) - - if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): - value = preprocessors[key](value) - - if not force and key in defaults and key in config and defaults[key] == value: - del config[key] - self._dirty = True - elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value): - if value is None and key in config: - del config[key] - else: - config[key] = value + chain.set_by_path(path, value) self._dirty = True def setInt(self, path, value, **kwargs): From c879ae40997b9f679fab7537d23bd85679293484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 23 Jun 2016 11:25:57 +0200 Subject: [PATCH 24/44] Allow adding a settings overlay --- src/octoprint/settings.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 700359cdb..e7968ce23 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -720,6 +720,25 @@ class Settings(object): if migrate: self._migrate_config() + def add_overlay(self, overlay, migrate=False): + config = None + + if isinstance(overlay, basestring): + if os.path.exists(overlay) and os.path.isfile(overlay): + with open(overlay, "r") as f: + config = yaml.safe_load(f) + elif isinstance(overlay, dict): + config = overlay + else: + raise ValueError("Overlay must be either a path to a yaml file or a dictionary") + + if not isinstance(config, dict): + raise ValueError("Configuration data must be a dict but is a {}".format(config.__class__)) + + if migrate: + self._migrate_config(config) + self._map.parents.maps.insert(0, config) + def _migrate_config(self, config=None): if config is None: config = self._config From 9131b3edd63e1de24ddecc07d3b4874004b76b20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 23 Jun 2016 11:26:51 +0200 Subject: [PATCH 25/44] Allow defining a class on confirmation dialog --- src/octoprint/static/js/app/helpers.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index f691acb4a..a26f95662 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -529,6 +529,7 @@ function showConfirmationDialog(msg, onacknowledge, options) { var proceed = options.proceed || gettext("Proceed"); var proceedClass = options.proceedClass || "danger"; var onproceed = options.onproceed || undefined; + var dialogClass = options.dialogClass || ""; var modalHeader = $('

    ' + title + '

    '); var modalBody = $('

    ' + message + '

    ' + question + '

    '); @@ -541,6 +542,7 @@ function showConfirmationDialog(msg, onacknowledge, options) { var modal = $('
    ') .addClass('modal hide fade') + .addClass(dialogClass) .append($('
    ').addClass('modal-header').append(modalHeader)) .append($('
    ').addClass('modal-body').append(modalBody)) .append($('
    ').addClass('modal-footer').append(cancelButton).append(proceedButton)); From 19ff9ac664bdc7afc99f6cc47f029be094ae3418 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 23 Jun 2016 13:54:14 +0200 Subject: [PATCH 26/44] Allow plugins to define settings overlays --- src/octoprint/__init__.py | 59 +++++++++++++++++++++++++++++++- src/octoprint/plugin/core.py | 24 +++++++++++-- src/octoprint/server/__init__.py | 19 ++++++---- src/octoprint/settings.py | 14 ++++++-- 4 files changed, 104 insertions(+), 12 deletions(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index fa67ad1c0..4c20bd9f0 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -201,8 +201,65 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con def init_pluginsystem(settings): """Initializes the plugin manager based on the settings.""" + from octoprint.plugin import plugin_manager - return plugin_manager(init=True, settings=settings) + pm = plugin_manager(init=True, settings=settings) + + logger = logging.getLogger(__name__) + settings_overlays = dict() + disabled_from_overlays = dict() + + def handle_plugin_loaded(name, plugin): + if hasattr(plugin.instance, "__plugin_settings_overlay__"): + # plugin has a settings overlay, inject it + overlay_definition = getattr(plugin.instance, "__plugin_settings_overlay__") + if isinstance(overlay_definition, (tuple, list)): + overlay_definition, order = overlay_definition + else: + order = None + + overlay = settings.load_overlay(overlay_definition) + + if "plugins" in overlay and "_disabled" in overlay["plugins"]: + disabled_plugins = overlay["plugins"]["_disabled"] + del overlay["plugins"]["_disabled"] + disabled_from_overlays[name] = (disabled_plugins, order) + + settings_overlays[name] = overlay + logger.debug("Found settings overlay on plugin {}".format(name)) + + def handle_plugins_loaded(startup=False, initialize_implementations=True, force_reload=None): + if not startup: + return + + sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, x[2], x[0])) + + disabled_list = pm.plugin_disabled_list + already_processed = [] + for name, addons, _ in sorted_disabled_from_overlays: + if not name in disabled_list and not name.endswith("disabled"): + for addon in addons: + if addon in disabled_list: + continue + + if addon in already_processed: + logger.info("Plugin {} wants to disable plugin {}, but that was already processed".format(name, addon)) + + if not addon in already_processed and not addon in disabled_list: + disabled_list.append(addon) + logger.info("Disabling plugin {} as defined by plugin {} through settings overlay".format(addon, name)) + already_processed.append(name) + + def handle_plugin_enabled(name, plugin): + if name in settings_overlays: + settings.add_overlay(settings_overlays[name]) + logger.info("Added settings overlay from plugin {}".format(name)) + + pm.on_plugin_loaded = handle_plugin_loaded + pm.on_plugins_loaded = handle_plugins_loaded + pm.on_plugin_enabled = handle_plugin_enabled + pm.reload_plugins(startup=True, initialize_implementations=False) + return pm #~~ server main method diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 869d15dfc..cbcf51e22 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -472,6 +472,9 @@ class PluginManager(object): self.on_plugin_disabled = lambda *args, **kwargs: None self.on_plugin_implementations_initialized = lambda *args, **kwargs: None + self.on_plugins_loaded = lambda *args, **kwargs: None + self.on_plugins_enabled = lambda *args, **kwargs: None + self.registered_clients = [] self.marked_plugins = defaultdict(list) @@ -480,8 +483,6 @@ class PluginManager(object): self._python_virtual_env = False self._detect_python_environment() - self.reload_plugins(startup=True, initialize_implementations=False) - def _detect_python_environment(self): from distutils.command.install import install as cmd_install from distutils.dist import Distribution @@ -667,16 +668,33 @@ class PluginManager(object): plugins = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload)) self.disabled_plugins.update(plugins) + # 1st pass: loading the plugins for name, plugin in plugins.items(): try: self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations) - if not self._is_plugin_disabled(name): + except PluginNeedsRestart: + pass + except PluginLifecycleException as e: + self.logger.info(str(e)) + + self.on_plugins_loaded(startup=startup, + initialize_implementations=initialize_implementations, + force_reload=force_reload) + + # 2nd pass: enabling those plugins that need enabling + for name, plugin in plugins.items(): + try: + if plugin.loaded and not self._is_plugin_disabled(name): self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup) except PluginNeedsRestart: pass except PluginLifecycleException as e: self.logger.info(str(e)) + self.on_plugins_enabled(startup=startup, + initialize_implementations=initialize_implementations, + force_reload=force_reload) + if len(self.enabled_plugins) <= 0: self.logger.info("No plugins found") else: diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 37c631e4c..a82a85a81 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1165,17 +1165,24 @@ class LifecycleManager(object): self._plugin_lifecycle_callbacks = defaultdict(list) self._logger = logging.getLogger(__name__) + def wrap_plugin_event(lifecycle_event, new_handler): + orig_handler = getattr(self._plugin_manager, "on_plugin_" + lifecycle_event) + + def handler(*args, **kwargs): + if callable(orig_handler): + orig_handler(*args, **kwargs) + if callable(new_handler): + new_handler(*args, **kwargs) + + return handler + def on_plugin_event_factory(lifecycle_event): def on_plugin_event(name, plugin): self.on_plugin_event(lifecycle_event, name, plugin) return on_plugin_event - self._plugin_manager.on_plugin_loaded = on_plugin_event_factory("loaded") - self._plugin_manager.on_plugin_unloaded = on_plugin_event_factory("unloaded") - self._plugin_manager.on_plugin_activated = on_plugin_event_factory("activated") - self._plugin_manager.on_plugin_deactivated = on_plugin_event_factory("deactivated") - self._plugin_manager.on_plugin_enabled = on_plugin_event_factory("enabled") - self._plugin_manager.on_plugin_disabled = on_plugin_event_factory("disabled") + for event in ("loaded", "unloaded", "enabled", "disabled"): + wrap_plugin_event(event, on_plugin_event_factory(event)) def on_plugin_event(self, event, name, plugin): for lifecycle_callback in self._plugin_lifecycle_callbacks[event]: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index e7968ce23..148ac28b9 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -720,9 +720,16 @@ class Settings(object): if migrate: self._migrate_config() - def add_overlay(self, overlay, migrate=False): + def load_overlay(self, overlay, migrate=True): config = None + if callable(overlay): + try: + overlay = overlay() + except: + self._logger.exception("Error loading overlay from callable") + return + if isinstance(overlay, basestring): if os.path.exists(overlay) and os.path.isfile(overlay): with open(overlay, "r") as f: @@ -737,7 +744,10 @@ class Settings(object): if migrate: self._migrate_config(config) - self._map.parents.maps.insert(0, config) + return config + + def add_overlay(self, overlay): + self._map.maps.insert(1, overlay) def _migrate_config(self, config=None): if config is None: From c693bce761a3595d483d05173f69a0ad60f79519 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 23 Jun 2016 16:13:49 +0200 Subject: [PATCH 27/44] Plugins with settings overlay need restart --- src/octoprint/__init__.py | 2 ++ src/octoprint/plugin/core.py | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 4c20bd9f0..337a43787 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -211,6 +211,8 @@ def init_pluginsystem(settings): def handle_plugin_loaded(name, plugin): if hasattr(plugin.instance, "__plugin_settings_overlay__"): + plugin.needs_restart = True + # plugin has a settings overlay, inject it overlay_definition = getattr(plugin.instance, "__plugin_settings_overlay__") if isinstance(overlay_definition, (tuple, list)): diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index cbcf51e22..a9d7f0613 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -134,6 +134,7 @@ class PluginInfo(object): self.bundled = False self.loaded = False self.managable = True + self.needs_restart = False self._name = name self._version = version @@ -900,7 +901,7 @@ class PluginManager(object): pass def is_restart_needing_plugin(self, plugin): - return self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin) + return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin) def has_restart_needing_implementation(self, plugin): if not plugin.implementation: From 4dafa6704d8c8e2f8f71ada4c8b1919004230f16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 23 Jun 2016 16:14:28 +0200 Subject: [PATCH 28/44] Fix processing of overlays with plugin defaults --- src/octoprint/settings.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 148ac28b9..0fc7b37df 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -706,6 +706,17 @@ class Settings(object): def _config(self, value): self._map.maps[0] = value + @property + def _overlay_maps(self): + if len(self._map.maps) > 2: + return self._map.maps[1:-1] + else: + return {} + + @property + def _default_map(self): + return self._map.maps[-1] + #~~ load and save def load(self, migrate=False): @@ -725,7 +736,7 @@ class Settings(object): if callable(overlay): try: - overlay = overlay() + overlay = overlay(self) except: self._logger.exception("Error loading overlay from callable") return @@ -1018,7 +1029,9 @@ class Settings(object): if defaults is None: defaults = dict(self._map.parents) - chain = HierarchicalChainMap(config, defaults) + # mappings: provided config + any intermediary parents + provided defaults + regular defaults + mappings = [config] + self._overlay_maps + [defaults, self._default_map] + chain = HierarchicalChainMap(*mappings) else: chain = self._map From e5b8fdf0f42ad477cdbef208cd5770124e052b00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 23 Jun 2016 17:51:46 +0200 Subject: [PATCH 29/44] Fix plugin settings cleanup "only_local" was not properly evaluated when retrieving full settings tree for config diffing and minimal persistance in SettingsPlugin. That lead to overlay settings making their way into config.yaml. --- src/octoprint/settings.py | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 0fc7b37df..df4537a2b 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -29,6 +29,7 @@ import yaml import logging import re import uuid +import copy try: from collections import ChainMap @@ -358,6 +359,8 @@ class HierarchicalChainMap(ChainMap): def has_path(self, path, only_local=False, only_defaults=False): if only_defaults: current = self.parents + elif only_local: + current = self.__class__(self.maps[0]) else: current = self @@ -375,6 +378,8 @@ class HierarchicalChainMap(ChainMap): def get_by_path(self, path, only_local=False, only_defaults=False): if only_defaults: current = self.parents + elif only_local: + current = self.__class__(self.maps[0]) else: current = self @@ -1018,7 +1023,7 @@ class Settings(object): current = current[key] return current - def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True): + def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True, do_copy=True): if len(path) == 0: raise NoSuchSettingsPath() @@ -1078,6 +1083,9 @@ class Settings(object): if callable(preprocessor): value = preprocessor(value) + if do_copy: + value = copy.deepcopy(value) + if asdict: results[key] = value else: @@ -1196,18 +1204,16 @@ class Settings(object): #~~ remove def remove(self, path, config=None): - if config is None: - config = self._config + if config is not None: + mappings = [config] + self._overlay_maps + [self._default_map] + chain = HierarchicalChainMap(*mappings) + else: + chain = self._map - while len(path) > 1: - key = path.pop(0) - if not isinstance(config, dict) or key not in config: - return - config = config[key] - - key = path.pop(0) - if isinstance(config, dict) and key in config: - del config[key] + try: + chain.del_by_path(path) + except KeyError: + pass self._dirty = True #~~ setter From 4398931b5cf539fd966fb8d26ba6f23861b2bdfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Jun 2016 09:23:53 +0200 Subject: [PATCH 30/44] Normalize paths for sub path testing in pluginmgr --- src/octoprint/plugin/core.py | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 869d15dfc..d30e5c774 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -491,9 +491,9 @@ class PluginManager(object): cmd.finalize_options() self._python_install_dir = cmd.install_lib - self._python_prefix = sys.prefix + self._python_prefix = os.path.realpath(sys.prefix) self._python_virtual_env = hasattr(sys, "real_prefix") \ - or (hasattr(sys, "base_prefix") and sys.prefix != sys.base_prefix) + or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)) @property def plugins(self): @@ -614,7 +614,7 @@ class PluginManager(object): # of the virtual env, so this check is necessary plugin.managable = os.access(plugin.location, os.W_OK) \ and (not self._python_virtual_env - or plugin.location.startswith(self._python_prefix)) + or is_sub_path_of(plugin.location, self._python_prefix)) plugin.enabled = False result[key] = plugin @@ -648,7 +648,7 @@ class PluginManager(object): def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None): try: instance = imp.load_module(key, f, filename, description) - return PluginInfo(key, filename, instance, name=name, version=version, description=summary, author=author, url=url, license=license) + return PluginInfo(key, os.path.realpath(filename), instance, name=name, version=version, description=summary, author=author, url=url, license=license) except: self.logger.exception("Error loading plugin {key}".format(key=key)) return None @@ -1239,6 +1239,27 @@ class PluginManager(object): raise ValueError("Invalid hook definition, neither a callable nor a 2-tuple (callback, order): {!r}".format(hook)) +def is_sub_path_of(path, parent): + """ + Tests if `path` is a sub path (or identical) to `path`. + + >>> is_sub_path_of("/a/b/c", "/a/b") + True + >>> is_sub_path_of("/a/b/c", "/a/b2") + False + >>> is_sub_path_of("/a/b/c", "/b/c") + False + >>> is_sub_path_of("/foo/bar/../../a/b/c", "/a/b") + True + >>> is_sub_path_of("/a/b", "/a/b") + True + """ + rel_path = os.path.relpath(os.path.realpath(path), + os.path.realpath(parent)) + return not (rel_path == os.pardir or + rel_path.startswith(os.pardir + os.sep)) + + class InstalledEntryPoint(pkginfo.Installed): def __init__(self, entry_point, metadata_version=None): From f8a4d73c30bb361e920887886b3e53b7bc788ca3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Jun 2016 11:06:23 +0200 Subject: [PATCH 31/44] Also detect editable plugins installs as managable --- src/octoprint/plugin/core.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index d30e5c774..29f475848 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -614,7 +614,11 @@ class PluginManager(object): # of the virtual env, so this check is necessary plugin.managable = os.access(plugin.location, os.W_OK) \ and (not self._python_virtual_env - or is_sub_path_of(plugin.location, self._python_prefix)) + or is_sub_path_of(plugin.location, self._python_prefix) + or is_editable_install(self._python_install_dir, + package_name, + module_name, + plugin.location)) plugin.enabled = False result[key] = plugin @@ -648,7 +652,7 @@ class PluginManager(object): def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None): try: instance = imp.load_module(key, f, filename, description) - return PluginInfo(key, os.path.realpath(filename), instance, name=name, version=version, description=summary, author=author, url=url, license=license) + return PluginInfo(key, filename, instance, name=name, version=version, description=summary, author=author, url=url, license=license) except: self.logger.exception("Error loading plugin {key}".format(key=key)) return None @@ -1260,6 +1264,22 @@ def is_sub_path_of(path, parent): rel_path.startswith(os.pardir + os.sep)) +def is_editable_install(install_dir, package, module, location): + package_link = os.path.join(install_dir, "{}.egg-link".format(package)) + if os.path.isfile(package_link): + expected_target = os.path.normcase(os.path.realpath(location)) + try: + with open(package_link) as f: + contents = f.readlines() + for line in contents: + target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module))) + if target == expected_target: + return True + except: + pass + return False + + class InstalledEntryPoint(pkginfo.Installed): def __init__(self, entry_point, metadata_version=None): From 0fb1a41fef7cb44569bdafeca9de92a75efca406 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Jun 2016 12:18:13 +0200 Subject: [PATCH 32/44] Fix ETag computation for UIPlugins --- src/octoprint/server/views.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index bb7e373f0..dc35db574 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -162,7 +162,7 @@ def index(): files = collect_files() return _compute_date(files) - def compute_etag(files=None, lastmodified=None): + def compute_etag(files=None, lastmodified=None, additional=None): if callable(custom_etag): try: etag = custom_etag() @@ -178,6 +178,8 @@ def index(): if lastmodified and not isinstance(lastmodified, basestring): from werkzeug.http import http_date lastmodified = http_date(lastmodified) + if additional is None: + additional = [] import hashlib hash = hashlib.sha1() @@ -186,11 +188,13 @@ def index(): hash.update(",".join(sorted(files))) if lastmodified: hash.update(lastmodified) + for add in additional: + hash.update(add) return hash.hexdigest() decorated_view = view decorated_view = util.flask.lastmodified(lambda _: compute_lastmodified())(decorated_view) - decorated_view = util.flask.etagged(lambda _: compute_etag())(decorated_view) + decorated_view = util.flask.etagged(lambda _: compute_etag(additional=cache_key()))(decorated_view) decorated_view = util.flask.cached(timeout=-1, refreshif=validate_cache, key=cache_key, From 7ed71fad289baa411f98a2f07ae8db123beafb80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Jun 2016 14:28:19 +0200 Subject: [PATCH 33/44] Improved request and preemptive caching * UiPlugins may now disable preemptive caching * Preemptive cache recording will also be disabled when preemptive caching is disabled according to settings (so far only execution on startup was prevented then) * Preemptive cache forces configured view. E.g. if plugin "someplugin" was recorded in the preemptive cache, a custom context now makes sure that only that this view will be cached even if request parameters are hard to define to get routing to work correctly for an alternative UI --- src/octoprint/plugin/types.py | 10 +++++ src/octoprint/server/__init__.py | 19 +++++++++- src/octoprint/server/util/flask.py | 16 ++++++-- src/octoprint/server/views.py | 61 +++++++++++++++++++++++------- 4 files changed, 87 insertions(+), 19 deletions(-) diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 2a2844839..4cf435fcb 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -741,6 +741,16 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return None + def get_ui_preemptive_caching_enabled(self): + """ + Allows to control whether the view provided by the plugin should be preemptively + cached on server startup (default) or not. + + Returns: + bool: Whether to enable preemptive caching or not + """ + return True + def get_ui_data_for_preemptive_caching(self): """ Allows defining additional data to be persisted in the preemptive cache configuration, on diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 37c631e4c..74bbbb27b 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -752,6 +752,20 @@ class Server(object): entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0))) for kwargs in entries: plugin = kwargs.get("plugin", None) + if plugin: + try: + plugin_info = pluginManager.get_plugin_info(plugin, require_enabled=True) + implementation = plugin_info.implementation + if implementation is None or not isinstance(implementation, octoprint.plugin.UiPlugin): + self._logger.debug("Plugin {} is not a UiPlugin, preemptive caching makes no sense".format(plugin)) + continue + if not implementation.get_ui_preemptive_caching_enabled(): + self._logger.debug("Plugin {} has disabled preemptive caching".format(plugin)) + continue + except: + self._logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry") + continue + additional_request_data = kwargs.get("_additional_request_data", dict()) kwargs = dict((k, v) for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin") kwargs.update(additional_request_data) @@ -761,8 +775,9 @@ class Server(object): else: self._logger.info("Preemptively caching {} for {!r}".format(route, kwargs)) builder = EnvironBuilder(**kwargs) - with preemptive_cache.disable_access_logging(): - app(builder.get_environ(), lambda *a, **kw: None) + with preemptive_cache.cache_environment(dict(plugin=plugin if plugin is not None else "_default")): + with preemptive_cache.disable_access_logging(): + app(builder.get_environ(), lambda *a, **kw: None) except: self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs)) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index d175bb775..8c7c3a184 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -383,11 +383,14 @@ class PreemptiveCache(object): def __init__(self, cachefile): self.cachefile = cachefile + self.environment = None - self._lock = threading.RLock() self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__) self._log_access = True + self._lock = threading.RLock() + self._environment_lock = threading.RLock() + def record(self, data, unless=None): if callable(unless) and unless(): return @@ -407,6 +410,13 @@ class PreemptiveCache(object): yield self._log_access = True + @contextlib.contextmanager + def cache_environment(self, environment): + with self._environment_lock: + self.environment = environment + yield + self.environment = None + def clean_all_data(self, cleanup_function): assert callable(cleanup_function) @@ -585,13 +595,13 @@ def conditional(condition, met): def check_etag(etag): return flask.request.method in ("GET", "HEAD") and \ - flask.request.if_none_match and \ + flask.request.if_none_match is not None and \ etag in flask.request.if_none_match def check_lastmodified(lastmodified): return flask.request.method in ("GET", "HEAD") and \ - flask.request.if_modified_since and \ + flask.request.if_modified_since is not None and \ lastmodified >= flask.request.if_modified_since diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index dc35db574..feb6588f0 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -37,6 +37,8 @@ _valid_div_re = re.compile("[a-zA-Z_-]+") def index(): global _templates, _plugin_names, _plugin_vars + preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"]) + # helper to check if wizards are active def wizard_active(templates): return templates is not None and bool(templates["wizard"]["order"]) @@ -116,11 +118,13 @@ def index(): files = collect_files() lastmodified = compute_lastmodified(files) lastmodified_ok = util.flask.check_lastmodified(lastmodified) - etag_ok = util.flask.check_etag(compute_etag(files, lastmodified)) + etag_ok = util.flask.check_etag(compute_etag(files=files, + lastmodified=lastmodified, + additional=cache_key())) return lastmodified_ok and etag_ok def validate_cache(cached): - etag_different = compute_etag() != cached.get_etag()[0] + etag_different = compute_etag(additional=cache_key()) != cached.get_etag()[0] return force_refresh or etag_different def collect_files(): @@ -202,8 +206,7 @@ def index(): decorated_view = util.flask.conditional(check_etag_and_lastmodified, NOT_MODIFIED)(decorated_view) return decorated_view - ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render") - for plugin in ui_plugins: + def plugin_view(plugin): if plugin.will_handle_ui(request): # plugin claims responsibility, let it render the UI cached = get_cached_view(plugin._identifier, @@ -214,17 +217,18 @@ def index(): custom_etag=plugin.get_ui_custom_etag, custom_lastmodified=plugin.get_ui_custom_lastmodified) - preemptively_cached = get_preemptively_cached_view(plugin._identifier, - cached, - plugin.get_ui_data_for_preemptive_caching, - plugin.get_ui_additional_request_data_for_preemptive_caching, - plugin.get_ui_additional_unless) + if preemptive_cache_enabled and plugin.get_ui_preemptive_caching_enabled(): + view = get_preemptively_cached_view(plugin._identifier, + cached, + plugin.get_ui_data_for_preemptive_caching, + plugin.get_ui_additional_request_data_for_preemptive_caching, + plugin.get_ui_additional_unless) + else: + view = cached - response = preemptively_cached(now, request, render_kwargs) - if response is not None: - break + return view(now, request, render_kwargs) - else: + def default_view(): wizard = wizard_active(_templates) enable_accesscontrol = userManager.enabled accesscontrol_active = enable_accesscontrol and userManager.hasBeenCustomized() @@ -254,7 +258,36 @@ def index(): cached, dict(), dict()) - response = preemptively_cached() + return preemptively_cached() + + forced_view = None + preemptive_cache_environment = preemptiveCache.environment + if preemptive_cache_environment is not None and isinstance(preemptive_cache_environment, dict): + forced_view = preemptive_cache_environment.get("plugin", "_default") + + if forced_view: + # we have view forced by the preemptive cache + _logger.debug("Forcing rendering of view {}".format(forced_view)) + response = None + if forced_view != "_default": + plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) + if plugin is not None and isinstance(plugin.implementation, octoprint.plugin.UiPlugin): + response = plugin_view(plugin.implementation) + + if response is None: + return default_view() + + else: + # select view from plugins and fall back on default view if no plugin will handle it + ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render") + for plugin in ui_plugins: + identifier = plugin._identifier + if plugin.will_handle_ui(request): + response = plugin_view(plugin) + if response is not None: + break + else: + response = default_view() return response From 4070702931aa29c32bcf0f41c414d11bc4a89f73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Jun 2016 14:42:55 +0200 Subject: [PATCH 34/44] Fix error in deep_dict when settings substructure defaults to None --- src/octoprint/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index df4537a2b..df2b53a1b 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -419,7 +419,7 @@ class HierarchicalChainMap(ChainMap): def _hierarchy_for_key(cls, key, chain): wrapped_mappings = list() for mapping in chain.maps: - if key in mapping: + if key in mapping and mapping[key] is not None: wrapped_mappings.append(mapping[key]) else: wrapped_mappings.append(dict()) From 3258b4b7f0b17dfd130b432bb42cd063e7fe053d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Jun 2016 14:57:52 +0200 Subject: [PATCH 35/44] Fix processing of settings if there are no overlay maps --- src/octoprint/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index df2b53a1b..fe4ace321 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -716,7 +716,7 @@ class Settings(object): if len(self._map.maps) > 2: return self._map.maps[1:-1] else: - return {} + return [] @property def _default_map(self): From cf496662e98c589660836ea6471373c703715b62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Jun 2016 14:59:25 +0200 Subject: [PATCH 36/44] If plugin is not enabled/installed, skip preemptive caching --- src/octoprint/server/__init__.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 74bbbb27b..e313d88e3 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -755,6 +755,10 @@ class Server(object): if plugin: try: plugin_info = pluginManager.get_plugin_info(plugin, require_enabled=True) + if plugin_info is None: + self._logger.debug("Plugin {} is not installed or enabled, preemptive caching makes no sense".format(plugin)) + continue + implementation = plugin_info.implementation if implementation is None or not isinstance(implementation, octoprint.plugin.UiPlugin): self._logger.debug("Plugin {} is not a UiPlugin, preemptive caching makes no sense".format(plugin)) From b39bb4c961558896e91c4314667be9432c639d08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 27 Jun 2016 12:19:28 +0200 Subject: [PATCH 37/44] Move get_connection_options as classmethod into PrinterInterface --- src/octoprint/printer/__init__.py | 57 +++++++++++++++----------- src/octoprint/server/__init__.py | 3 +- src/octoprint/server/api/connection.py | 8 ++-- src/octoprint/server/api/settings.py | 5 +-- 4 files changed, 39 insertions(+), 34 deletions(-) diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index 857e9b3e6..e46227c1c 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -23,31 +23,15 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re -import octoprint.util.comm as comm from octoprint.settings import settings +from octoprint.util import deprecated + +@deprecated(message="get_connection_options has been replaced by PrinterInterface.get_connection_options", + includedoc="Replaced by :func:`PrinterInterface.get_connection_options`", + since="1.3.0") def get_connection_options(): - """ - Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer. - - Returned ``dict`` has the following structure:: - - ports: - baudrates: - portPreference: - baudratePreference: - autoconnect: - - Returns: - (dict): A dictionary holding the connection options in the structure specified above - """ - return { - "ports": comm.serialList(), - "baudrates": comm.baudrateList(), - "portPreference": settings().get(["serial", "port"]), - "baudratePreference": settings().getInt(["serial", "baudrate"]), - "autoconnect": settings().getBoolean(["serial", "autoconnect"]) - } + return PrinterInterface.get_connection_options() class PrinterInterface(object): @@ -65,6 +49,31 @@ class PrinterInterface(object): valid_heater_regex = re.compile("^(tool\d+|bed)$") """Regex for valid heater identifiers.""" + @classmethod + def get_connection_options(cls): + """ + Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer. + + Returned ``dict`` has the following structure:: + + ports: + baudrates: + portPreference: + baudratePreference: + autoconnect: + + Returns: + (dict): A dictionary holding the connection options in the structure specified above + """ + import octoprint.util.comm as comm + return { + "ports": comm.serialList(), + "baudrates": comm.baudrateList(), + "portPreference": settings().get(["serial", "port"]), + "baudratePreference": settings().getInt(["serial", "baudrate"]), + "autoconnect": settings().getBoolean(["serial", "autoconnect"]) + } + def connect(self, port=None, baudrate=None, profile=None): """ Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a @@ -200,7 +209,7 @@ class PrinterInterface(object): Arguments: factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an - int between 0 and 100 or a float between 0 and 1. + int between 0 and 100 or a float between 0 and 1. """ raise NotImplementedError() @@ -210,7 +219,7 @@ class PrinterInterface(object): Arguments: factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an - int between 0 and 100 or a float between 0 and 1. + int between 0 and 100 or a float between 0 and 1. """ raise NotImplementedError() diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index e313d88e3..733b68c0f 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -53,7 +53,6 @@ user_permission = Permission(RoleNeed("user")) # only import the octoprint stuff down here, as it might depend on things defined above to be initialized already from octoprint import __version__, __branch__, __display_version__, __revision__ -from octoprint.printer import get_connection_options from octoprint.printer.profile import PrinterProfileManager from octoprint.printer.standard import Printer from octoprint.settings import settings @@ -469,7 +468,7 @@ class Server(object): if self._settings.getBoolean(["serial", "autoconnect"]): (port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"]) printer_profile = printerProfileManager.get_default() - connectionOptions = get_connection_options() + connectionOptions = printer.__class__.get_connection_options() if port in connectionOptions["ports"]: printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default") diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index 40c7259fc..d7c75b9fe 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -8,11 +8,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from flask import request, jsonify, make_response from octoprint.settings import settings -from octoprint.printer import get_connection_options from octoprint.server import printer, printerProfileManager, NO_CONTENT from octoprint.server.api import api from octoprint.server.util.flask import restricted_access, get_json_command_from_request -import octoprint.util as util @api.route("/connection", methods=["GET"]) @@ -42,7 +40,7 @@ def connectionCommand(): return response if command == "connect": - connection_options = get_connection_options() + connection_options = printer.__class__.get_connection_options() port = None baudrate = None @@ -75,7 +73,7 @@ def connectionCommand(): return NO_CONTENT def _get_options(): - connection_options = get_connection_options() + connection_options = printer.__class__.get_connection_options() profile_options = printerProfileManager.get_all() default_profile = printerProfileManager.get_default() @@ -88,4 +86,4 @@ def _get_options(): printerProfilePreference=default_profile["id"] if "id" in default_profile else None ) - return options \ No newline at end of file + return options diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index d0f56874b..a67dc2a40 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -12,9 +12,8 @@ from werkzeug.exceptions import BadRequest from octoprint.events import eventManager, Events from octoprint.settings import settings -from octoprint.printer import get_connection_options -from octoprint.server import admin_permission +from octoprint.server import admin_permission, printer from octoprint.server.api import api from octoprint.server.util.flask import restricted_access @@ -30,7 +29,7 @@ def getSettings(): s = settings() - connectionOptions = get_connection_options() + connectionOptions = printer.__class__.get_connection_options() data = { "api": { From 73ba5b05a9985d832ddd6f4319339ba799a484f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Jun 2016 10:29:05 +0200 Subject: [PATCH 38/44] Add unit tests for settings --- src/octoprint/settings.py | 55 ++- tests/settings/__init__.py | 10 + tests/settings/_files/config.yaml | 15 + tests/settings/_files/defaults.yaml | 21 + tests/settings/test_settings.py | 581 ++++++++++++++++++++++++++++ 5 files changed, 667 insertions(+), 15 deletions(-) create mode 100644 tests/settings/__init__.py create mode 100644 tests/settings/_files/config.yaml create mode 100644 tests/settings/_files/defaults.yaml create mode 100644 tests/settings/test_settings.py diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 45d172978..4d925e9e0 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -603,6 +603,15 @@ class Settings(object): hash.update(repr(self._config)) return hash.hexdigest() + @property + def last_modified(self): + """ + Returns: + int: The last modification time of the configuration file. + """ + stat = os.stat(self._configfile) + return stat.st_mtime + #~~ load and save def load(self, migrate=False): @@ -853,15 +862,6 @@ class Settings(object): self.load() return True - @property - def last_modified(self): - """ - Returns: - int: The last modification time of the configuration file. - """ - stat = os.stat(self._configfile) - return stat.st_mtime - ##~~ Internal getter def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True): @@ -1032,25 +1032,41 @@ class Settings(object): #~~ remove - def remove(self, path, config=None): + def remove(self, path, config=None, error_on_path=False): + if not len(path): + if error_on_path: + raise NoSuchSettingsPath() + return + if config is None: config = self._config while len(path) > 1: key = path.pop(0) if not isinstance(config, dict) or key not in config: + if error_on_path: + raise NoSuchSettingsPath() return config = config[key] + if not isinstance(config, dict): + if error_on_path: + raise NoSuchSettingsPath() + return + key = path.pop(0) - if isinstance(config, dict) and key in config: + if key in config: del config[key] - self._dirty = True + self._dirty = True + elif error_on_path: + raise NoSuchSettingsPath() #~~ setter - def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None): + def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None, error_on_path=False): if len(path) == 0: + if error_on_path: + raise NoSuchSettingsPath() return if self._mtime is not None and self.last_modified != self._mtime: @@ -1073,17 +1089,26 @@ class Settings(object): config = config[key] defaults = defaults[key] else: + if error_on_path: + raise NoSuchSettingsPath() return if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: preprocessors = preprocessors[key] + if not isinstance(config, dict): + if error_on_path: + raise NoSuchSettingsPath() + return + key = path.pop(0) if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): value = preprocessors[key](value) - if not force and key in defaults and key in config and defaults[key] == value: + if not key in defaults and error_on_path: + raise NoSuchSettingsPath() + elif not force and key in defaults and key in config and defaults[key] == value: del config[key] self._dirty = True elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value): @@ -1122,7 +1147,7 @@ class Settings(object): def setBoolean(self, path, value, **kwargs): if value is None or isinstance(value, bool): self.set(path, value, **kwargs) - elif value.lower() in valid_boolean_trues: + elif isinstance(value, basestring) and value.lower() in valid_boolean_trues: self.set(path, True, **kwargs) else: self.set(path, False, **kwargs) diff --git a/tests/settings/__init__.py b/tests/settings/__init__.py new file mode 100644 index 000000000..5159fa897 --- /dev/null +++ b/tests/settings/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +""" +Unit tests for ``octoprint.settings``. +""" + +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/settings/_files/config.yaml b/tests/settings/_files/config.yaml new file mode 100644 index 000000000..071e1f863 --- /dev/null +++ b/tests/settings/_files/config.yaml @@ -0,0 +1,15 @@ +api: + key: test +serial: + timeout: + detection: 1.0 + connection: "5" + additionalPorts: + - /dev/portA + - /dev/portB +server: + port: 8080 +devel: + virtualPrinter: + enabled: true + diff --git a/tests/settings/_files/defaults.yaml b/tests/settings/_files/defaults.yaml new file mode 100644 index 000000000..1c7eff302 --- /dev/null +++ b/tests/settings/_files/defaults.yaml @@ -0,0 +1,21 @@ +api: + enabled: true + key: +folder: + uploads: + timelapse: + timelapse_tmp: + scripts: +serial: + timeout: + detection: 0.5 + connection: 10.0 +server: + host: 0.0.0.0 + port: 5000 +devel: + virtualPrinter: + enabled: false + sendWait: true + waitInterval: 1.0 + repetierStyleResends: false diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py new file mode 100644 index 000000000..c7b7a77f2 --- /dev/null +++ b/tests/settings/test_settings.py @@ -0,0 +1,581 @@ +# coding=utf-8 +""" +Tests for OctoPrint's Settings class + +.. todo:: + + * tests for base folder management + * tests for script management + * tests for settings migration +""" + +import unittest +import shutil +import contextlib +import os +import tempfile +import yaml +import hashlib +import ddt + +import octoprint.settings + +@ddt.ddt +class TestSettings(unittest.TestCase): + + def setUp(self): + self.base_path = os.path.join(os.path.dirname(__file__), "_files") + self.config_path = os.path.realpath(os.path.join(self.base_path, "config.yaml")) + self.defaults_path = os.path.realpath(os.path.join(self.base_path, "defaults.yaml")) + + with open(self.config_path, "r+b") as f: + self.config = yaml.safe_load(f) + with open(self.defaults_path, "r+b") as f: + self.defaults = yaml.safe_load(f) + + from octoprint.util import dict_merge + self.expected_effective = dict_merge(self.defaults, self.config) + + def test_basedir_initialization(self): + with self.mocked_basedir() as basedir: + # construct settings + settings = octoprint.settings.Settings() + + # verify + self.assertTrue(os.path.isdir(basedir)) + self.assertTrue(os.path.isfile(os.path.join(basedir, "config.yaml"))) + self.assertIsNotNone(settings.get(["api", "key"])) + + def test_basedir_folder_creation(self): + with self.mocked_basedir() as basedir: + # construct settings + settings = octoprint.settings.Settings() + + expected_upload_folder = os.path.join(basedir, "uploads") + expected_timelapse_folder = os.path.join(basedir, "timelapse") + expected_timelapse_tmp_folder = os.path.join(basedir, "timelapse", "tmp") + + # test + self.assertFalse(os.path.isdir(expected_upload_folder)) + + upload_folder = settings.getBaseFolder("uploads") + timelapse_folder = settings.getBaseFolder("timelapse") + timelapse_tmp_folder = settings.getBaseFolder("timelapse_tmp") + + for folder, expected in ((upload_folder, expected_upload_folder), + (timelapse_folder, expected_timelapse_folder), + (timelapse_tmp_folder, expected_timelapse_tmp_folder)): + self.assertIsNotNone(folder) + self.assertEquals(folder, expected) + self.assertTrue(os.path.isdir(folder)) + + def test_basedir_initialization_with_custom_basedir(self): + with self.mocked_basedir() as default_basedir: + my_basedir = None + + try: + my_basedir = tempfile.mkdtemp("octoprint-settings-test-custom") + self.assertNotEqual(my_basedir, default_basedir) + + octoprint.settings.Settings(basedir=my_basedir) + + self.assertFalse(os.path.isfile(os.path.join(default_basedir, "config.yaml"))) + self.assertTrue(os.path.isfile(os.path.join(my_basedir, "config.yaml"))) + + finally: + try: + shutil.rmtree(my_basedir) + except: + self.fail("Could not remove temporary custom basedir") + + def test_basedir_initialization_with_custom_config(self): + config_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "_files", "config.yaml")) + + with self.mocked_basedir() as basedir: + my_configdir = None + + try: + my_configdir = tempfile.mkdtemp("octoprint-settings-test-custom") + my_configfile = os.path.join(my_configdir, "config.yaml") + shutil.copy(config_path, my_configfile) + + expected_upload_folder = os.path.join(basedir, "uploads") + + settings = octoprint.settings.Settings(configfile=my_configfile) + upload_folder = settings.getBaseFolder("uploads") + + self.assertFalse(os.path.isfile(os.path.join(basedir, "config.yaml"))) + self.assertTrue(os.path.isfile(my_configfile)) + self.assertIsNotNone(upload_folder) + self.assertTrue(os.path.isdir(upload_folder)) + self.assertEqual(expected_upload_folder, upload_folder) + + finally: + try: + shutil.rmtree(my_configdir) + except: + self.fail("Could not remove temporary custom basedir") + + ##~~ test getters + + def test_get(self): + with self.mocked_config(): + expected_api_key = "test" + + settings = octoprint.settings.Settings() + + api_key = settings.get(["api", "key"]) + + self.assertIsNotNone(api_key) + self.assertEqual(api_key, expected_api_key) + + def test_get_int(self): + with self.mocked_config(): + expected_server_port = 8080 + + settings = octoprint.settings.Settings() + + server_port = settings.get(["server", "port"]) + + self.assertIsNotNone(server_port) + self.assertEqual(server_port, expected_server_port) + + def test_get_int_converted(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + value = settings.getInt(["serial", "timeout", "connection"]) + + self.assertEqual(5, value) + + def test_get_int_invalid(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + value = settings.getInt(["server", "host"]) + + self.assertIsNone(value) + + def test_get_float(self): + with self.mocked_config(): + expected_serial_timeout = 1.0 + + settings = octoprint.settings.Settings() + + serial_timeout = settings.get(["serial", "timeout", "detection"]) + + self.assertIsNotNone(serial_timeout) + self.assertEqual(serial_timeout, expected_serial_timeout) + + def test_get_float_converted(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + value = settings.getFloat(["serial", "timeout", "connection"]) + + self.assertEqual(5.0, value) + + def test_get_float_invalid(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + value = settings.getFloat(["server", "host"]) + + self.assertIsNone(value) + + def test_get_boolean(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + value = settings.get(["devel", "virtualPrinter", "enabled"]) + + self.assertTrue(value) + + def test_get_list(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + data = settings.get(["serial", "additionalPorts"]) + + self.assertEqual(len(data), 2) + self.assertListEqual(["/dev/portA", "/dev/portB"], data) + + def test_get_map(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + data = settings.get(["devel", "virtualPrinter"]) + + self.assertEqual(len(data), 1) + self.assertDictEqual(dict(enabled=True), data) + + def test_get_map_merged(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + data = settings.get(["devel", "virtualPrinter"], merged=True) + + self.assertGreater(len(data), 1) + self.assertDictContainsSubset(dict(enabled=True, + sendWait=True, + waitInterval=1.0), + data) + + def test_get_multiple(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + data = settings.get(["serial", ["timeout", "additionalPorts"]]) + + self.assertIsInstance(data, list) + self.assertEqual(len(data), 2) + + self.assertIsInstance(data[0], dict) + self.assertIsInstance(data[1], list) + + + def test_get_multiple_asdict(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + data = settings.get(["serial", ["timeout", "additionalPorts"]], asdict=True) + + self.assertIsInstance(data, dict) + self.assertEqual(len(data), 2) + + self.assertTrue("timeout" in data) + self.assertTrue("additionalPorts" in data) + + def test_get_invalid(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + value = settings.get(["i", "do", "not", "exist"]) + + self.assertIsNone(value) + + def test_get_invalid_error(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + try: + settings.get(["i", "do", "not", "exist"], error_on_path=True) + self.fail("Expected NoSuchSettingsPath") + except octoprint.settings.NoSuchSettingsPath: + pass + + def test_get_custom_config(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + server_port = settings.getInt(["server", "port"], config=dict(server=dict(port=9090))) + + self.assertEqual(9090, server_port) + + def test_get_custom_defaults(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + api_enabled = settings.getBoolean(["api", "enabled"], defaults=dict(api=dict(enabled=False))) + + self.assertFalse(api_enabled) + + def test_get_empty_path(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + self.assertIsNone(settings.get([])) + + try: + settings.get([], error_on_path=True) + self.fail("Expected NoSuchSettingsPath") + except octoprint.settings.NoSuchSettingsPath: + pass + + ##~~ test setters + + def test_set(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + settings.set(["server", "host"], "127.0.0.1") + + self.assertEqual("127.0.0.1", settings._config["server"]["host"]) + + def test_set_int(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + settings.setInt(["server", "port"], 8181) + + self.assertEqual(8181, settings._config["server"]["port"]) + + def test_set_int_convert(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + settings.setInt(["server", "port"], "8181") + + self.assertEqual(8181, settings._config["server"]["port"]) + + def test_set_float(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + settings.setFloat(["serial", "timeout", "detection"], 1.2) + + self.assertEqual(1.2, settings._config["serial"]["timeout"]["detection"]) + + def test_set_float_convert(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + settings.setFloat(["serial", "timeout", "detection"], "1.2") + + self.assertEqual(1.2, settings._config["serial"]["timeout"]["detection"]) + + def test_set_boolean(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + settings.setBoolean(["devel", "virtualPrinter", "sendWait"], False) + + self.assertEqual(False, settings._config["devel"]["virtualPrinter"]["sendWait"]) + + @ddt.data("1", "yes", "true", "TrUe", "y", "Y", "YES") + def test_set_boolean_convert_string_true(self, value): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + settings.setBoolean(["devel", "virtualPrinter", "repetierStyleResends"], value) + + self.assertEqual(True, settings._config["devel"]["virtualPrinter"]["repetierStyleResends"]) + + @ddt.data("0", "no", "false", ["some", "list"], dict(a="dictionary"), lambda: None) + def test_set_boolean_convert_any_false(self, value): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + settings.setBoolean(["api", "enabled"], value) + + self.assertEqual(False, settings._config["api"]["enabled"]) + + def test_set_default(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + self.assertEqual(8080, settings._config["server"]["port"]) + + settings.set(["server", "port"], 5000) + + self.assertNotIn("port", settings._config["server"]) + self.assertEqual(5000, settings.get(["server", "port"])) + + def test_set_none(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + self.assertTrue("port" in settings._config["server"]) + + settings.set(["server", "port"], None) + + self.assertFalse("port" in settings._config["server"]) + + @ddt.data([], ["api", "lock"], ["api", "lock", "door"], ["serial", "additionalPorts", "key"]) + def test_set_invalid(self, path): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + try: + settings.set(path, "value", error_on_path=True) + self.fail("Expected NoSuchSettingsPath") + except octoprint.settings.NoSuchSettingsPath: + pass + + ##~~ test remove + + def test_remove(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + self.assertTrue("port" in settings._config["server"]) + + settings.remove(["server", "port"]) + + self.assertFalse("port" in settings._config["server"]) + self.assertEqual(5000, settings.get(["server", "port"])) + + @ddt.data([], ["server", "lock"], ["serial", "additionalPorts", "key"]) + def test_remove_invalid(self, path): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + try: + settings.remove(path, error_on_path=True) + self.fail("Expected NoSuchSettingsPath") + except octoprint.settings.NoSuchSettingsPath: + pass + + ##~~ test has + + def test_has(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + + self.assertTrue(settings.has(["api", "key"])) + self.assertFalse(settings.has(["api", "lock"])) + + ##~~ test properties + + def test_effective(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + effective = settings.effective + + self.assertDictEqual(self.expected_effective, effective) + + def test_effective_hash(self): + with self.mocked_config(): + hash = hashlib.md5() + hash.update(repr(self.expected_effective)) + expected_effective_hash = hash.hexdigest() + print(repr(self.expected_effective)) + + settings = octoprint.settings.Settings() + effective_hash = settings.effective_hash + print(repr(settings.effective)) + + self.assertEqual(expected_effective_hash, effective_hash) + + def test_config_hash(self): + with self.mocked_config(): + hash = hashlib.md5() + hash.update(repr(self.config)) + expected_config_hash = hash.hexdigest() + + settings = octoprint.settings.Settings() + config_hash = settings.config_hash + + self.assertEqual(expected_config_hash, config_hash) + + def test_last_modified(self): + with self.mocked_config() as paths: + basedir, configfile = paths + settings = octoprint.settings.Settings() + + last_modified = os.stat(configfile).st_mtime + self.assertEqual(settings.last_modified, last_modified) + + ##~~ test preprocessors + + def test_get_preprocessor(self): + with self.mocked_config(): + config = dict() + defaults = dict(test="some string") + preprocessors = dict(test=lambda x: x.upper()) + + settings = octoprint.settings.Settings() + value = settings.get(["test"], + config=config, + defaults=defaults, + preprocessors=preprocessors) + + self.assertEqual("SOME STRING", value) + + def test_set_preprocessor(self): + with self.mocked_config(): + config = dict() + defaults = dict(foo=dict(bar="fnord")) + preprocessors = dict(foo=dict(bar=lambda x: x.upper())) + + settings = octoprint.settings.Settings() + settings.set(["foo", "bar"], + "value", + config=config, + defaults=defaults, + preprocessors=preprocessors) + + self.assertEqual("VALUE", config["foo"]["bar"]) + + def test_set_external_modification(self): + with self.mocked_config() as paths: + basedir, configfile = paths + settings = octoprint.settings.Settings() + + self.assertEqual("0.0.0.0", settings.get(["server", "host"])) + + # modify yaml file externally + with open(configfile, "r+b") as f: + config = yaml.safe_load(f) + config["server"]["host"] = "127.0.0.1" + with open(configfile, "w+b") as f: + yaml.safe_dump(config, f) + + # set some value, should also reload file before setting new api key + settings.set(["api", "key"], "key") + + # verify updated values + self.assertEqual("127.0.0.1", settings.get(["server", "host"])) + self.assertEqual("key", settings.get(["api", "key"])) + + ##~~ test save + + def test_save(self): + with self.mocked_config() as paths: + basedir, config_path = paths + settings = octoprint.settings.Settings() + + # current modification date of config.yaml + current_modified = os.stat(config_path).st_mtime + + # set a new value + settings.set(["api", "key"], "newkey") + + # should not be written automatically + self.assertEqual(current_modified, os.stat(config_path).st_mtime) + + # should be updated after calling save though + settings.save() + self.assertNotEqual(current_modified, os.stat(config_path).st_mtime) + + def test_save_unmodified(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + last_modified = settings.last_modified + + settings.save() + self.assertEqual(settings.last_modified, last_modified) + + settings.save(force=True) + self.assertGreater(settings.last_modified, last_modified) + + ##~~ helpers + + @contextlib.contextmanager + def mocked_basedir(self): + orig_default_basedir = octoprint.settings._default_basedir + directory = None + + try: + directory = tempfile.mkdtemp("octoprint-settings-test") + octoprint.settings._default_basedir = lambda *args, **kwargs: directory + yield directory + finally: + octoprint.settings._default_basedir = orig_default_basedir + if directory is not None: + try: + shutil.rmtree(directory) + except: + self.fail("Could not remove temporary basedir") + + @contextlib.contextmanager + def mocked_config(self): + orig_defaults = octoprint.settings.default_settings + + with self.mocked_basedir() as basedir: + fresh_config_path = os.path.join(basedir, "config.yaml") + shutil.copy(self.config_path, fresh_config_path) + try: + octoprint.settings.default_settings = self.defaults + yield basedir, fresh_config_path + finally: + octoprint.settings.default_settings = orig_defaults From 3b2af5b7eda3275802ba2f83dc7fb902148bfc10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Jun 2016 10:57:51 +0200 Subject: [PATCH 39/44] Fix settings unit tests --- src/octoprint/settings.py | 24 ++++++++++++++++++------ tests/settings/test_settings.py | 8 ++++---- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index a15385eaf..7fd62e958 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -405,6 +405,9 @@ class HierarchicalChainMap(ChainMap): current[path[-1]] = value def del_by_path(self, path): + if not path: + raise ValueError("Invalid path") + current = self for key in path[:-1]: @@ -693,14 +696,19 @@ class Settings(object): def effective_hash(self): import hashlib hash = hashlib.md5() - hash.update(repr(self.effective)) + hash.update(self.effective_yaml) return hash.hexdigest() + @property + def config_yaml(self): + import yaml + return yaml.safe_dump(self._config) + @property def config_hash(self): import hashlib hash = hashlib.md5() - hash.update(repr(self._config)) + hash.update(self.config_yaml) return hash.hexdigest() @property @@ -1024,7 +1032,7 @@ class Settings(object): return current def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True, do_copy=True): - if len(path) == 0: + if not path: raise NoSuchSettingsPath() if config is not None or defaults is not None: @@ -1122,8 +1130,7 @@ class Settings(object): except NoSuchSettingsPath: if error_on_path: raise - else: - return None + return None def getInt(self, path, **kwargs): value = self.get(path, **kwargs) @@ -1204,6 +1211,11 @@ class Settings(object): #~~ remove def remove(self, path, config=None, error_on_path=False): + if not path: + if error_on_path: + raise NoSuchSettingsPath() + return + if config is not None: mappings = [config] + self._overlay_maps + [self._default_map] chain = HierarchicalChainMap(*mappings) @@ -1221,7 +1233,7 @@ class Settings(object): #~~ setter def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None, error_on_path=False): - if len(path) == 0: + if not path: if error_on_path: raise NoSuchSettingsPath() return diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index c7b7a77f2..75d528bce 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -436,20 +436,20 @@ class TestSettings(unittest.TestCase): def test_effective_hash(self): with self.mocked_config(): hash = hashlib.md5() - hash.update(repr(self.expected_effective)) + hash.update(yaml.safe_dump(self.expected_effective)) expected_effective_hash = hash.hexdigest() - print(repr(self.expected_effective)) + print(yaml.safe_dump(self.expected_effective)) settings = octoprint.settings.Settings() effective_hash = settings.effective_hash - print(repr(settings.effective)) + print(yaml.safe_dump(settings.effective)) self.assertEqual(expected_effective_hash, effective_hash) def test_config_hash(self): with self.mocked_config(): hash = hashlib.md5() - hash.update(repr(self.config)) + hash.update(yaml.safe_dump(self.config)) expected_config_hash = hash.hexdigest() settings = octoprint.settings.Settings() From 015b99fa14f70de4454ed2c27d8f9805ed6eef19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Jun 2016 11:02:44 +0200 Subject: [PATCH 40/44] Fix plugin unit tests --- tests/plugin/test_core.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/plugin/test_core.py b/tests/plugin/test_core.py index b76110afb..119fca801 100644 --- a/tests/plugin/test_core.py +++ b/tests/plugin/test_core.py @@ -17,9 +17,16 @@ class PluginTestCase(unittest.TestCase): self.plugin_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "_plugins") plugin_folders = [self.plugin_folder] - plugin_types = [octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin, octoprint.plugin.AssetPlugin] + plugin_types = [octoprint.plugin.SettingsPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.AssetPlugin] plugin_entry_points = None - self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=[], logging_prefix="logging_prefix.") + self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders, + plugin_types, + plugin_entry_points, + plugin_disabled_list=[], + logging_prefix="logging_prefix.") + self.plugin_manager.reload_plugins(startup=True, initialize_implementations=False) self.plugin_manager.initialize_implementations() def test_plugin_loading(self): From b41c1d89f49b5f4eeaa3cb190623a1c3428eabf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Jun 2016 12:58:08 +0200 Subject: [PATCH 41/44] Docs for octoprint.printer.factory hook --- docs/plugins/hooks.rst | 32 ++++++++++++++++++++++++++++++++ src/octoprint/server/__init__.py | 23 +++++++++++------------ 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index c8842ee40..08f6d40c1 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -676,6 +676,38 @@ octoprint.filemanager.preprocessor :return: The `file_object` as passed in or None, or a replaced version to use instead for further processing. :rtype: AbstractFileWrapper or None +.. _sec-plugins-hook-printer-factory: + +octoprint.printer.factory +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: hook(components, *args, **kwargs) + + Return a :class:`~octoprint.printer.PrinterInstance` instance to use as global printer object. This will + be called only once during initial server startup. + + The provided ``components`` is a dictionary containing the already initialized system components: + + * ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager` + * ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager` + * ``event_bus``: The :class:`~octoprint.events.EventManager` + * ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue` + * ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager` + * ``file_manager``: The :class:`~octoprint.filemanager.FileManager` + * ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager` + * ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager` + * ``user_manager``: The :class:`~octoprint.users.UserManager` + * ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache` + + If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance. + + If no of the registered factories return a printer instance, the default :class:`~octoprint.printer.standard.Printer` + class will be instantiated. + + :param dict components: System components to use for printer instance initialization + :return: The ``printer`` instance to use globally. + :rtype: PrinterInterface subclass or None + .. _sec-plugins-hook-server-http-bodysize: octoprint.server.http.bodysize diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 25fc5a94b..e7e99aa4b 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -196,6 +196,17 @@ class Server(object): pluginLifecycleManager = LifecycleManager(pluginManager) preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml")) + # setup access control + userManagerName = self._settings.get(["accessControl", "userManager"]) + try: + clazz = octoprint.util.get_class(userManagerName) + userManager = clazz() + except AttributeError as e: + self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName)) + userManager = octoprint.users.FilebasedUserManager() + finally: + userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"]) + components = dict( plugin_manager=pluginManager, printer_profile_manager=printerProfileManager, @@ -223,18 +234,6 @@ class Server(object): printer = Printer(fileManager, analysisQueue, printerProfileManager) components.update(dict(printer=printer)) - # setup access control - userManagerName = self._settings.get(["accessControl", "userManager"]) - try: - clazz = octoprint.util.get_class(userManagerName) - userManager = clazz() - except AttributeError as e: - self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName)) - userManager = octoprint.users.FilebasedUserManager() - finally: - userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"]) - components["user_manager"] = userManager - def octoprint_plugin_inject_factory(name, implementation): if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin): return None From df5a6e42d73de92a63cbc052bcbd71bfb7f9b27d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Jun 2016 12:58:31 +0200 Subject: [PATCH 42/44] Docs for additions to slicing event payload --- docs/events/index.rst | 8 ++++++++ src/octoprint/filemanager/__init__.py | 6 +++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/events/index.rst b/docs/events/index.rst index fb2ad0977..483ee2d17 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -352,7 +352,9 @@ SlicingStarted Payload: * ``stl``: the STL's filename + * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename + * ``gcode_location``: the sliced GCODE's location * ``progressAvailable``: true if progress information via the ``slicingProgress`` push update will be available, false if not SlicingDone @@ -361,7 +363,9 @@ SlicingDone Payload: * ``stl``: the STL's filename + * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename + * ``gcode_location``: the sliced GCODE's location * ``time``: the time needed for slicing, in seconds (float) SlicingCancelled @@ -371,7 +375,9 @@ SlicingCancelled Payload: * ``stl``: the STL's filename + * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename + * ``gcode_location``: the sliced GCODE's location SlicingFailed The slicing of a file has failed. @@ -379,7 +385,9 @@ SlicingFailed Payload: * ``stl``: the STL's filename + * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename + * ``gcode_location``: the sliced GCODE's location * ``reason``: the reason for the slicing having failed SlicingProfileAdded diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index d70aad468..14f2b99a0 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -295,7 +295,11 @@ class FileManager(object): import time start_time = time.time() - eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False}) + eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, + "stl_location": source_location, + "gcode": dest_path, + "gcode_location": dest_location, + "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False}) import tempfile f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False) From 7207421051f607f32926e566a2e916950755f30e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Jun 2016 13:02:23 +0200 Subject: [PATCH 43/44] Docs for new typePath property in file model --- docs/api/datamodel.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index bdc2c8048..3eb981435 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -216,10 +216,6 @@ Progress information File related ============ -.. todo:: - - Update to reflect enhanced data now available. - .. _sec-api-datamodel-files-file: File information @@ -242,6 +238,11 @@ File information - String - Type of file. ``model`` or ``machinecode``. Or ``folder`` if it's a folder, in which case the ``children`` node will be populated + * - ``typePath`` + - 1 + - list + - Path to type of file in extension tree. E.g. ``["model", "stl"]`` for ``.stl`` files, or ``["machinecode", "gcode"]`` + for ``.gcode`` files. ``["folder"]`` for folders. Additional properties depend on ``type``. For a ``type`` value of ``folder``, see "Folders". For any other value see "Files". From c4a0b63a87e01a2b588202f0dd57e529b069512c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Jun 2016 14:47:17 +0200 Subject: [PATCH 44/44] Add flag to disable model size detection & check Also marked feature as beta --- src/octoprint/server/api/settings.py | 4 +++- src/octoprint/settings.py | 3 ++- src/octoprint/static/js/app/viewmodels/files.js | 11 +++++++++++ src/octoprint/static/js/app/viewmodels/settings.js | 1 + .../templates/dialogs/settings/features.jinja2 | 9 ++++++++- 5 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index a67dc2a40..ba08fc24a 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -73,7 +73,8 @@ def getSettings(): "externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]), "keyboardControl": s.getBoolean(["feature", "keyboardControl"]), "pollWatched": s.getBoolean(["feature", "pollWatched"]), - "ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]) + "ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]), + "modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]) }, "serial": { "port": connectionOptions["portPreference"], @@ -235,6 +236,7 @@ def _saveSettings(data): if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"]) 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 "serial" in data.keys(): if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 7fd62e958..fed93526b 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -181,7 +181,8 @@ default_settings = { "pollWatched": False, "ignoreIdenticalResends": False, "identicalResendsCountdown": 7, - "supportFAsCommand": False + "supportFAsCommand": False, + "modelSizeDetection": True }, "folder": { "uploads": None, diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index c20bda063..8789405f1 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -447,6 +447,15 @@ $(function() { }; self.evaluatePrintDimensions = function(data, notify) { + if (!self.settingsViewModel.feature_modelSizeDetection()) { + return true; + } + + var analysis = data["gcodeAnalysis"]; + if (!analysis) { + return true; + } + var printingArea = data["gcodeAnalysis"]["printingArea"]; if (!printingArea) { return true; @@ -507,6 +516,8 @@ $(function() { warning += pnotifyAdditionalInfo(info); + warning += "

    You can disable this check via Settings > Features > \"Enable model size detection [...]\"

    "; + new PNotify({ title: gettext("Object doesn't fit print volume"), text: warning, diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index d13b07089..eb7aacd5f 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -131,6 +131,7 @@ $(function() { self.feature_keyboardControl = ko.observable(undefined); self.feature_pollWatched = ko.observable(undefined); self.feature_ignoreIdenticalResends = ko.observable(undefined); + self.feature_modelSizeDetection = ko.observable(undefined); self.serial_port = ko.observable(); self.serial_baudrate = ko.observable(); diff --git a/src/octoprint/templates/dialogs/settings/features.jinja2 b/src/octoprint/templates/dialogs/settings/features.jinja2 index ad13738c7..c00e93434 100644 --- a/src/octoprint/templates/dialogs/settings/features.jinja2 +++ b/src/octoprint/templates/dialogs/settings/features.jinja2 @@ -8,7 +8,14 @@
    -
    +
    +
    +
    +