- {{ _('Take note that all plugin management functionality is disabled while your printer is printing or paused.') }}
+ {{ _('Take note that most plugin management functionality is disabled while your printer is printing or paused.') }}
From 8f3808889363b82deb9baeba00001477a0349eaa Mon Sep 17 00:00:00 2001
From: JoveToo
Date: Thu, 20 Oct 2022 13:21:30 +0200
Subject: [PATCH 4/4] =?UTF-8?q?=E2=9A=A1=20GCodeViewer:=20Async=20download?=
=?UTF-8?q?=20(#4559)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* Initial version. Seems tp works as intended except for skipUntil
* typo
* skipUntilThis support
* skipUntil should also be skipped if it is ""
* Update src/octoprint/plugins/gcodeviewer/__init__.py
Co-authored-by: Gina Häußge
* Apply requested changes.
* Rename symbols for readability
Co-authored-by: Gina Häußge
---
src/octoprint/plugins/gcodeviewer/__init__.py | 29 +++++
.../gcodeviewer/static/js/gcodeviewer.js | 75 ++++-------
.../gcodeviewer/static/js/viewer/reader.js | 25 +---
.../gcodeviewer/static/js/viewer/ui.js | 6 +-
.../gcodeviewer/static/js/viewer/worker.js | 118 +++++++++++++++---
.../templates/gcodeviewer_settings.jinja2 | 3 -
src/octoprint/static/js/app/client/files.js | 8 ++
7 files changed, 175 insertions(+), 89 deletions(-)
diff --git a/src/octoprint/plugins/gcodeviewer/__init__.py b/src/octoprint/plugins/gcodeviewer/__init__.py
index a72b1f860..a145c3887 100644
--- a/src/octoprint/plugins/gcodeviewer/__init__.py
+++ b/src/octoprint/plugins/gcodeviewer/__init__.py
@@ -1,15 +1,20 @@
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
+import os
+
+import flask
from flask_babel import gettext
import octoprint.plugin
+from octoprint.util.files import search_through_file
class GcodeviewerPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin,
+ octoprint.plugin.BlueprintPlugin,
):
def get_assets(self):
js = [
@@ -70,6 +75,30 @@ class GcodeviewerPlugin(
self._settings.set_int(["sizeThreshold"], config["sizeThreshold"])
self._settings.global_remove(["gcodeViewer"])
+ @octoprint.plugin.BlueprintPlugin.route(
+ "/skipuntilcheck//", methods=["GET"]
+ )
+ def check_skip_until_presence(self, origin, filename):
+ try:
+ path = self._file_manager.path_on_disk(origin, filename)
+ except NotImplementedError:
+ # storage doesn't support path on disk
+ flask.abort(404)
+
+ if not os.path.exists(path):
+ # path doesn't exist
+ flask.abort(404)
+
+ skipUntilThis = self._settings.get(["skipUntilThis"])
+ if not skipUntilThis:
+ # no skipUntilThis, no need to search, shortcut
+ return flask.jsonify(present=False)
+
+ return flask.jsonify(present=search_through_file(path, skipUntilThis))
+
+ def is_blueprint_csrf_protected(self):
+ return True
+
__plugin_name__ = gettext("GCode Viewer")
__plugin_author__ = "Gina Häußge"
diff --git a/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js
index aaf38a58d..23d1c8552 100644
--- a/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js
+++ b/src/octoprint/plugins/gcodeviewer/static/js/gcodeviewer.js
@@ -16,14 +16,6 @@ $(function () {
self.ui_progress_text = ko.pureComputed(function () {
var text = "";
switch (self.ui_progress_type()) {
- case "downloading": {
- text = gettext("Downloading...");
- break;
- }
- case "splitting": {
- text = gettext("Splitting lines...");
- break;
- }
case "parsing": {
text =
gettext("Parsing...") +
@@ -396,6 +388,7 @@ $(function () {
onProgress: self._onProgress,
onModelLoaded: self._onModelLoaded,
onLayerSelected: self._onLayerSelected,
+ onFileLoaded: self._onFileLoaded,
bed: self._retrieveBedDimensions(),
toolOffsets: self._retrieveToolOffsets(),
invertAxes: self._retrieveAxesConfiguration(),
@@ -517,51 +510,33 @@ $(function () {
self.needsLoad = false;
if (self.status === "idle" && self.errorCount < 3) {
self.status = "request";
- self._onProgress("downloading");
- OctoPrint.files
- .download("local", path)
- .done(function (response, rstatus) {
- if (rstatus === "success") {
- self.showGCodeViewer(response, rstatus);
- self.loadedFilepath = path;
- self.loadedFileDate = date;
- self.status = "idle";
- self.enableReload(true);
- }
- })
- .fail(function () {
- self.status = "idle";
- self.errorCount++;
- });
+
+ self.cachedPath = path;
+ self.cachedDate = date;
+ var par = {
+ url: OctoPrint.files.downloadPath("local", path),
+ path: path,
+ skipUntil: self.settings.settings.plugins.gcodeviewer.skipUntilThis()
+ };
+
+ GCODE.renderer.clear();
+ self._onProgress("parsing");
+ GCODE.gCodeReader.loadFile(par);
+
+ if (self.layerSlider !== undefined) {
+ self.layerSlider.slider("disable");
+ }
+ if (self.layerCommandSlider !== undefined) {
+ self.layerCommandSlider.slider("disable");
+ }
}
};
- self.showGCodeViewer = function (response, rstatus) {
- // Slice of the gcode
- var findThis = self.settings.settings.plugins.gcodeviewer.skipUntilThis();
- if (findThis && findThis !== "") {
- var indexPos = response.indexOf("\n" + findThis);
- if (indexPos !== -1) {
- // Slice and make sure we comment out any string left back after slicing - so if a user configures something like "G1" we dont end up with a snippet of gcode commands
- // Yes it would be prettier to parse it line by line and remove the entire line, that is very slow and uses mem - this way we find the string, and remove it
- response = ";" + response.slice(indexPos + findThis.length + 1);
- }
- }
- var par = {
- target: {
- result: response
- }
- };
- GCODE.renderer.clear();
- self._onProgress("splitting");
- GCODE.gCodeReader.loadFile(par);
-
- if (self.layerSlider !== undefined) {
- self.layerSlider.slider("disable");
- }
- if (self.layerCommandSlider !== undefined) {
- self.layerCommandSlider.slider("disable");
- }
+ self._onFileLoaded = function () {
+ self.loadedFilepath = self.cachedPath;
+ self.loadedFileDate = self.cachedDate;
+ self.status = "idle";
+ self.enableReload(true);
};
self.reload = function () {
diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js
index 7afd71cc8..31df5d3ab 100644
--- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js
+++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/reader.js
@@ -210,25 +210,6 @@ GCODE.gCodeReader = (function () {
loadFile: function (reader) {
this.clear();
- var totalSize = reader.target.result.length;
-
- /*
- * Split by line ending
- *
- * Be aware that for windows line endings \r\n this leaves the \r attached to
- * the lines. That will not influence our parser, but makes file position
- * calculation way easier (line length + 1), so we just leave it in.
- *
- * This cannot cope with old MacOS \r line endings, but those should
- * really not be used anymore and thus we'll happily ignore them here.
- *
- * Note: A simple string split uses up *much* less memory than regex.
- */
- lines = reader.target.result.split("\n");
-
- reader.target.result = null;
- prepareGCode(totalSize);
-
var mustCompress =
gCodeOptions["forceCompression"] ||
gCodeOptions["alwaysCompress"] ||
@@ -236,9 +217,11 @@ GCODE.gCodeReader = (function () {
gCodeOptions["compressionSizeThreshold"] <= totalSize);
GCODE.ui.worker.postMessage({
- cmd: "parseGCode",
+ cmd: "downloadAndParseGCode",
msg: {
- gcode: gcode,
+ url: reader.url,
+ path: reader.path,
+ skipUntil: reader.skipUntil,
options: {
firstReport: 5,
toolOffsets: gCodeOptions["toolOffsets"],
diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js
index 3e9672f22..9fa1494ae 100644
--- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js
+++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/ui.js
@@ -13,7 +13,8 @@ GCODE.ui = (function () {
bedDimensions: undefined,
onProgress: undefined,
onModelLoaded: undefined,
- onLayerSelected: undefined
+ onLayerSelected: undefined,
+ onFileLoaded: undefined
};
var setProgress = function (type, progress) {
@@ -49,6 +50,9 @@ GCODE.ui = (function () {
var data = e.data;
switch (data.cmd) {
case "returnModel":
+ if (uiOptions["onFileLoaded"]) {
+ uiOptions.onFileLoaded();
+ }
GCODE.ui.worker.postMessage({
cmd: "analyzeModel",
msg: {}
diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js
index dcdd0c69b..c1be5700c 100644
--- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js
+++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/worker.js
@@ -4,7 +4,10 @@
* Time: 12:18 PM
*/
-var gcode;
+// raw path suitable for fetch()
+var url;
+// path relative to Local
+var path;
var firstReport;
var toolOffsets = [{x: 0, y: 0}];
var g90InfluencesExtruder = false;
@@ -40,6 +43,8 @@ var emptyLayers = [];
var percentageByLayer = [];
var mustCompress = false;
+var skipUntil = null;
+var skipUntilPresent = false;
importScripts("../lib/pako.js");
@@ -337,7 +342,73 @@ var analyzeModel = function () {
sendAnalyzeDone();
};
-var doParse = function () {
+var gCodeLineGenerator = async function* (fileURL) {
+ const utf8Decoder = new TextDecoder("utf-8");
+ const response = await fetch(fileURL);
+
+ // the download failed.
+ if (!response.ok) return;
+
+ // create a reader object that will read the incoming data
+ const reader = response.body.getReader();
+
+ // we use these two variables to calculate the percentage.
+ var totalDownloadLength = response.headers.get("content-length");
+ var currentDownloadLength = 0;
+
+ // lets read a first data chunk
+ let {value: chunk, done: readerDone} = await reader.read();
+ chunk = chunk ? utf8Decoder.decode(chunk) : "";
+
+ // some init
+ const re = /\n|\r|\r\n/gm;
+ let startIndex = 0;
+ let result;
+
+ // now continue until all the downloaded data is processed.
+ for (;;) {
+ // cut at a new line
+ let result = re.exec(chunk);
+ if (!result) {
+ // there was not a complete line, what is up?
+
+ if (readerDone) {
+ // we reached the end of the file.
+ break;
+ }
+ // lets read a new chunk
+ let remainder = chunk.substr(startIndex);
+ ({value: chunk, done: readerDone} = await reader.read());
+ // concatenate with our leftovers from the previous chunk
+ chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
+ // reset the indexes
+ startIndex = re.lastIndex = 0;
+ continue;
+ }
+ // we use re.lastIndex and not result.index so we include
+ // the actual terminator.
+ currentDownloadLength += re.lastIndex - startIndex;
+ // return the data to the caller
+ yield [
+ chunk.substring(startIndex, result.index),
+ (100 * currentDownloadLength) / totalDownloadLength
+ ];
+
+ // move to after the line we just returned
+ startIndex = re.lastIndex;
+ }
+ if (startIndex < chunk.length) {
+ // last line didn't end in a newline char
+ currentDownloadLength += chunk.length - startIndex;
+ // return the data to the caller
+ yield [
+ chunk.substr(startIndex),
+ (100 * currentDownloadLength) / totalDownloadLength
+ ];
+ }
+};
+
+var doParse = async function () {
var argChar, numSlice;
var activeLayer = undefined;
var sendLayer = undefined;
@@ -376,10 +447,23 @@ var doParse = function () {
// visualizer doesn't actually have a physical offset ;)
var activeToolOffset = toolOffsets[0];
+ // skipUntil preparations
+ var skipUntilFound = false;
+
var i, j, args;
+ // if skipUntil is set, get skipUntilPresent
+ skipUntilPresent = false;
+ if (skipUntil !== undefined && skipUntil !== "") {
+ result = await fetch("/plugin/gcodeviewer/skipuntilcheck/local/" + path);
+ if (result.ok) {
+ response = await result.json();
+ skipUntilPresent = response.present;
+ }
+ }
+
model = [];
- for (i = 0; i < gcode.length; i++) {
+ for await (let [line, percentage] of gCodeLineGenerator(url)) {
x = undefined;
y = undefined;
z = undefined;
@@ -388,8 +472,11 @@ var doParse = function () {
center_j = undefined;
direction = undefined;
- var line = gcode[i].line;
- var percentage = gcode[i].percentage;
+ // find the skipUntil if it is present
+ // we do not actually remove the line, it is parsed normally.
+ if (skipUntilPresent && !skipUntilFound && line.startsWith(skipUntil)) {
+ skipUntilFound = true;
+ }
extrude = false;
line = line.split(/[\(;]/)[0];
@@ -646,7 +733,9 @@ var doParse = function () {
zLift = false;
}
- if (addToModel) {
+ // if skipUntilPresent is true, we will not add anything to
+ // the model until the skipUntil string is found.
+ if (addToModel && (!skipUntilPresent || skipUntilFound)) {
if (!model[layer]) model[layer] = [];
if (model[layer] instanceof Uint8Array)
model[layer] = decompress(model[layer]);
@@ -748,9 +837,9 @@ var doParse = function () {
}
if (typeof sendLayer !== "undefined") {
- if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length !== 0) {
- lastSend = i;
- sendLayersToParent(sendMultiLayer, (i / gcode.length) * 100);
+ if (percentage - lastSend > 2 && sendMultiLayer.length !== 0) {
+ lastSend = percentage;
+ sendLayersToParent(sendMultiLayer, percentage);
sendMultiLayer = [];
sendMultiLayerZ = [];
}
@@ -770,8 +859,9 @@ var doParse = function () {
sendLayersToParent(sendMultiLayer, 100);
};
-var parseGCode = function (message) {
- gcode = message.gcode;
+var parseGCode = async function (message) {
+ url = message.url;
+ path = message.path;
firstReport = message.options.firstReport;
toolOffsets = message.options.toolOffsets;
if (!toolOffsets || toolOffsets.length === 0) toolOffsets = [{x: 0, y: 0}];
@@ -780,9 +870,9 @@ var parseGCode = function (message) {
g90InfluencesExtruder = message.options.g90InfluencesExtruder;
boundingBox.minZ = min.z = message.options.bedZ;
mustCompress = message.options.compress;
+ skipUntil = message.skipUntil;
- doParse();
- gcode = [];
+ await doParse();
self.postMessage({
cmd: "returnModel",
msg: {}
@@ -827,7 +917,7 @@ onmessage = function (e) {
var data = e.data;
// for some reason firefox doesn't garbage collect when something inside closures is deleted, so we delete and recreate whole object eaech time
switch (data.cmd) {
- case "parseGCode":
+ case "downloadAndParseGCode":
parseGCode(data.msg);
break;
case "setOption":
diff --git a/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2 b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2
index a83b4a90a..0fc5342f8 100644
--- a/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2
+++ b/src/octoprint/plugins/gcodeviewer/templates/gcodeviewer_settings.jinja2
@@ -7,9 +7,6 @@
{% trans %}If provided, the GCode Viewer will search for a line beginning with this string. If found, all GCode up to that point will be skipped. This can be used to skip "purge/nozzle wipe" GCode in the viewer. Note the search is case sensitive.{% endtrans %}
-
- {% trans %}Important! Make sure that any setup codes (especially things like G20/G21, G90/G91, M82/M83) are not skipped, or your files might not get rendered correctly! If things look broken with a skip configuration, you are skipping too much.{% endtrans %}
-