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/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/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/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/cli/analysis.py b/src/octoprint/cli/analysis.py index 617663b84..1bd3c63bc 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/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: 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/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/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 9a0dae841..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} @@ -1998,6 +2000,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..49bcf6705 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  
@@ -266,7 +267,7 @@
@@ -278,11 +279,12 @@
 
- + 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.') }}
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/__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 7ed561d12..b68bd4150 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -212,6 +212,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( @@ -385,11 +386,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) @@ -817,6 +815,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/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 d2b41ef5f..b14d84777 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1667,15 +1667,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") diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index e6f22a467..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) { @@ -1135,6 +1139,11 @@ $(function () { return true; } + var travelArea = data["gcodeAnalysis"]["travelArea"]; + if (!travelArea) { + return true; + } + var printerProfile = self.printerProfiles.currentProfileData(); if (!printerProfile) { return true; @@ -1173,46 +1182,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 +1262,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; } }; @@ -1420,7 +1468,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}) ); @@ -1566,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 }); }; @@ -1600,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(); @@ -1615,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(); @@ -1726,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 @@ -1796,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/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 1762d5b74..a3e628637 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -209,6 +209,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); @@ -391,6 +392,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/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') }} - + diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 24fa846d7..d9d00773a 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -619,9 +619,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 @@ -722,6 +725,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( @@ -2001,6 +2007,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() @@ -2555,6 +2567,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) @@ -2704,6 +2743,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[ @@ -2896,6 +2939,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 @@ -3602,11 +3646,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"}) diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index 46dc42cfe..7d3bd2dff 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