⚡ GCodeViewer: Async download (#4559)

* 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 <gina@octoprint.org>

* Apply requested changes.

* Rename symbols for readability

Co-authored-by: Gina Häußge <gina@octoprint.org>
This commit is contained in:
JoveTooandGina Häußge authored and GitHub committed 2022-10-20 13:21:30 +02:00
1 parent b032e1339f
commit 8f38088893
7 files changed
+175 -89

No files matched your search

@@ -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/<string:origin>/<path:filename>", 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"
@@ -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 () {
@@ -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"],
@@ -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: {}
@@ -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":
@@ -7,9 +7,6 @@
<span class="help-block">
{% 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 %}
</span>
<span class="help-block">
{% trans %}<strong>Important!</strong> Make sure that any setup codes (especially things like <code>G20</code>/<code>G21</code>, <code>G90</code>/<code>G91</code>, <code>M82</code>/<code>M83</code>) are <strong>not</strong> skipped, or your files might not get rendered correctly! If things look broken with a skip configuration, you are skipping too much.{% endtrans %}
</span>
</div>
</div>
<div class="control-group" title="{{ _('Maximum size for which the GCode Viewer autoloads the file for preview')|edq }}">
@@ -156,6 +156,14 @@
return this.base.download(downloadForEntry(location, path), opts);
};
OctoPrintFilesClient.prototype.downloadPath = function (location, path) {
var url = downloadForEntry(location, path);
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
url = this.base.getBaseUrl() + url;
}
return url;
};
OctoPrintFilesClient.prototype.pathForEntry = function (entry) {
if (!entry || !entry.hasOwnProperty("parent") || entry.parent == undefined) {
return "";