From 1093ff0714e26ca8d81f3d7fe15d782cc047346f Mon Sep 17 00:00:00 2001 From: SoftFever <103989404+SoftFever@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:14:58 +0800 Subject: [PATCH] Let Slice and Print retry after a post-processing script or plugin fails (#17095) --- src/libslic3r/Print.hpp | 4 + src/libslic3r/PrintBase.hpp | 4 + src/slic3r/GUI/BackgroundSlicingProcess.cpp | 32 +++-- src/slic3r/GUI/BackgroundSlicingProcess.hpp | 6 +- src/slic3r/GUI/Plater.cpp | 8 +- src/slic3r/GUI/PostProcessor.cpp | 27 +++- src/slic3r/GUI/PostProcessor.hpp | 4 +- tests/fff_print/test_print.cpp | 32 +++++ tests/slic3rutils/CMakeLists.txt | 1 + tests/slic3rutils/test_post_processor.cpp | 142 ++++++++++++++++++++ 10 files changed, 243 insertions(+), 17 deletions(-) create mode 100644 tests/slic3rutils/test_post_processor.cpp diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index d9d7f801fe..0aca2dcde0 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -1311,6 +1311,10 @@ public: //BBS: export gcode from previous gcode file from 3mf void set_gcode_file_ready(); void set_gcode_file_invalidated(); + // For the background thread that exported the G-code, when a step that then edits the file in place + // (post-processing scripts or plugins) failed and may have left it half edited: the next run exports + // the G-code again instead of reusing it. + void invalidate_gcode_export_from_worker() { this->invalidate_step_from_worker(psGCodeExport); } void export_gcode_from_previous_file(const std::string& file, GCodeProcessorResult* result, ThumbnailsGeneratorCallback thumbnail_cb = nullptr); // Re-reads the moves and line offsets of `result` from its G-code file after the file was rewritten in // place (post-processing scripts or plugins), so the preview and its G-code window follow the file on diff --git a/src/libslic3r/PrintBase.hpp b/src/libslic3r/PrintBase.hpp index f3c40102f8..b3d10bab77 100644 --- a/src/libslic3r/PrintBase.hpp +++ b/src/libslic3r/PrintBase.hpp @@ -621,6 +621,10 @@ protected: { return m_state.invalidate_multiple(il.begin(), il.end(), this->cancel_callback()); } bool invalidate_all_steps() { return m_state.invalidate_all(this->cancel_callback()); } + // invalidate_step() for the background processing thread, about a step it finished itself. It skips the + // cancel callback, which stops the background processing and so would wait for this very thread. + bool invalidate_step_from_worker(PrintStepEnum step) + { std::scoped_lock lock(this->state_mutex()); return m_state.invalidate(step, []() {}); } bool is_step_started_unguarded(PrintStepEnum step) const { return m_state.is_started_unguarded(step); } bool is_step_done_unguarded(PrintStepEnum step) const { return m_state.is_done_unguarded(step); } diff --git a/src/slic3r/GUI/BackgroundSlicingProcess.cpp b/src/slic3r/GUI/BackgroundSlicingProcess.cpp index e1dc565874..d9d716a658 100644 --- a/src/slic3r/GUI/BackgroundSlicingProcess.cpp +++ b/src/slic3r/GUI/BackgroundSlicingProcess.cpp @@ -83,15 +83,18 @@ bool SlicingProcessCompletedEvent::critical_error() const bool SlicingProcessCompletedEvent::invalidate_plater() const { - if (critical_error()) { - try { - this->rethrow_exception(); - } catch (const Slic3r::ExportError&) { - // Exception thrown by copying file does not ivalidate plater - return false; - } catch (...) {} + return error() && critical_error() && !export_failed(); +} + +bool SlicingProcessCompletedEvent::export_failed() const +{ + if (!error()) + return false; + try { + this->rethrow_exception(); + } catch (const Slic3r::ExportError&) { return true; - } + } catch (...) {} return false; } @@ -289,8 +292,15 @@ void BackgroundSlicingProcess::process_fff() // the preview re-reads its moves and line offsets from the edited file. The rest of m_gcode_result, // including nozzle_group_result (consumed by the H2C print-dispatch nozzle mapping), is kept. if (m_fff_print->is_BBL_printer()) { - if (run_post_process_scripts(m_temp_output_path, false, "File", m_temp_output_path, m_fff_print->full_print_config())) - m_fff_print->reload_gcode_moves(m_gcode_result); + try { + if (run_post_process_scripts(m_temp_output_path, false, "File", m_temp_output_path, m_fff_print->full_print_config())) + m_fff_print->reload_gcode_moves(m_gcode_result); + } catch (...) { + // A failed script or plugin may have left the G-code half edited, so the next run exports + // it again instead of reusing it. + m_fff_print->invalidate_gcode_export_from_worker(); + throw; + } } BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": export gcode finished"); @@ -991,7 +1001,7 @@ void BackgroundSlicingProcess::prepare_upload() m_print->set_status(95, _utf8(L("Running post-processing scripts"))); std::string error_message; if (copy_file(m_temp_output_path, source_path.string(), error_message) != SUCCESS) - throw Slic3r::RuntimeError(_utf8(L("Copying of the temporary G-code to the output G-code failed."))); + throw Slic3r::ExportError(_utf8(L("Copying of the temporary G-code to the output G-code failed."))); m_upload_job.upload_data.upload_path = m_fff_print->print_statistics().finalize_output_path( m_upload_job.upload_data.upload_path.string()); // Orca: skip post-processing scripts for BBL printers as we have run them already in finalize_gcode() diff --git a/src/slic3r/GUI/BackgroundSlicingProcess.hpp b/src/slic3r/GUI/BackgroundSlicingProcess.hpp index 1ccd821190..b1375b672b 100644 --- a/src/slic3r/GUI/BackgroundSlicingProcess.hpp +++ b/src/slic3r/GUI/BackgroundSlicingProcess.hpp @@ -67,8 +67,12 @@ public: bool error() const { return m_status == Error; } // Unhandled error produced by stdlib or a Win32 structured exception, or unhandled Slic3r's own critical exception. bool critical_error() const; - // Critical errors does invalidate plater except CopyFileError. + // A critical error that leaves the sliced data unusable. A failed export (export_failed()) is critical too, + // but leaves the sliced data usable. bool invalidate_plater() const; + // Exporting or uploading the G-code failed (a copy, a post-processing script or plugin: an ExportError); + // the slice itself is intact. + bool export_failed() const; // Only valid if error() void rethrow_exception() const { assert(this->error()); assert(m_exception); std::rethrow_exception(m_exception); } // Produce a human readable message to be displayed by a notification or a message box. diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index ad7c8aa90d..90815a76d5 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -13440,8 +13440,12 @@ void Plater::priv::on_process_completed(SlicingProcessCompletedEvent &evt) } //BBS: set the current plater's slice result to valid - if (!this->background_process.empty()) - this->background_process.get_current_plate()->update_slice_result_valid_state(evt.success()); + // A failed export or upload keeps a complete FFF slice valid, so Print and Export can be run again. + if (!this->background_process.empty()) { + const bool slice_valid = evt.success() || + (evt.export_failed() && printer_technology == ptFFF && this->background_process.finished()); + this->background_process.get_current_plate()->update_slice_result_valid_state(slice_valid); + } //BBS: update the action button according to the current plate's status bool ready_to_slice = !this->partplate_list.get_curr_plate()->is_slice_result_valid(); diff --git a/src/slic3r/GUI/PostProcessor.cpp b/src/slic3r/GUI/PostProcessor.cpp index 34087aa7cb..f304fe52d2 100644 --- a/src/slic3r/GUI/PostProcessor.cpp +++ b/src/slic3r/GUI/PostProcessor.cpp @@ -34,7 +34,9 @@ #include #include "libslic3r/PrintConfig.hpp" #include +#include #include "libslic3r/Print.hpp" +#include "libslic3r/PrintBase.hpp" #include "libslic3r/Exception.hpp" #include #include @@ -265,7 +267,7 @@ void gcode_add_line_number(const std::string& path, const DynamicPrintConfig& co // seam. This is the same capability that runs at the geometry seams inside Print::process(); here it is // dispatched a final time on the exported G-code, so a plugin can edit slices AND the final G-code from // one class. Plugins are executed in-process through the embedded Python interpreter. Throws -// Slic3r::RuntimeError on any failure; the caller removes the working copy (see run_post_process_scripts' +// Slic3r::RuntimeError on any failure; the caller removes the working copy (see run_post_process_scripts_impl()'s // catch block). Entries are bare capability names; the top-level plugins manifest carries the full refs. // A geometry-only plugin simply returns success here (it filters on ctx.step), so it costs nothing beyond // one no-op call, but note any configured pipeline plugin still engages this post-process path (i.e. the @@ -343,7 +345,7 @@ static void run_post_process_plugins(const ConfigOptionStrings& capabilities, // output_name is the final name of the G-code on SD card or when uploaded to PrusaLink or OctoPrint. // If uploading to PrusaLink or OctoPrint, then the file will be renamed to output_name first on the target host. // The post-processing script may change the output_name. -bool run_post_process_scripts( +static bool run_post_process_scripts_impl( std::string& src_path, bool make_copy, const std::string& host, std::string& output_name, const DynamicPrintConfig& config) { // post_process / slicing_pipeline_plugin are absent in SLA mode, hence the null checks. G-code @@ -512,4 +514,25 @@ bool run_post_process_scripts( return true; } +// Post-processing works on G-code that is already generated, so whatever fails in it (a script or plugin, +// starting the shell, the file work around them) fails the export or upload, not the slice. It is reported +// as an ExportError, which does not invalidate the plater, so the user can retry (see +// SlicingProcessCompletedEvent::invalidate_plater()). A cancel, a fatal error and running out of memory keep +// their own handling. +bool run_post_process_scripts( + std::string& src_path, bool make_copy, const std::string& host, std::string& output_name, const DynamicPrintConfig& config) +{ + try { + return run_post_process_scripts_impl(src_path, make_copy, host, output_name, config); + } catch (const CanceledException&) { + throw; + } catch (const HardCrash&) { + throw; + } catch (const std::bad_alloc&) { + throw; + } catch (const std::exception& ex) { + throw ExportError(ex.what()); + } +} + } // namespace Slic3r diff --git a/src/slic3r/GUI/PostProcessor.hpp b/src/slic3r/GUI/PostProcessor.hpp index 25d2db3351..cf4da8ff81 100644 --- a/src/slic3r/GUI/PostProcessor.hpp +++ b/src/slic3r/GUI/PostProcessor.hpp @@ -15,7 +15,9 @@ namespace Slic3r { // not depend on. // Returns true if a script or plugin was executed. // Returns false if neither a post-processing script nor plugin was defined. -// Throws an exception on error. +// A failure of the scripts or plugins, or of the file work around them, throws Slic3r::ExportError: it fails +// this export or upload, not the slice. A cancel, a fatal error and running out of memory keep their own +// exceptions. // host is one of "File", "PrusaLink", "Repetier", "SL1Host", "OctoPrint", "FlashAir", "Duet", "AstroBox" ... // If make_copy, then a temp file will be created for src_path by adding a ".pp" suffix and src_path will be updated. // In that case the caller is responsible to delete the temp file created. Scripts and plugins always diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 8efb5e0ac0..e87a698720 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -932,6 +932,38 @@ TEST_CASE("Plate name reaches the G-code once G-code export is invalidated", "[P CHECK(regenerated.find("; Plate First") == std::string::npos); } +// The background thread drops its own export when an in-place edit of the file fails. The print's cancel +// callback stops that thread and waits for it, so the invalidation must not call it. +TEST_CASE("An export the background thread invalidates is written again without re-slicing", "[Print]") +{ + // Declared before the print, whose destructor calls the cancel callback too. + bool cancel_called = false; + Print print; + Model model; + init_print({ cube(20) }, print, model); + print.set_status_silent(); + print.set_cancel_callback([&cancel_called]() { cancel_called = true; }); + + ScopedTemporaryFile output(".gcode"); + print.process(); + print.export_gcode(output.string(), nullptr, nullptr); + REQUIRE(print.finished()); + // What a post-processing script that failed half way leaves in the file. + std::ofstream(output.string(), std::ios::app) << "; half edited\n"; + + print.invalidate_gcode_export_from_worker(); + CHECK_FALSE(print.finished()); + CHECK_FALSE(cancel_called); + CHECK(print.objects().front()->is_step_done(posSlice)); + + print.process(); + print.export_gcode(output.string(), nullptr, nullptr); + CHECK(print.finished()); + std::ifstream in(output.string(), std::ios::binary); + const std::string gcode((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + CHECK(gcode.find("; half edited") == std::string::npos); +} + // The layer change G-code runs before its layer prints, so the layer mass it gets is the previous layer's. TEST_CASE("Layer change G-code gets the previous layer's mass under both placeholder names", "[Print]") { diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 118ec3205a..0ff09b2b04 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -41,6 +41,7 @@ add_executable(${_TEST_NAME}_tests test_plugin_lifecycle.cpp test_plugin_resource_texture.cpp test_plugin_printer_agent.cpp + test_post_processor.cpp test_printhost.cpp test_slicing_pipeline_bindings.cpp test_slicing_pipeline_config.cpp diff --git a/tests/slic3rutils/test_post_processor.cpp b/tests/slic3rutils/test_post_processor.cpp new file mode 100644 index 0000000000..ff8765e0b9 --- /dev/null +++ b/tests/slic3rutils/test_post_processor.cpp @@ -0,0 +1,142 @@ +#include +#include +#include + +#include +#include +#include +#include +#ifndef _WIN32 +#include +#include +#include +#endif + +#include + +#include "libslic3r/Config.hpp" +#include "libslic3r/Exception.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "slic3r/GUI/BackgroundSlicingProcess.hpp" +#include "slic3r/GUI/PostProcessor.hpp" +#include "test_utils.hpp" + +using namespace Slic3r; +using Catch::Matchers::ContainsSubstring; + +namespace { + +// Runs `script` as the post-processing script on a real G-code file, so a failure comes from the script +// and not from a missing input, and returns what it threw. +std::exception_ptr post_process_with(const std::string& script) +{ + ScopedTemporaryFile gcode(".gcode"); + std::ofstream(gcode.string()) << "G1 X10 Y10\n"; + DynamicPrintConfig config; + config.set_key_value("post_process", new ConfigOptionStrings({script})); + std::string path = gcode.string(); + std::string output_name = gcode.string(); + try { + run_post_process_scripts(path, false, "File", output_name, config); + } catch (...) { + return std::current_exception(); + } + return nullptr; +} + +std::string message_of(const std::exception_ptr& ex) +{ + try { + std::rethrow_exception(ex); + } catch (const std::exception& e) { + return e.what(); + } +} + +SlicingProcessCompletedEvent completed(SlicingProcessCompletedEvent::StatusType status, std::exception_ptr ex) +{ + return SlicingProcessCompletedEvent(wxEVT_NULL, 0, status, std::move(ex)); +} + +#ifndef _WIN32 +// Sets an environment variable for the scope, restoring its previous value. +class ScopedEnv +{ +public: + ScopedEnv(const char* name, const char* value) : m_name(name) + { + if (const char* old = std::getenv(name)) + m_old = old; + ::setenv(name, value, 1); + } + ~ScopedEnv() + { + if (m_old) + ::setenv(m_name.c_str(), m_old->c_str(), 1); + else + ::unsetenv(m_name.c_str()); + } + +private: + std::string m_name; + std::optional m_old; +}; +#endif + +} // namespace + +TEST_CASE("A post-processing script that cannot run fails the export, not the slice", "[PostProcessor]") +{ + ScopedTemporaryFile missing(".sh"); + // Quoted, as a configured path with spaces must be (the temp directory may have some). + const std::exception_ptr ex = post_process_with("\"" + missing.string() + "\""); + + REQUIRE(ex); + CHECK_THROWS_AS(std::rethrow_exception(ex), ExportError); + CHECK_THAT(message_of(ex), ContainsSubstring(missing.path().filename().string())); + const SlicingProcessCompletedEvent evt = completed(SlicingProcessCompletedEvent::Error, ex); + CHECK(evt.export_failed()); + CHECK_FALSE(evt.invalidate_plater()); +} + +#ifndef _WIN32 +TEST_CASE("A post-processing script that fails reports its exit code as an export error", "[PostProcessor]") +{ + const std::exception_ptr ex = post_process_with("sh -c 'echo \"; half edited\" >> \"$0\"; exit 3'"); + + REQUIRE(ex); + CHECK_THROWS_AS(std::rethrow_exception(ex), ExportError); + CHECK_THAT(message_of(ex), ContainsSubstring("Error code: 3")); +} + +TEST_CASE("A shell that cannot start fails the export, not the slice", "[PostProcessor]") +{ + ScopedTemporaryFile missing_shell(".sh"); + ScopedEnv shell("SHELL", missing_shell.string().c_str()); + const std::exception_ptr ex = post_process_with("true"); + + REQUIRE(ex); + CHECK_THROWS_AS(std::rethrow_exception(ex), ExportError); +} +#endif + +TEST_CASE("A completion event tells a failed export from a failed slice", "[PostProcessor]") +{ + const SlicingProcessCompletedEvent export_error = + completed(SlicingProcessCompletedEvent::Error, std::make_exception_ptr(ExportError("copy failed"))); + CHECK(export_error.export_failed()); + CHECK(export_error.critical_error()); + CHECK_FALSE(export_error.invalidate_plater()); + + const SlicingProcessCompletedEvent slice_error = + completed(SlicingProcessCompletedEvent::Error, std::make_exception_ptr(RuntimeError("slicing failed"))); + CHECK_FALSE(slice_error.export_failed()); + CHECK(slice_error.invalidate_plater()); + + // A cancel or a success carries no exception to inspect. + for (const auto status : {SlicingProcessCompletedEvent::Cancelled, SlicingProcessCompletedEvent::Finished}) { + const SlicingProcessCompletedEvent evt = completed(status, nullptr); + CHECK_FALSE(evt.export_failed()); + CHECK_FALSE(evt.invalidate_plater()); + } +}