From 84b83b6cecbd6aa2066bfa36f4aa64650098e704 Mon Sep 17 00:00:00 2001 From: Kestin Goforth Date: Wed, 28 Sep 2022 06:23:12 -0400 Subject: [PATCH 01/11] =?UTF-8?q?=F0=9F=90=9B=20Defer=20M20=20commands=20u?= =?UTF-8?q?ntil=20initial=20capability=20report=20is=20done=20(#4577)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Defer M20 commands until initial capability report is done * Fix whitepsace * Add setting for deferring sd file refresh * Refactor to be more similar to _firmware_info implementation * Add event hook for after capability report * Improve capability report hook name * Fix headline formatting Co-authored-by: Gina Häußge --- docs/configuration/config_yaml.rst | 4 ++ docs/plugins/hooks.rst | 24 +++++++++ src/octoprint/schema/config/serial.py | 3 ++ src/octoprint/server/api/settings.py | 6 +++ .../static/js/app/viewmodels/settings.js | 2 + .../dialogs/settings/serialconnection.jinja2 | 6 +++ src/octoprint/util/comm.py | 49 +++++++++++++++++-- 7 files changed, 89 insertions(+), 5 deletions(-) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index baa7e5519..71bf107cc 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -764,6 +764,10 @@ Use the following settings to configure the serial connection to the printer: # during connect. waitForStartOnConnect: false + # Specifies whether OctoPrint should wait to load the SD card file list until the first firmware capability + # report is processed. + waitToLoadSdFileList: false + # Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for # successful communication with Repetier firmware alwaysSendChecksum: false diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 47822eb48..bf4207bea 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -509,6 +509,30 @@ octoprint.comm.protocol.firmware.capabilities .. _sec-plugins-hook-comm-protocol-action: +octoprint.comm.protocol.firmware.capability_report +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: firmware_capability_report_hook(comm_instance, firmware_capabilities, *args, **kwargs) + + .. versionadded:: 1.9.0 + + Be notified when all capability report entries are received from the printer. + + Hook handlers may use this to react to the end of the custom firmware capability report. OctoPrint parses the received + capability lines and provides a dictionary of all reported capabilities and whether they're enabled to the handler. + + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + + :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. + :param dict firmware_capabilities: Reported capabilities (capability name mapped to enabled flag) + +.. _sec-plugins-hook-comm-protocol-action: + octoprint.comm.protocol.action ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/octoprint/schema/config/serial.py b/src/octoprint/schema/config/serial.py index e336dc0e4..163b0be53 100644 --- a/src/octoprint/schema/config/serial.py +++ b/src/octoprint/schema/config/serial.py @@ -167,6 +167,9 @@ class SerialConfig(BaseModel): waitForStartOnConnect: bool = False """Whether OctoPrint should wait for the `start` response from the printer before trying to send commands during connect.""" + waitToLoadSdFileList: bool = False + """Specifies whether OctoPrint should wait to load the SD card file list until the first firmware capability report is processed.""" + alwaysSendChecksum: bool = False """Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for successful communication with Repetier firmware.""" diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index ba01887ca..31b9ef562 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -213,6 +213,7 @@ def getSettings(): "abortHeatupOnCancel": s.getBoolean(["serial", "abortHeatupOnCancel"]), "supportResendsWithoutOk": s.get(["serial", "supportResendsWithoutOk"]), "waitForStart": s.getBoolean(["serial", "waitForStartOnConnect"]), + "waitToLoadSdFileList": s.getBoolean(["serial", "waitToLoadSdFileList"]), "alwaysSendChecksum": s.getBoolean(["serial", "alwaysSendChecksum"]), "neverSendChecksum": s.getBoolean(["serial", "neverSendChecksum"]), "sendChecksumWithUnknownCommands": s.getBoolean( @@ -834,6 +835,11 @@ def _saveSettings(data): s.setBoolean( ["serial", "waitForStartOnConnect"], data["serial"]["waitForStart"] ) + if "waitToLoadSdFileList" in data["serial"]: + s.setBoolean( + ["serial", "waitToLoadSdFileList"], + data["serial"]["waitToLoadSdFileList"], + ) if "alwaysSendChecksum" in data["serial"]: s.setBoolean( ["serial", "alwaysSendChecksum"], data["serial"]["alwaysSendChecksum"] diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index ff26f821b..1d72febf0 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -210,6 +210,7 @@ $(function () { self.serial_serialErrorBehaviour = ko.observable("cancel"); self.serial_triggerOkForM29 = ko.observable(undefined); self.serial_waitForStart = ko.observable(undefined); + self.serial_waitToLoadSdFileList = ko.observable(undefined); self.serial_sendChecksum = ko.observable("print"); self.serial_sendChecksumWithUnknownCommands = ko.observable(undefined); self.serial_unknownCommandsNeedAck = ko.observable(undefined); @@ -392,6 +393,7 @@ $(function () { self.observableCopies = { feature_waitForStart: "serial_waitForStart", + feature_waitToLoadSdFileList: "serial_waitToLoadSdFileList", feature_sendChecksum: "serial_sendChecksum", feature_sdRelativePath: "serial_sdRelativePath", feature_sdAlwaysAvailable: "serial_sdAlwaysAvailable", diff --git a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 index 885b86d25..2a147052a 100644 --- a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 +++ b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 @@ -453,6 +453,12 @@ {{ _('Try checking this if you run into connection timeouts due to your printer taking too long to respond to OctoPrint\'s handshake attempts on connect.') }} +
+ +
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 58d9f269a..af892f55d 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -622,9 +622,12 @@ class MachineCom: self._firmware_detection = settings().getBoolean(["serial", "firmwareDetection"]) self._firmware_info_received = False + self._firmware_capabilities_received = False self._firmware_info = {} self._firmware_capabilities = {} + self._defer_sd_refresh = settings().getBoolean(["serial", "waitToLoadSdFileList"]) + self._temperature_autoreporting = False self._sdstatus_autoreporting = False self._pos_autoreporting = False @@ -725,6 +728,9 @@ class MachineCom: "capabilities": self._pluginManager.get_hooks( "octoprint.comm.protocol.firmware.capabilities" ), + "capability_report": self._pluginManager.get_hooks( + "octoprint.comm.protocol.firmware.capability_report" + ), } self._printer_action_hooks = self._pluginManager.get_hooks( @@ -2004,6 +2010,12 @@ class MachineCom: if not self.isOperational() or self.isBusy(): return + if self._defer_sd_refresh and not self._firmware_capabilities_received: + self._logger.debug( + "Deferring sd file refresh until capability report is processed" + ) + return + if tags is None: tags = set() @@ -2558,6 +2570,33 @@ class MachineCom: ): continue + # wait for the end of the firmware capability report (M115) then notify plugins and refresh sd list if deferred + if ( + self._firmware_capabilities + and not self._firmware_capabilities_received + and not lower_line.startswith("cap:") + ): + self._firmware_capabilities_received = True + + if self._defer_sd_refresh: + # sd list was deferred, refresh it now + self._logger.debug("Performing deferred sd file refresh") + self.refreshSdFiles() + + # notify plugins + for name, hook in self._firmware_info_hooks[ + "capability_report" + ].items(): + try: + hook(self, copy.copy(self._firmware_capabilities)) + except Exception: + self._logger.exception( + "Error processing firmware reported hook {}:".format( + name + ), + extra={"plugin": name}, + ) + ##~~ position report processing if "X:" in line and "Y:" in line and "Z:" in line: parsed = parse_position_line(line) @@ -2707,6 +2746,10 @@ class MachineCom: self._logger.info( "Firmware states that it supports emergency GCODEs to be sent without waiting for an acknowledgement first" ) + elif capability == self.CAPABILITY_EXTENDED_M20 and enabled: + self._logger.info( + "Firmware states that it supports long filenames" + ) # notify plugins for name, hook in self._firmware_info_hooks[ @@ -3605,11 +3648,7 @@ class MachineCom: ) if self._sdAvailable: - self.refreshSdFiles( - tags={ - "trigger:comm.on_connected", - } - ) + self.refreshSdFiles(tags={"trigger:comm.on_connected"}) else: self.initSdCard(tags={"trigger:comm.on_connected"}) From ffdda85c39ae1cfad2211accb40ca44317fc9d45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 28 Sep 2022 13:33:39 +0200 Subject: [PATCH 02/11] =?UTF-8?q?=E2=9C=A8=20Add=20privacy=20policy=20link?= =?UTF-8?q?=20to=20plugins?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit That will allow plugins to link to their privacy policy directy in the repository listing and the plugin overview. As suggested by @AlbertMN 👍 --- docs/plugins/controlproperties.rst | 5 +++++ src/octoprint/plugin/core.py | 16 ++++++++++++++++ src/octoprint/plugins/pluginmanager/__init__.py | 1 + .../templates/pluginmanager_settings.jinja2 | 6 ++++-- 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/docs/plugins/controlproperties.rst b/docs/plugins/controlproperties.rst index b5905fa07..48fdd5b52 100644 --- a/docs/plugins/controlproperties.rst +++ b/docs/plugins/controlproperties.rst @@ -53,6 +53,11 @@ The following properties are recognized: ``__plugin_license__`` License of your plugin, optional, overrides the license specified in ``setup.py`` if provided. +.. _sec-plugins-controlproperties-plugin_privacypolicy: + +``__plugin_privacypolicy__`` + URL of the privacy policy of your plugin, optional. + .. _sec-plugins-controlproperties-plugin_pythoncompat: ``__plugin_pythoncompat__`` diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 411ea6004..0d8fe2246 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -177,6 +177,9 @@ class ControlProperties: attr_license = "__plugin_license__" """ Module attribute from which to retrieve the plugin's license. """ + attr_privacypolicy = "__plugin_privacypolicy__" + """ Module attribute from which to retrieve the plugin's privacy policy URL, if any. """ + attr_pythoncompat = "__plugin_pythoncompat__" """ Module attribute from which to retrieve the plugin's python compatibility string. @@ -617,6 +620,19 @@ class PluginInfo: ControlProperties.attr_license, default=self._license, incl_metadata=True ) + @property + def privacypolicy(self): + """ + Privacy Policy URL of the plugin. Will be taken from the privacy policy attribute of the plugin module + as defined in :attr:`attr_privacypolicy` if available. May be None. + + Returns: + str or None: Privacy Policy URL of the plugin. + """ + return self._get_instance_attribute( + ControlProperties.attr_privacypolicy, default=None, incl_metadata=True + ) + @property def pythoncompat(self): """ diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 9a0dae841..757bc2d6e 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -1998,6 +1998,7 @@ class PluginManagerPlugin( "version": plugin.version, "url": plugin.url, "license": plugin.license, + "privacypolicy": plugin.privacypolicy, "python": plugin.pythoncompat, "bundled": plugin.bundled, "managable": plugin.managable, diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index aaea76ef1..f4572dc67 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -149,12 +149,13 @@
()
{{ _('Homepage') }} + {{ _('Privacy Policy') }}
 
- + Python  
@@ -278,11 +279,12 @@
 
- + From 4c86459c1bb2cd72152ffad37bf5ad05b9159276 Mon Sep 17 00:00:00 2001 From: Kestin Goforth Date: Wed, 28 Sep 2022 08:36:48 -0400 Subject: [PATCH 03/11] =?UTF-8?q?=E2=9C=A8=20Analyze=20non-extruding=20mov?= =?UTF-8?q?es=20and=20notify=20if=20exceeds=20print=20volume=20(#4579)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Track travel moves and notify if exceeds print volume * Implement changes from pr review * Update GcodeAnalysisQueue docstring for travel area * Update docs for GCODE analysis information * Update exceedance messages for translation --- docs/api/datamodel.rst | 44 +++++++ src/octoprint/cli/analysis.py | 14 +- src/octoprint/filemanager/analysis.py | 42 +++++- .../static/js/app/viewmodels/files.js | 120 ++++++++++++------ src/octoprint/util/gcodeInterpreter.py | 82 ++++++++---- 5 files changed, 232 insertions(+), 70 deletions(-) diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index 595c91d0d..0b5033def 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -485,6 +485,50 @@ GCODE analysis information - 0..1 - Float - The minimum Z coordinate of the printed model, in mm + * - ``travelArea`` + - 0..1 + - Object + - Information regarding the bounding box of all moves + * - ``travelArea.maxX`` + - 0..1 + - Float + - The maximum X coordinate of all moves, in mm + * - ``travelArea.maxY`` + - 0..1 + - Float + - The maximum Y coordinate of all moves, in mm + * - ``travelArea.maxZ`` + - 0..1 + - Float + - The maximum Z coordinate of all moves, in mm + * - ``travelArea.minX`` + - 0..1 + - Float + - The minimum X coordinate of all moves, in mm + * - ``travelArea.minY`` + - 0..1 + - Float + - The minimum Y coordinate of all moves, in mm + * - ``travelArea.minZ`` + - 0..1 + - Float + - The minimum Z coordinate of all moves, in mm + * - ``travelDimensions`` + - 0..1 + - Object + - Information regarding the size of the travel area + * - ``travelDimensions.depth`` + - 0..1 + - Float + - The depth of the travel area, in mm + * - ``travelDimensions.height`` + - 0..1 + - Float + - The height of the travel area, in mm + * - ``travelDimensions.width`` + - 0..1 + - Float + - The width of the travel area, in mm .. _sec-api-datamodel-files-ref: diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 297ccb83c..6ada2c807 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -13,7 +13,7 @@ click.disable_unicode_literals_warning = True dimensions = ("depth", "height", "width") -printing_area = ("maxX", "maxY", "maxZ", "minX", "minY", "minZ") +area = ("maxX", "maxY", "maxZ", "minX", "minY", "minZ") def empty_result(result): @@ -37,15 +37,21 @@ def validate_result(result): if "dimensions" not in result or not validate_dict(result["dimensions"], dimensions): return False + if "travel_dimensions" not in result or not validate_dict( + result["travel_dimensions"], dimensions + ): + return False + if "extrusion_length" not in result or not validate_list(result["extrusion_length"]): return False if "extrusion_volume" not in result or not validate_list(result["extrusion_volume"]): return False - if "printing_area" not in result or not validate_dict( - result["printing_area"], printing_area - ): + if "printing_area" not in result or not validate_dict(result["printing_area"], area): + return False + + if "travel_area" not in result or not validate_dict(result["travel_area"], area): return False if "total_time" not in result or invalid_float(result["total_time"]): diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index b6c01de93..6eea16c47 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -27,7 +27,16 @@ EMPTY_RESULT = { "minZ": 0, "maxZ": 0, }, + "travelArea": { + "minX": 0, + "maxX": 0, + "minY": 0, + "maxY": 0, + "minZ": 0, + "maxZ": 0, + }, "dimensions": {"width": 0, "height": 0, "depth": 0}, + "travelDimensions": {"width": 0, "height": 0, "depth": 0}, "filament": {}, } @@ -390,6 +399,28 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): * Depth of the printed model along the Y axis, in mm - * ``dimensions.height`` * Height of the printed model along the Z axis, in mm + - * ``travelArea`` + * Bounding box of all machine movements (minimum and maximum coordinates) + - * ``travelArea.minX`` + * Minimum X coordinate of the machine movement + - * ``travelArea.maxX`` + * Maximum X coordinate of the machine movement + - * ``travelArea.minY`` + * Minimum Y coordinate of the machine movement + - * ``travelArea.maxY`` + * Maximum Y coordinate of the machine movement + - * ``travelArea.minZ`` + * Minimum Z coordinate of the machine movement + - * ``travelArea.maxZ`` + * Maximum Z coordinate of the machine movement + - * ``travelDimensions`` + * Dimensions of the travel area in X, Y, Z + - * ``travelDimensions.width`` + * Width of the travel area along the X axis, in mm + - * ``travelDimensions.depth`` + * Depth of the travel area along the Y axis, in mm + - * ``travelDimensions.height`` + * Height of the travel area along the Z axis, in mm """ def __init__(self, finished_callback): @@ -406,7 +437,14 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): if self._current.analysis and all( map( lambda x: x in self._current.analysis, - ("printingArea", "dimensions", "estimatedPrintTime", "filament"), + ( + "printingArea", + "dimensions", + "travelArea", + "travelDimensions", + "estimatedPrintTime", + "filament", + ), ) ): return self._current.analysis @@ -499,6 +537,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): result["printingArea"] = analysis["printing_area"] result["dimensions"] = analysis["dimensions"] + result["travelArea"] = analysis["travel_area"] + result["travelDimensions"] = analysis["travel_dimensions"] if analysis["total_time"]: result["estimatedPrintTime"] = analysis["total_time"] * 60 if analysis["extrusion_length"]: diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index e6f22a467..925c57d3c 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -1135,6 +1135,11 @@ $(function () { return true; } + var travelArea = data["gcodeAnalysis"]["travelArea"]; + if (!travelArea) { + return true; + } + var printerProfile = self.printerProfiles.currentProfileData(); if (!printerProfile) { return true; @@ -1173,46 +1178,72 @@ $(function () { } } - // model not within bounds, we need to prepare a warning - var warning = - "

" + - _.sprintf( - gettext( - "Object in %(name)s exceeds the print volume of the currently selected printer profile, be careful when printing this." - ), - {name: _.escape(data.name)} - ) + - "

"; var info = ""; + var objectFits = true; + var travelFits = true; - var formatData = { - profile: boundaries, - object: printingArea - }; - - // find exceeded dimensions - if ( - printingArea["minX"] < boundaries["minX"] || - printingArea["maxX"] > boundaries["maxX"] - ) { - info += gettext("Object exceeds print volume in width.
"); - } - if ( - printingArea["minY"] < boundaries["minY"] || - printingArea["maxY"] > boundaries["maxY"] - ) { - info += gettext("Object exceeds print volume in depth.
"); - } - if ( - printingArea["minZ"] < boundaries["minZ"] || - printingArea["maxZ"] > boundaries["maxZ"] - ) { - info += gettext("Object exceeds print volume in height.
"); + function _area_exceeds_boundaries(ax, area) { + return ( + area["min" + ax] < boundaries["min" + ax] || + area["max" + ax] > boundaries["max" + ax] + ); } - //warn user - if (info !== "") { + function _exceed_warning(culprit, dimension) { + return _.sprintf( + gettext("%(culprit)s exceeds print volume in %(dimension)s.
"), + {culprit: culprit, dimension: dimension} + ); + } + + // check if printing area exceeds boundaries + if (_area_exceeds_boundaries("X", printingArea)) { + info += _exceed_warning(gettext("Object"), gettext("width")); + objectFits = false; + } + if (_area_exceeds_boundaries("Y", printingArea)) { + info += _exceed_warning(gettext("Object"), gettext("depth")); + objectFits = false; + } + if (_area_exceeds_boundaries("Z", printingArea)) { + info += _exceed_warning(gettext("Object"), gettext("height")); + objectFits = false; + } + + // check if travel area exceeds boundaries + if (_area_exceeds_boundaries("X", travelArea)) { + info += _exceed_warning(gettext("Travel"), gettext("width")); + travelFits = false; + } + if (_area_exceeds_boundaries("Y", travelArea)) { + info += _exceed_warning(gettext("Travel"), gettext("depth")); + travelFits = false; + } + if (_area_exceeds_boundaries("Z", travelArea)) { + info += _exceed_warning(gettext("Travel"), gettext("height")); + travelFits = false; + } + + if (travelFits && objectFits) { + return true; + } else { + // model not within bounds, we need to prepare a warning if (notify) { + var formatData = { + name: _.escape(data.name), + profile: boundaries, + object: printingArea, + travel: travelArea, + culprit: !objectFits ? "Object" : "Travel area" + }; + + info += _.sprintf( + gettext( + "Travel area: (%(travel.minX).2f, %(travel.minY).2f, %(travel.minZ).2f) × (%(travel.maxX).2f, %(travel.maxY).2f, %(travel.maxZ).2f)" + ), + formatData + ); + info += "
"; info += _.sprintf( gettext( "Object's bounding box: (%(object.minX).2f, %(object.minY).2f, %(object.minZ).2f) × (%(object.maxX).2f, %(object.maxY).2f, %(object.maxZ).2f)" @@ -1227,21 +1258,34 @@ $(function () { formatData ); + // prepare a warning message + var warning = + "

" + + _.sprintf( + gettext( + "%(culprit)s in %(name)s exceeds the print volume of the currently selected printer profile, be careful when printing this." + ), + formatData + ) + + "

"; + warning += pnotifyAdditionalInfo(info); warning += '

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

'; + //warn user new PNotify({ - title: gettext("Object doesn't fit print volume"), + title: _.sprintf( + gettext("%(culprit)s exceeds print volume"), + formatData + ), text: warning, type: "warning", hide: false }); } return false; - } else { - return true; } }; diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index 3437b5c63..8f0773981 100644 --- a/src/octoprint/util/gcodeInterpreter.py +++ b/src/octoprint/util/gcodeInterpreter.py @@ -194,6 +194,22 @@ class MinMax3D: setattr(result, c, value) return result + @property + def dimensions(self): + size = self.size + return {"width": size.x, "depth": size.y, "height": size.z} + + @property + def area(self): + return { + "minX": None if math.isinf(self.min.x) else self.min.x, + "minY": None if math.isinf(self.min.y) else self.min.y, + "minZ": None if math.isinf(self.min.z) else self.min.z, + "maxX": None if math.isinf(self.max.x) else self.max.x, + "maxY": None if math.isinf(self.max.y) else self.max.y, + "maxZ": None if math.isinf(self.max.z) else self.max.z, + } + class AnalysisAborted(Exception): def __init__(self, reenqueue=True, *args, **kwargs): @@ -217,7 +233,8 @@ class gcode: self._abort = False self._reenqueue = True self._filamentDiameter = 0 - self._minMax = MinMax3D() + self._print_minMax = MinMax3D() + self._travel_minMax = MinMax3D() self._progress_callback = progress_callback self._incl_layers = incl_layers @@ -249,19 +266,19 @@ class gcode: @property def dimensions(self): - size = self._minMax.size - return {"width": size.x, "depth": size.y, "height": size.z} + return self._print_minMax.dimensions + + @property + def travel_dimensions(self): + return self._travel_minMax.dimensions @property def printing_area(self): - return { - "minX": None if math.isinf(self._minMax.min.x) else self._minMax.min.x, - "minY": None if math.isinf(self._minMax.min.y) else self._minMax.min.y, - "minZ": None if math.isinf(self._minMax.min.z) else self._minMax.min.z, - "maxX": None if math.isinf(self._minMax.max.x) else self._minMax.max.x, - "maxY": None if math.isinf(self._minMax.max.y) else self._minMax.max.y, - "maxZ": None if math.isinf(self._minMax.max.z) else self._minMax.max.z, - } + return self._print_minMax.area + + @property + def travel_area(self): + return self._travel_minMax.area @property def layers(self): @@ -291,7 +308,7 @@ class gcode: g90_extruder=False, bed_z=0.0, ): - self._minMax.min.z = bed_z + self._print_minMax.min.z = self._travel_minMax.min.z = bed_z if os.path.isfile(filename): self.filename = filename self._fileSize = os.stat(filename).st_size @@ -463,12 +480,6 @@ class gcode: else: e -= currentE[currentExtruder] - # If move with extrusion, calculate new min/max coordinates of model - if e > 0 and move: - # extrusion and move -> oldPos & pos relevant for print area & dimensions - self._minMax.record(oldPos) - self._minMax.record(pos) - totalExtrusion[currentExtruder] += e currentE[currentExtruder] += e maxExtrusion[currentExtruder] = max( @@ -484,6 +495,15 @@ class gcode: else: e = 0 + # If move, calculate new min/max coordinates + if move: + self._travel_minMax.record(oldPos) + self._travel_minMax.record(pos) + if e > 0: + # store as print move if extrusion is > 0 + self._print_minMax.record(oldPos) + self._print_minMax.record(pos) + # move time in x, y, z, will be 0 if no movement happened moveTimeXYZ = abs((oldPos - pos).length / feedrate) @@ -567,15 +587,6 @@ class gcode: else: e -= currentE[currentExtruder] - # If move with extrusion, calculate new min/max coordinates of model - if e > 0 and move: - # extrusion and move -> oldPos & pos relevant for print area & dimensions - self._minMax.record(oldPos) - self._minMax.record(pos) - self._addArcMinMax( - self._minMax, startAngle, endAngle, centerArc, r - ) - totalExtrusion[currentExtruder] += e currentE[currentExtruder] += e maxExtrusion[currentExtruder] = max( @@ -591,6 +602,21 @@ class gcode: else: e = 0 + # If move, calculate new min/max coordinates + if move: + self._travel_minMax.record(oldPos) + self._travel_minMax.record(pos) + self._addArcMinMax( + self._travel_minMax, startAngle, endAngle, centerArc, r + ) + if e > 0: + # store as print move if extrusion is > 0 + self._print_minMax.record(oldPos) + self._print_minMax.record(pos) + self._addArcMinMax( + self._print_minMax, startAngle, endAngle, centerArc, r + ) + # calculate 3d arc length arcLengthXYZ = math.sqrt((oldPos.z - pos.z) ** 2 + (arcAngle * r) ** 2) @@ -806,6 +832,8 @@ class gcode: "extrusion_volume": self.extrusionVolume, "dimensions": self.dimensions, "printing_area": self.printing_area, + "travel_dimensions": self.travel_dimensions, + "travel_area": self.travel_area, } if self._incl_layers: result["layers"] = self.layers From e74f87b07ccad219c5b00faa3bfab99c1311bd6c Mon Sep 17 00:00:00 2001 From: Federico Nembrini <25205086+FedericoNembrini@users.noreply.github.com> Date: Wed, 28 Sep 2022 14:51:59 +0200 Subject: [PATCH 04/11] =?UTF-8?q?=E2=9C=A8=20SWU:=20Add=20button=20to=20cl?= =?UTF-8?q?ear=20the=20Github=20Access=20Token=20(#4609)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add github token clear checkbox in software update plugin * Replace checkbox with action button for github access token removal in software update plugin * Fix action button title --- .../static/js/softwareupdate.js | 23 +++++++++++++++++++ .../templates/snippets/githubToken.jinja2 | 16 ++++++++----- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index 13dcbd37e..aba2cf5b7 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -241,6 +241,29 @@ $(function () { self.configurationDialog.modal(); }; + self.deleteGithubTokenApiKey = function () { + var data = { + plugins: { + softwareupdate: { + credentials: { + github: undefined + } + } + } + }; + + self.settings.saveData(data, { + success: function () { + self.performCheck(); + }, + complete: function () { + self.config_githubToken(""); + self.config_githubTokenSet(false); + }, + sending: true + }); + }; + self.savePluginSettings = function (viewModel, event) { var target = $(event.target); target.prepend(' '); diff --git a/src/octoprint/plugins/softwareupdate/templates/snippets/githubToken.jinja2 b/src/octoprint/plugins/softwareupdate/templates/snippets/githubToken.jinja2 index 133832211..2338ede6e 100644 --- a/src/octoprint/plugins/softwareupdate/templates/snippets/githubToken.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/snippets/githubToken.jinja2 @@ -1,12 +1,16 @@
- - - - - - +
+ + + + + + + +
{{ _('Set this if you keep running into rate limiting issues. See here for how to obtain a token.', url="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token") }} + {{ _('Please note that the deletion of the access token is applied immediately, without having to "Confirm" first.') }}
From bbd06a0212d3a0dfd300555ffd6387a5e8d36173 Mon Sep 17 00:00:00 2001 From: Charlie Powell <31997505+cp2004@users.noreply.github.com> Date: Wed, 28 Sep 2022 13:58:25 +0100 Subject: [PATCH 05/11] :lipstick: Add tooltip to disabled plugin manager install (#4620) * :lipstick: Add tooltip to disabled plugin manager install Closes #4611 * :globe_with_meridians: Allow translation of disable string --- .../pluginmanager/templates/pluginmanager_settings.jinja2 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index f4572dc67..49bcf6705 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -267,7 +267,7 @@
From b133eea89448a8e3ce9b99c3cfafac4885fbfb4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arkadiusz=20Mi=C5=9Bkiewicz?= Date: Wed, 28 Sep 2022 15:03:47 +0200 Subject: [PATCH 06/11] =?UTF-8?q?=F0=9F=90=9B=20Initialize=20exception=20w?= =?UTF-8?q?ith=20provided=20message=20(#4625)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit So we get actual message when exception happens like: "octoprint.filemanager.storage.StorageError: /tmp/test is not a valid directory" --- src/octoprint/filemanager/storage.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index ef64fc954..e4ae04bdf 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -445,8 +445,7 @@ class StorageError(Exception): NOT_EMPTY = "not_empty" def __init__(self, message, code=None, cause=None): - BaseException.__init__(self) - self.message = message + Exception.__init__(self, message) self.cause = cause if code is None: From 05ea0b29a475495e1add0c7781fcb3e2e79ca51a Mon Sep 17 00:00:00 2001 From: Charlie Powell <31997505+cp2004@users.noreply.github.com> Date: Wed, 28 Sep 2022 14:07:24 +0100 Subject: [PATCH 07/11] :bug: Fix werkzeug 2.1 compatibility and remove redundant code (#4630) See #4629 --- .../plugins/corewizard/subwizards.py | 2 +- src/octoprint/server/api/__init__.py | 2 +- src/octoprint/server/api/access.py | 26 ------------------- src/octoprint/server/api/printer.py | 6 ----- src/octoprint/server/api/printer_profiles.py | 13 +--------- src/octoprint/server/api/settings.py | 5 +--- src/octoprint/server/api/slicing.py | 12 +-------- src/octoprint/server/util/flask.py | 9 +------ 8 files changed, 6 insertions(+), 69 deletions(-) diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py index 2a2e04fac..42b9ee04e 100644 --- a/src/octoprint/plugins/corewizard/subwizards.py +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -85,7 +85,7 @@ class AclSubwizard: ): abort(404) - data = request.get_json() + data = request.get_json(silent=True) if data is None: data = request.values diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 14ef6e475..c4a306e9a 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -291,7 +291,7 @@ def serverStatus(): error_message="You have made too many failed login attempts. Please try again later.", ) def login(): - data = request.get_json() + data = request.get_json(silent=True) if not data: data = request.values diff --git a/src/octoprint/server/api/access.py b/src/octoprint/server/api/access.py index e8e568de3..53d0c99eb 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -34,9 +34,6 @@ def get_groups(): @no_firstrun_access @Permissions.ADMIN.require(403) def add_group(): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - data = request.get_json() if "key" not in data: @@ -82,9 +79,6 @@ def get_group(key): @no_firstrun_access @Permissions.ADMIN.require(403) def update_group(key): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - data = request.get_json() try: @@ -138,12 +132,7 @@ def get_users(): @no_firstrun_access @Permissions.ADMIN.require(403) def add_user(): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - data = request.get_json() - if data is None: - abort(400, description="Malformed JSON body in request") if "name" not in data: abort(400, description="name is missing") @@ -192,14 +181,8 @@ def get_user(username): def update_user(username): user = userManager.find_user(username) if user is not None: - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - data = request.get_json() - if data is None: - abort(400, description="Malformed JSON body in request") - # change groups if "groups" in data: groups = data["groups"] @@ -246,14 +229,8 @@ def change_password_for_user(username): or current_user.has_permission(Permissions.ADMIN) ) ): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - data = request.get_json() - if data is None: - abort(400, description="Malformed JSON body in request") - if "password" not in data or not data["password"]: abort(400, description="new password is missing") @@ -308,9 +285,6 @@ def change_settings_for_user(username): data = request.get_json() - if data is None: - abort(400, description="Malformed JSON body in request") - try: userManager.change_user_settings(username, data) return jsonify(SUCCESS) diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index d92f7bb93..25a8fca0b 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -396,14 +396,8 @@ def printerCommand(): if not printer.is_operational(): abort(409, description="Printer is not operational") - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content type JSON") - data = request.get_json() - if data is None: - abort(400, description="Malformed JSON body in request") - if "command" in data and "commands" in data: abort(400, description="'command' and 'commands' are mutually exclusive") elif ("command" in data or "commands" in data) and "script" in data: diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py index 55644eb45..edbbe2c2b 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -54,13 +54,7 @@ def printerProfilesList(): @no_firstrun_access @Permissions.SETTINGS.require(403) def printerProfilesAdd(): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - - json_data = request.get_json() - - if json_data is None: - abort(400, description="Malformed JSON body in request") + json_data = request.get_json() # Werkzeug should return 400 if invalid JSON if "profile" not in json_data: abort(400, description="profile is missing") @@ -136,12 +130,7 @@ def printerProfilesDelete(identifier): @no_firstrun_access @Permissions.SETTINGS.require(403) def printerProfilesUpdate(identifier): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - json_data = request.get_json() - if json_data is None: - abort(400, description="Malformed JSON body in request") if "profile" not in json_data: abort(400, description="profile missing") diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 31b9ef562..625b2cafd 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -387,11 +387,8 @@ def _get_plugin_settings(): @no_firstrun_access @Permissions.SETTINGS.require(403) def setSettings(): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - data = request.get_json() - if data is None or not isinstance(data, dict): + if not isinstance(data, dict): abort(400, description="Malformed JSON body in request") response = _saveSettings(data) diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index f2dd80b42..ec648f80d 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -160,12 +160,7 @@ def slicingGetSlicerProfile(slicer, name): @no_firstrun_access @Permissions.SETTINGS.require(403) def slicingAddSlicerProfile(slicer, name): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") - json_data = request.get_json() - if json_data is None: - abort(400, description="Malformed JSON body in request") data = {} display_name = None @@ -199,8 +194,7 @@ def slicingAddSlicerProfile(slicer, name): @no_firstrun_access @Permissions.SETTINGS.require(403) def slicingPatchSlicerProfile(slicer, name): - if "application/json" not in request.headers["Content-Type"]: - abort(400, description="Expected content-type JSON") + json_data = request.get_json() try: profile = slicingManager.load_profile(slicer, name, require_configured=False) @@ -209,10 +203,6 @@ def slicingPatchSlicerProfile(slicer, name): except UnknownProfile: return abort(404) - json_data = request.get_json() - if json_data is None: - abort(400, description="Malformed JSON body in request") - data = {} display_name = None description = None diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 4673053da..132663df5 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1664,15 +1664,8 @@ def get_remote_address(request): def get_json_command_from_request(request, valid_commands): - content_type = request.headers.get("Content-Type", None) - if content_type is None or "application/json" not in content_type: - flask.abort(400, description="Expected content-type JSON") - data = request.get_json() - if data is None: - flask.abort( - 400, description="Malformed JSON body or wrong content-type in request" - ) + if "command" not in data or data["command"] not in valid_commands: flask.abort(400, description="command is invalid") From efdf127df85ae4b0fd266f101c467a2a4d546a6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arkadiusz=20Mi=C5=9Bkiewicz?= Date: Wed, 28 Sep 2022 15:22:35 +0200 Subject: [PATCH 08/11] =?UTF-8?q?=E2=9C=A8=20Correctly=20handle=20Marlin's?= =?UTF-8?q?=20"No=20media"=20as=20"sd=20card=20released"=20(#4635)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commands like M20 return "No media" on Marlin 2.1.x with sd card not initialized. Send: M21 Recv: echo:SD card ok Recv: ok P15 B3 Send: M22 Recv: ok P15 B3 Send: M20 Recv: echo:No media Recv: ok P15 B3 Send: M115 Recv: FIRMWARE_NAME:Marlin bugfix-2.1.x (Aug 29 2022 12:04:58) SOURCE_CODE_URL:github.com/MarlinFirmware/Marlin PROTOCOL_VERSION:1.0 ... --- src/octoprint/util/comm.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index af892f55d..1efba7257 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -2942,6 +2942,7 @@ class MachineCom: if ( "SD init fail" in line or "volume.init failed" in line + or "No media" in line or "openRoot failed" in line or "SD Card unmounted" in line or "SD card released" in line From 4625e6aa7b91489a0772ea22e700a1910f318659 Mon Sep 17 00:00:00 2001 From: Josef-MrBeam <81746291+Josef-MrBeam@users.noreply.github.com> Date: Wed, 28 Sep 2022 15:23:40 +0200 Subject: [PATCH 09/11] =?UTF-8?q?=F0=9F=90=9B=20Fix=20bug=20in=20slicing?= =?UTF-8?q?=20progress=20reporting=20to=20UI=20(#4636)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit in the event handler onSlicingStarted the uploadProgressPercentage was given the parameter perecntage, but this was not know, so it will throw an error. As this is the start of the slicing the correct value should be 0 --- src/octoprint/static/js/app/viewmodels/files.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 925c57d3c..a0c33d85e 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -1464,7 +1464,7 @@ $(function () { self.uploadProgress.addClass("progress-striped").addClass("active"); self.uploadProgressBar.css("width", "100%"); if (payload.progressAvailable) { - self.uploadProgressPercentage(percentage); + self.uploadProgressPercentage(0); self.uploadProgressText( _.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}) ); From 776c24da5b0eb3ae503c99365e57efbaa40a9060 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 28 Sep 2022 16:28:02 +0200 Subject: [PATCH 10/11] =?UTF-8?q?=F0=9F=90=9B=20PMGR:=20Fix=20repo=20listi?= =?UTF-8?q?ng?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/plugins/pluginmanager/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 757bc2d6e..1063aa5d1 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -66,6 +66,8 @@ def map_repository_entry(entry): if "follow_dependency_links" not in result: result["follow_dependency_links"] = False + if "privacypolicy" not in result: + result["privacypolicy"] = False result["is_compatible"] = {"octoprint": True, "os": True, "python": True} From 9303aca6ca26eb1f645edc882cb54742b1a14914 Mon Sep 17 00:00:00 2001 From: Charlie Powell <31997505+cp2004@users.noreply.github.com> Date: Wed, 28 Sep 2022 15:40:58 +0100 Subject: [PATCH 11/11] =?UTF-8?q?=E2=9C=A8=20Enable=20multiple=20file=20up?= =?UTF-8?q?loads=20(#4633)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * :construction: Handle multiple uploads better Start for support. Has some TODOs and outstanding issues to tackle still, including the file upload/overwrite/rename/cancel dialog * :construction: Handle failed multiple uploads better Show target filename when showing errors Only refresh the files list if there was at least one successful file upload in the batch * :construction: Queue up file exists confirmations for multiple uploads See #4300 * :construction: Scroll to only the last uploaded file * :construction: Fix scrolling to the file index starts at 0, length 1 Co-authored-by: Gina Häußge --- .../static/js/app/viewmodels/files.js | 252 ++++++++++-------- src/octoprint/templates/sidebar/files.jinja2 | 2 +- 2 files changed, 146 insertions(+), 108 deletions(-) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index a0c33d85e..6b40e0e9e 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -402,7 +402,7 @@ $(function () { }; self._otherRequestInProgress = undefined; - self._focus = undefined; + self._filesToFocus = []; self._switchToPath = undefined; self.requestData = function (params) { if (!self.loginState.hasPermission(self.access.permissions.FILES_LIST)) { @@ -435,7 +435,7 @@ $(function () { } } - self._focus = self._focus || focus; + self._filesToFocus = self._filesToFocus || focus; self._switchToPath = self._switchToPath || switchToPath; if (self._otherRequestInProgress !== undefined) { @@ -446,7 +446,7 @@ $(function () { .list(true, force) .done(function (response) { self.fromResponse(response, { - focus: self._focus, + focus: self._filesToFocus, switchToPath: self._switchToPath }); }) @@ -456,13 +456,13 @@ $(function () { }) .always(function () { self._otherRequestInProgress = undefined; - self._focus = undefined; + self._filesToFocus = []; self._switchToPath = undefined; })); }; self.fromResponse = function (response, params) { - var focus = undefined; + var focus = []; var switchToPath; if (_.isObject(params)) { @@ -470,7 +470,7 @@ $(function () { switchToPath = params.switchToPath || undefined; } else if (arguments.length > 1) { log.warn( - "FilesViewModel.requestData called with old argument list. That is deprecated, please use parameter object instead." + "FilesViewModel.fromResponse called with old argument list. That is deprecated, please use parameter object instead." ); if (arguments.length > 2) { focus = {location: arguments[2], path: arguments[1]}; @@ -530,27 +530,31 @@ $(function () { self.changeFolderByPath(switchToPath); } - if (focus) { - // got a file to scroll to - var entryElement = self.getEntryElement({ - path: focus.path, - origin: focus.location - }); - if (entryElement) { - // scroll to uploaded element - self.listElement.scrollTop(entryElement.offsetTop); - - // highlight uploaded element - var element = $(entryElement); - element.on( - "webkitAnimationEnd oanimationend msAnimationEnd animationend", - function (e) { - // remove highlight class again - element.removeClass("highlight"); + if (focus.length) { + _.each(focus, function (focusItem, index) { + // got a file to scroll to + var entryElement = self.getEntryElement({ + path: focusItem.path, + origin: focusItem.location + }); + if (entryElement) { + // scroll to uploaded element + if (index + 1 === focus.length) { + self.listElement.scrollTop(entryElement.offsetTop); } - ); - element.addClass("highlight"); - } + + // highlight uploaded element + var element = $(entryElement); + element.on( + "webkitAnimationEnd oanimationend msAnimationEnd animationend", + function (e) { + // remove highlight class again + element.removeClass("highlight"); + } + ); + element.addClass("highlight"); + } + }); } if (response.free !== undefined) { @@ -1610,12 +1614,13 @@ $(function () { url: url, dataType: "json", dropZone: enable ? drop : null, + sequentialUploads: true, drop: function (e, data) {}, add: self._handleUploadAdd, submit: self._handleUploadStart, done: self._handleUploadDone, fail: self._handleUploadFail, - always: self._handleUploadAlways, + stop: self._handleUploadStop, progressall: self._handleUploadProgress }); }; @@ -1644,6 +1649,88 @@ $(function () { } }; + self._uploadExistsQueue = []; // Files will be in this queue if their test fails and something needs to be done + self._uploadExistsOpen = false; + + self._processUploadQueue = function () { + if (!self._uploadExistsQueue.length > 0 || self._uploadExistsOpen) return; + + const hideAndSubmit = function (data) { + self.uploadExistsDialog.modal("hide"); + self._uploadExistsOpen = false; + data.submit(); + // Recursively move on to process the queue every time a dialog is closed + if (self._uploadExistsQueue.length > 0) { + self._processUploadQueue(); + } + }; + + // Collect an item from the queue that needs an overwrite dialog + const {data, response, path, fileSizeTooBig} = + self._uploadExistsQueue.shift(); + const file = data.files[0]; + + const formData = {}; + if (path !== "") { + formData.path = path; + } + + // Build and show a dialog + self._uploadExistsOpen = true; + + $("h3", self.uploadExistsDialog).text( + _.sprintf(gettext("File already exists: %(name)s"), { + name: file.name + }) + ); + $("p, form", self.uploadExistsDialog).toggle(!fileSizeTooBig); + $("span", self.uploadExistsDialog).toggle(fileSizeTooBig); + $("input", self.uploadExistsDialog) + .val("") + .prop("placeholder", response.suggestion); + $("a.upload-rename", self.uploadExistsDialog) + .toggle(!fileSizeTooBig) + .prop("disabled", false) + .off("click") + .on("click", function () { + var newName = $("input", self.uploadExistsDialog).val(); + if (newName === "") newName = response.suggestion; + + OctoPrint.files.exists("local", path, newName).done(function (r) { + if (r.exists) { + $(".control-group", self.uploadExistsDialog).addClass( + "error" + ); + $(".help-block", self.uploadExistsDialog).show(); + } else { + $(".control-group", self.uploadExistsDialog).removeClass( + "error" + ); + $(".help-block", self.uploadExistsDialog).hide(); + + formData.filename = newName; + formData.noOverwrite = true; + data.formData = formData; + + hideAndSubmit(data); + } + }); + }); + if (self.loginState.hasPermission(self.access.permissions.FILES_DELETE)) { + $("a.upload-overwrite", self.uploadExistsDialog) + .off("click") + .show() + .on("click", function () { + data.formData = formData; + hideAndSubmit(data); + }); + } else { + $("a.upload-overwrite", self.uploadExistsDialog).hide(); + } + + self.uploadExistsDialog.modal("show"); + }; + self._handleUploadAdd = function (e, data) { var file = data.files[0]; var path = self.currentPath(); @@ -1659,73 +1746,15 @@ $(function () { .exists("local", path, file.name) .done(function (response) { if (response.exists) { - $("h3", self.uploadExistsDialog).text( - _.sprintf(gettext("File already exists: %(name)s"), { - name: file.name - }) - ); - $("p, form", self.uploadExistsDialog).toggle(!fileSizeTooBig); - $("span", self.uploadExistsDialog).toggle(fileSizeTooBig); - $("input", self.uploadExistsDialog).val(response.suggestion); - $("a.upload-rename", self.uploadExistsDialog) - .toggle(!fileSizeTooBig) - .prop("disabled", false) - .off("click") - .on("click", function () { - var newName = $( - "input", - self.uploadExistsDialog - ).val(); - - OctoPrint.files - .exists("local", path, newName) - .done(function (r) { - if (r.exists) { - $( - ".control-group", - self.uploadExistsDialog - ).addClass("error"); - $( - ".help-block", - self.uploadExistsDialog - ).show(); - } else { - $( - ".control-group", - self.uploadExistsDialog - ).removeClass("error"); - $( - ".help-block", - self.uploadExistsDialog - ).hide(); - - self.uploadExistsDialog.modal("hide"); - - formData.filename = newName; - formData.noOverwrite = true; - data.formData = formData; - - data.submit(); - } - }); - }); - if ( - self.loginState.hasPermission( - self.access.permissions.FILES_DELETE - ) - ) { - $("a.upload-overwrite", self.uploadExistsDialog) - .off("click") - .show() - .on("click", function () { - self.uploadExistsDialog.modal("hide"); - data.formData = formData; - data.submit(); - }); - } else { - $("a.upload-overwrite", self.uploadExistsDialog).hide(); - } - self.uploadExistsDialog.modal("show"); + const queueEntry = { + data, + response, + path, + fileSizeTooBig + }; + self._uploadExistsQueue.push(queueEntry); + // Start processing queue - if already processing, this will do nothing + self._processUploadQueue(); } else { data.formData = formData; data.submit(); @@ -1770,32 +1799,46 @@ $(function () { }; self._handleUploadDone = function (e, data) { - self._setProgressBar(100, gettext("Refreshing list ..."), true); - var focus = undefined; if (data.result.files.hasOwnProperty("sdcard")) { focus = {location: "sdcard", path: data.result.files.sdcard.path}; } else if (data.result.files.hasOwnProperty("local")) { focus = {location: "local", path: data.result.files.local.path}; } - self.requestData({focus: focus}).done(function () { - if (data.result.done) { - self._setProgressBar(0, "", false); - } - }); + + if (focus) { + self._filesToFocus.push(focus); + } if (focus && _.endsWith(focus.path.toLowerCase(), ".stl")) { self.slicing.show(focus.location, focus.path); } }; + self._handleUploadStop = function (e, data) { + var reset = function () { + self.ignoreUpdatedFilesEvent = false; + self._setProgressBar(0, "", false); + }; + + if (self._filesToFocus.length > 0) { + // Only refresh the list if there were files uploaded successfully + self._setProgressBar(100, gettext("Refreshing list ..."), true); + self.requestData({focus: self._filesToFocus}).always(function () { + reset(); + }); + } else { + reset(); + } + }; + self._handleUploadFail = function (e, data) { var extensions = _.map(SUPPORTED_EXTENSIONS, function (extension) { return extension.toLowerCase(); }).sort(); extensions = extensions.join(", "); - var error = "

"; + var error = "

" + _.escape(data.files[0].name) + "

"; switch (data.jqXHR.status) { case 409: // already printing or otherwise busy @@ -1840,11 +1883,6 @@ $(function () { type: "error", hide: false }); - self._setProgressBar(0, "", false); - }; - - self._handleUploadAlways = function (e, data) { - self.ignoreUpdatedFilesEvent = false; }; self._handleUploadProgress = function (e, data) { diff --git a/src/octoprint/templates/sidebar/files.jinja2 b/src/octoprint/templates/sidebar/files.jinja2 index 944737eb0..3b300d238 100644 --- a/src/octoprint/templates/sidebar/files.jinja2 +++ b/src/octoprint/templates/sidebar/files.jinja2 @@ -67,7 +67,7 @@ {{ _('Upload') }} - +