From 9281032fdc3925474e2afb0af8ba4cca79fc626f Mon Sep 17 00:00:00 2001 From: Ian Chua Date: Wed, 4 Nov 2026 14:41:23 +0800 Subject: [PATCH 01/24] feat: add plater notifications for orcacloud plugin updates (#17168) --- src/slic3r/GUI/GUI_App.cpp | 26 ++++++++++++--- src/slic3r/GUI/NotificationManager.hpp | 18 ++++++++++ src/slic3r/plugin/PluginManager.cpp | 46 ++++++++++++++++++++++++++ 3 files changed, 85 insertions(+), 5 deletions(-) diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 69e071c617..e4693d3056 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -3662,9 +3662,10 @@ bool GUI_App::on_init_inner() if (m_agent && m_agent->is_user_login()) { enable_user_preset_folder(true); - plugin_mgr.set_cloud_user(m_agent->get_user_id()); + const std::string cloud_user_id = m_agent->get_user_id(); + plugin_mgr.set_cloud_user(cloud_user_id); // Sync cloud plugin metadata off the UI thread; the network round trips took ~2 s of startup. - m_startup_cloud_plugin_fetch_thread = Slic3r::create_thread([this] { + m_startup_cloud_plugin_fetch_thread = Slic3r::create_thread([this, cloud_user_id] { std::vector not_found, unauthorized; try { PluginManager::instance().fetch_plugins_from_cloud(¬_found, &unauthorized); @@ -3675,14 +3676,15 @@ bool GUI_App::on_init_inner() BOOST_LOG_TRIVIAL(error) << "Startup cloud plugin fetch failed"; return; } - auto report = [this, not_found = std::move(not_found), unauthorized = std::move(unauthorized)] { + auto report = [this, cloud_user_id, not_found = std::move(not_found), unauthorized = std::move(unauthorized)] { if (is_closing()) return; if (m_plugins_dlg) m_plugins_dlg->update_plugin_dialog_ui(); Plater* plater = this->plater(); - if (plater == nullptr || m_agent == nullptr || !m_agent->is_user_login()) - return; // logged out meanwhile + if (plater == nullptr || m_agent == nullptr || !m_agent->is_user_login() || + m_agent->get_user_id() != cloud_user_id) + return; // logged out or switched account meanwhile for (const auto& uuid : not_found) { plater->get_notification_manager()->push_notification( NotificationType::CustomNotification, @@ -3695,6 +3697,20 @@ bool GUI_App::on_init_inner() NotificationManager::NotificationLevel::RegularNotificationLevel, format(_L("Plugin %s access is unauthorized."), uuid)); } + + // If the fetch finished before the plater existed, PluginManager could not deliver + // its update notice. Deliver it here from post_init(). update_available is only set + // by a successful fetch, so this remains success-only, and reading it now keeps the + // notice fresh if updates were installed while the report was deferred. + NotificationManager* notifications = plater->get_notification_manager(); + if (notifications != nullptr && + !notifications->has_notification_of_type(NotificationType::OrcaCloudPluginUpdateAvailable)) { + const std::vector descriptors = PluginManager::instance().get_plugin_descriptors(); + const bool has_update = std::any_of(descriptors.begin(), descriptors.end(), + [](const PluginDescriptor& descriptor) { return descriptor.has_update_available(); }); + if (has_update) + notifications->push_notification(NotificationType::OrcaCloudPluginUpdateAvailable); + } }; // This can run in a splash wxYield() before the main window exists. CallAfter([this, report = std::move(report)]() mutable { diff --git a/src/slic3r/GUI/NotificationManager.hpp b/src/slic3r/GUI/NotificationManager.hpp index ff40a2b5c1..713a8a599c 100644 --- a/src/slic3r/GUI/NotificationManager.hpp +++ b/src/slic3r/GUI/NotificationManager.hpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -197,6 +198,9 @@ enum class NotificationType // Active preset references a capability the installed+loaded plugin does not provide (outdated // plugin). Informational; cannot be auto-resolved; persistent, blocks slicing. OrcaPluginCapabilityUnavailableError, + // One aggregate notice that installed OrcaCloud plugins have updates. "More" opens the + // Plugins dialog, where the updates can be installed. + OrcaCloudPluginUpdateAvailable, NotificationTypeCount }; @@ -1130,6 +1134,20 @@ private: return true; }}, + // One notice for all OrcaCloud plugin updates found by a successful metadata fetch. + NotificationData{NotificationType::OrcaCloudPluginUpdateAvailable, NotificationLevel::ImportantNotificationLevel, BBL_NOTICE_MAX_INTERVAL, + _u8L("Updates are available for your OrcaCloud plugins."), _u8L("More"), + [](wxEvtHandler*) { + // Defer past the notification's render frame: the Plugins dialog is a + // webview window and must not be created from inside an ImGui pass. + if (wxTheApp != nullptr) + wxGetApp().CallAfter([] { + if (wxTheApp != nullptr && !wxGetApp().is_closing()) + wxGetApp().open_plugins_dialog(); + }); + return true; + }}, + NotificationData{NotificationType::BBLPrinterConfigUpdateAvailable, NotificationLevel::ImportantNotificationLevel, BBL_NOTICE_MAX_INTERVAL, _u8L("New printer config available."), _u8L("Details"), [](wxEvtHandler *evnthndlr) { diff --git a/src/slic3r/plugin/PluginManager.cpp b/src/slic3r/plugin/PluginManager.cpp index 137aa9696a..ef58df74fb 100644 --- a/src/slic3r/plugin/PluginManager.cpp +++ b/src/slic3r/plugin/PluginManager.cpp @@ -1677,6 +1677,52 @@ void PluginManager::fetch_plugins_from_cloud(std::vector* out_not_f } } + // A successful fetch is the only point where update availability is authoritative. Publish + // one aggregate notice after the orphan/unauthorized verdicts above so a plugin the user can + // no longer act on is not advertised. The check is repeated when the callback runs, keeping + // the notice fresh if an update was installed while the fetch was in flight. + if (cloud_fetch_succeeded) { + std::string fetched_cloud_user; + { + std::lock_guard lock(m_mutex); + fetched_cloud_user = m_cloud_user_id; + } + + auto push_update_notification = [this, fetched_cloud_user]() { + if (wxTheApp == nullptr || m_shutting_down.load(std::memory_order_acquire)) + return; + if (GUI::wxGetApp().is_closing()) + return; + GUI::Plater* plater = GUI::wxGetApp().plater(); + // Before post_init() there is no plater yet; GUI_App's startup report delivers the + // notice instead of dropping it. + if (plater == nullptr) + return; + + bool update_available = false; + { + std::lock_guard lock(m_mutex); + if (m_cloud_user_id != fetched_cloud_user) + return; // login/logout while the fetch was in flight + update_available = std::any_of(m_plugins.begin(), m_plugins.end(), [](const Plugin& plugin) { + return plugin.descriptor.has_update_available(); + }); + } + if (!update_available) + return; + + GUI::NotificationManager* notifications = plater->get_notification_manager(); + if (notifications == nullptr || + notifications->has_notification_of_type(GUI::NotificationType::OrcaCloudPluginUpdateAvailable)) + return; + notifications->push_notification(GUI::NotificationType::OrcaCloudPluginUpdateAvailable); + }; + if (wxTheApp == nullptr || wxIsMainThread()) + push_update_notification(); + else + GUI::wxGetApp().CallAfter(std::move(push_update_notification)); + } + if (out_not_found) *out_not_found = std::move(not_found); if (out_unauthorized) From 78134d24c6ea4442b2e318accb8b1952ae691cda Mon Sep 17 00:00:00 2001 From: Lam Wei Lun Date: Wed, 4 Nov 2026 17:14:04 +0800 Subject: [PATCH 02/24] Keep the Speed Dial anchored to the main window (#17242) fix: keep the Speed Dial anchored to the main window The dial is a long-lived hidden window. Its origin was computed once, at construction (DPIAware's CenterOnParent and create_webview's), and never again, so moving or resizing the main frame - or dragging it to another display - left the dial at the centre of the frame's original rect. Wayland only looked correct because the compositor places the window there. Re-derive the origin from the parent's current screen rect on every open, again once the window is mapped (GTK drops a position requested before the map), and on a DPI change. The origin comes from the fixed 540x282 box rather than the current client height, so the content-driven resize does not move the window while the user types. On GTK, clear the dialog's default CENTER_ON_PARENT hint so the window manager stops overriding the computed coordinates. The geometry is a free function, so the centring and the work-area clamp are testable without a GUI. --- src/slic3r/GUI/SpeedDialDialog.cpp | 50 +++++++++++ src/slic3r/GUI/SpeedDialDialog.hpp | 10 +++ tests/slic3rutils/CMakeLists.txt | 1 + .../slic3rutils/test_speed_dial_position.cpp | 85 +++++++++++++++++++ 4 files changed, 146 insertions(+) create mode 100644 tests/slic3rutils/test_speed_dial_position.cpp diff --git a/src/slic3r/GUI/SpeedDialDialog.cpp b/src/slic3r/GUI/SpeedDialDialog.cpp index a079e89cd7..17fe5ccfeb 100644 --- a/src/slic3r/GUI/SpeedDialDialog.cpp +++ b/src/slic3r/GUI/SpeedDialDialog.cpp @@ -137,6 +137,15 @@ nlohmann::json speed_dial_ui_strings() } // namespace +wxPoint speed_dial_origin(const wxRect& parent_screen_rect, const wxRect& work_area, const wxSize& box_size) +{ + const int x = parent_screen_rect.x + (parent_screen_rect.width - box_size.GetWidth()) / 2; + const int y = parent_screen_rect.y + (parent_screen_rect.height - box_size.GetHeight()) / 2; + // std::max(0, ...) keeps the clamp bounds ordered when the work area is smaller than the box. + return {std::clamp(x, work_area.x, work_area.x + std::max(0, work_area.width - box_size.GetWidth())), + std::clamp(y, work_area.y, work_area.y + std::max(0, work_area.height - box_size.GetHeight()))}; +} + SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent) : WebViewHostDialog(parent, wxID_ANY, @@ -146,6 +155,11 @@ SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent) wxBORDER_NONE | wxFRAME_NO_TASKBAR | wxFRAME_FLOAT_ON_PARENT | wxFRAME_SHAPED) { SetBackgroundColour(bg_color()); +#ifdef __WXGTK__ + // wxGTK dialogs default to CENTER_ON_PARENT, which places the window at its first map and then + // keeps that position for every later Show(). position_over_parent() supplies the origin instead. + gtk_window_set_position(GTK_WINDOW(GetHandle()), GTK_WIN_POS_NONE); +#endif Bind(wxEVT_ACTIVATE, [this](wxActivateEvent& event) { // Focus the WebKit widget exactly when the WM makes the popup the active window // (modeless focus is granted asynchronously, so a focus request made right after @@ -174,14 +188,42 @@ SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent) apply_rounded_shape(); }); apply_rounded_shape(); + // Place the window before the first map; request_show() re-derives it on every later open. + position_over_parent(); } SpeedDialWebDialog::~SpeedDialWebDialog() { m_alive->store(false, std::memory_order_release); } nlohmann::json SpeedDialWebDialog::localized_strings() const { return speed_dial_ui_strings(); } +void SpeedDialWebDialog::position_over_parent() +{ + wxWindow* parent = GetParent(); + if (!parent) + return; + + int display_index = wxDisplay::GetFromWindow(parent); + if (display_index == wxNOT_FOUND) + display_index = 0; + const wxRect work_area = wxDisplay(static_cast(display_index)).GetClientArea(); + const wxPoint origin = speed_dial_origin(parent->GetScreenRect(), work_area, FromDIP(wxSize(kPopupWidth, kPopupMaxHeight))); + + if (origin != GetPosition()) + Move(origin); +#ifdef __WXGTK__ + // wxGTK caches requested coordinates: Move() can skip the native request even when the window + // manager ignored the previous one. Reapply at native level (same as ColorPickerDialog). + gtk_window_move(GTK_WINDOW(GetHandle()), origin.x, origin.y); +#endif +} + void SpeedDialWebDialog::request_show() { + // Re-derived on every open: the dialog is a long-lived hidden window, so without this the + // coordinates stay at the frame's position from the first open and the dial stops following the + // frame when it is moved, resized, or dragged to another display. + position_over_parent(); + if (IsShown()) { Raise(); focus_webview(browser(), m_page_ready); @@ -198,6 +240,11 @@ void SpeedDialWebDialog::request_show() // what makes typing reach the search field immediately on open. focus_webview(browser(), m_page_ready); repaint_webview(); + // A position requested before the window is mapped can be dropped, so reapply once it is up. + wxGetApp().CallAfter([this, alive = m_alive]() { + if (alive->load(std::memory_order_acquire)) + position_over_parent(); + }); } void SpeedDialWebDialog::on_script_message(const nlohmann::json& payload) @@ -351,6 +398,9 @@ void SpeedDialWebDialog::apply_rounded_shape() void SpeedDialWebDialog::on_dpi_changed(const wxRect&) { apply_rounded_shape(); + // A monitor with a different scale factor re-anchors the window: MSW applies the rect the OS + // suggests (wxNonOwnedWindow::HandleDPIChange), so re-derive the origin from the parent instead. + position_over_parent(); Refresh(); } diff --git a/src/slic3r/GUI/SpeedDialDialog.hpp b/src/slic3r/GUI/SpeedDialDialog.hpp index 841a72f240..851aaea7f5 100644 --- a/src/slic3r/GUI/SpeedDialDialog.hpp +++ b/src/slic3r/GUI/SpeedDialDialog.hpp @@ -14,6 +14,12 @@ class wxWindow; namespace Slic3r { namespace GUI { +// Top-left origin of the dial: a `box_size` rectangle centred on the parent's current screen rect, +// clamped so it stays inside the display work area (negative monitor origins are valid). Callers pass +// the fixed-width, maximum-height box rather than the current client size, so the content-driven +// resize in resize_to_content() never moves the window. +wxPoint speed_dial_origin(const wxRect& parent_screen_rect, const wxRect& work_area, const wxSize& box_size); + class SpeedDialWebDialog : public WebViewHostDialog { public: @@ -25,6 +31,10 @@ private: nlohmann::json localized_strings() const override; void on_script_message(const nlohmann::json& payload) override; void handle_web_command(const nlohmann::json& payload); + // Re-derives the origin from the parent's current screen rect and moves the window there. Called + // on every open, since the dialog is a long-lived hidden window: without this the coordinates + // stay at the frame's position from the first open (frozen at the first map by the WM). + void position_over_parent(); void resize_to_content(int height); void run_action(const std::string& id, const std::string& title, const std::string& param = ""); void open_wiki(const std::string& id); diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index b52e60c404..044ad0ea99 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -50,6 +50,7 @@ add_executable(${_TEST_NAME}_tests test_plugin_audit.cpp test_plugin_json_depth.cpp test_shortcuts.cpp + test_speed_dial_position.cpp test_texture_color_palette.cpp test_texture_island_view.cpp test_timelapse_codecs.cpp diff --git a/tests/slic3rutils/test_speed_dial_position.cpp b/tests/slic3rutils/test_speed_dial_position.cpp new file mode 100644 index 0000000000..9cd358248d --- /dev/null +++ b/tests/slic3rutils/test_speed_dial_position.cpp @@ -0,0 +1,85 @@ +#include + +#include "slic3r/GUI/SpeedDialDialog.hpp" + +#include + +using namespace Slic3r::GUI; + +namespace { + +// Matches kPopupWidth / kPopupMaxHeight in SpeedDialDialog.cpp: the dial derives its origin from this +// box rather than from its current client size, so the content-driven resize never moves the window. +const wxSize kDialBox(540, 282); + +} // namespace + +TEST_CASE("Speed dial origin centres the dial box on the parent window", "[SpeedDialPosition][SpeedDial]") +{ + const wxRect parent(120, 80, 1600, 1200); + const wxRect work_area(0, 0, 1920, 1200); + + const wxPoint origin = speed_dial_origin(parent, work_area, kDialBox); + + REQUIRE(origin.x == 650); // 120 + (1600 - 540) / 2 + REQUIRE(origin.y == 539); // 80 + (1200 - 282) / 2 +} + +TEST_CASE("Speed dial origin follows the parent when the parent is moved", "[SpeedDialPosition][SpeedDial]") +{ + const wxRect work_area(0, 0, 1920, 1200); + const wxRect first(120, 80, 1600, 1200); + const wxRect moved(400, 300, 1600, 1200); + + const wxPoint before = speed_dial_origin(first, work_area, kDialBox); + const wxPoint after = speed_dial_origin(moved, work_area, kDialBox); + + REQUIRE(after.x - before.x == 280); + REQUIRE(after.y - before.y == 220); +} + +TEST_CASE("Speed dial origin follows the parent when the parent is resized", "[SpeedDialPosition][SpeedDial]") +{ + const wxRect work_area(0, 0, 1920, 1200); + const wxRect wide(200, 100, 1400, 1000); + const wxRect narrow(200, 100, 1000, 700); + + const wxPoint before = speed_dial_origin(wide, work_area, kDialBox); + const wxPoint after = speed_dial_origin(narrow, work_area, kDialBox); + + REQUIRE(after.x - before.x == -200); // (1000 - 1400) / 2 + REQUIRE(after.y - before.y == -150); // ( 700 - 1000) / 2 +} + +TEST_CASE("Speed dial origin stays negative on a monitor left of the primary", "[SpeedDialPosition][SpeedDial]") +{ + const wxRect work_area(-1920, 0, 1920, 1080); + const wxRect parent(-1800, 100, 1600, 1000); + + const wxPoint origin = speed_dial_origin(parent, work_area, kDialBox); + + REQUIRE(origin.x == -1270); // -1800 + (1600 - 540) / 2 + REQUIRE(origin.y == 459); // 100 + (1000 - 282) / 2 +} + +TEST_CASE("Speed dial origin is clamped into the work area when the parent is mostly off screen", "[SpeedDialPosition][SpeedDial]") +{ + const wxRect work_area(0, 0, 1920, 1200); + const wxRect parent(1800, -800, 1600, 1200); + + const wxPoint origin = speed_dial_origin(parent, work_area, kDialBox); + + REQUIRE(origin.x == 1380); // centred would be 2330, clamped to 1920 - 540 + REQUIRE(origin.y == 0); // centred would be -341, clamped to the work-area top +} + +TEST_CASE("Speed dial origin is pinned to a work area smaller than the dial box", "[SpeedDialPosition][SpeedDial]") +{ + const wxRect work_area(0, 0, 300, 100); + const wxRect parent(0, 0, 300, 100); + + const wxPoint origin = speed_dial_origin(parent, work_area, kDialBox); + + REQUIRE(origin.x == work_area.x); + REQUIRE(origin.y == work_area.y); +} From 7e3d5d4d040a519815f62dc9dc94a0cf75ccb0c2 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:09:57 +0800 Subject: [PATCH 03/24] Ignore a Print Sequence Count That Does Not Match Its Values (#17243) * Ignore a Print Sequence Count That Does Not Match Its Values get_other_layers_print_sequence split other_layers_print_sequence into other_layers_print_sequence_nums groups and read the layer range from the first two entries of each, checking the layout with an assert that Release builds compile out. A count raised without its values, as a command line override does on a project storing the default placeholder, read past a one-element vector. A count that does not divide the values, or groups too short for a range and one extruder, now give no custom sequence, as the default pair does. * Log the Ignored Print Sequence and Test the Two-Group Case A pair that is ignored now says so in the log, since the removed assert was the only sign of it. The test covers two groups that divide the values but have no extruder, and names the negative-count case. --- src/libslic3r/ParameterUtils.cpp | 16 ++++++-- tests/libslic3r/CMakeLists.txt | 1 + tests/libslic3r/test_parameter_utils.cpp | 49 ++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 tests/libslic3r/test_parameter_utils.cpp diff --git a/src/libslic3r/ParameterUtils.cpp b/src/libslic3r/ParameterUtils.cpp index f2f3669124..2edaa6b00e 100644 --- a/src/libslic3r/ParameterUtils.cpp +++ b/src/libslic3r/ParameterUtils.cpp @@ -1,5 +1,6 @@ #include "ParameterUtils.hpp" #include "PrintConfig.hpp" +#include #include #include #include @@ -11,19 +12,26 @@ namespace Slic3r { std::vector get_other_layers_print_sequence(int sequence_nums, const std::vector &sequence) { std::vector res; - if (sequence_nums == 0 || sequence.empty()) + if (sequence_nums <= 0 || sequence.empty()) return res; - assert(sequence.size() % sequence_nums == 0); + // The two keys are written together by the GUI, but a config edited by hand or + // overridden on the command line can carry a count that does not divide the + // values, or groups too short for a layer range and one extruder. Treat such a + // pair as no custom sequence rather than reading past the groups. + size_t item_nums = sequence.size() / size_t(sequence_nums); + if (sequence.size() % size_t(sequence_nums) != 0 || item_nums < 3) { + BOOST_LOG_TRIVIAL(warning) << "other_layers_print_sequence_nums " << sequence_nums << " does not fit the " + << sequence.size() << " values of other_layers_print_sequence, ignoring the custom sequence"; + return res; + } res.reserve(sequence_nums); - size_t item_nums = sequence.size() / sequence_nums; for (int i = 0; i < sequence_nums; ++i) { std::vector item; item.assign(sequence.begin() + i * item_nums, sequence.begin() + ((i + 1) * item_nums)); - assert(item.size() > 2); std::pair, std::vector> res_item; res_item.first.first = item[0]; res_item.first.second = item[1]; diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index a95b476341..98f7b17c7a 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -83,6 +83,7 @@ add_executable(${_TEST_NAME}_tests test_wipe_path.cpp test_optimizers.cpp test_ordering_strategies.cpp + test_parameter_utils.cpp test_shortest_path.cpp # test_png_io.cpp test_indexed_triangle_set.cpp diff --git a/tests/libslic3r/test_parameter_utils.cpp b/tests/libslic3r/test_parameter_utils.cpp new file mode 100644 index 0000000000..a1a436eb83 --- /dev/null +++ b/tests/libslic3r/test_parameter_utils.cpp @@ -0,0 +1,49 @@ +#include + +#include + +#include "libslic3r/ParameterUtils.hpp" + +using namespace Slic3r; + +TEST_CASE("A print sequence splits into layer ranges with their extruder orders", "[ParameterUtils]") +{ + // Two groups of equal length: layers 1-5 print extruders 2 then 1, layers 6-9 print 1 then 2. + const std::vector sequence{1, 5, 2, 1, 6, 9, 1, 2}; + const auto seqs = get_other_layers_print_sequence(2, sequence); + REQUIRE(seqs.size() == 2); + CHECK(seqs[0].first.first == 1); + CHECK(seqs[0].first.second == 5); + CHECK(seqs[0].second == std::vector{2, 1}); + CHECK(seqs[1].first.first == 6); + CHECK(seqs[1].first.second == 9); + CHECK(seqs[1].second == std::vector{1, 2}); +} + +TEST_CASE("A print sequence round-trips through its flat form", "[ParameterUtils]") +{ + std::vector seqs{{{1, 3}, {2, 1}}, {{4, 8}, {1, 2}}}; + int nums = 0; + std::vector flat; + get_other_layers_print_sequence(seqs, nums, flat); + CHECK(nums == 2); + CHECK(flat == std::vector{1, 3, 2, 1, 4, 8, 1, 2}); + CHECK(get_other_layers_print_sequence(nums, flat) == seqs); +} + +TEST_CASE("A sequence count without matching values gives no custom sequence", "[ParameterUtils]") +{ + // The stored default: one placeholder value and a count of zero. + const std::vector placeholder{0}; + CHECK(get_other_layers_print_sequence(0, placeholder).empty()); + // The count raised on its own, as a command line override does. + CHECK(get_other_layers_print_sequence(1, placeholder).empty()); + // A group with a layer range but no extruder, alone and as two groups that divide evenly. + CHECK(get_other_layers_print_sequence(1, std::vector{1, 5}).empty()); + CHECK(get_other_layers_print_sequence(2, std::vector{1, 5, 6, 9}).empty()); + // A count that does not divide the values. + CHECK(get_other_layers_print_sequence(2, std::vector{1, 5, 2, 1, 6}).empty()); + // A negative count, and no values at all. + CHECK(get_other_layers_print_sequence(-1, std::vector{1, 5, 2}).empty()); + CHECK(get_other_layers_print_sequence(1, {}).empty()); +} From 23f82fa6310df58d5c78aa98566eba0b780da0fe Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:23:04 +0800 Subject: [PATCH 04/24] Count the Fake Printer's Close Frame When It Arrives (#17210) The fake printer counted a close frame when its read completed, which Beast does only after sending the reply and tearing the socket down. The agent's stop returns on the reply, and the test then releases the printer, which closes the socket. When that close beat the teardown, the read failed with another error, the frame went uncounted, and the test waited out its 10 s for nothing. The control callback sees the close frame before the reply goes out, so counting there leaves no window, and the wait helper is no longer needed. --- .../test_moonraker_printer_agent.cpp | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/tests/slic3rutils/test_moonraker_printer_agent.cpp b/tests/slic3rutils/test_moonraker_printer_agent.cpp index 283c06d1b3..7a347d958f 100644 --- a/tests/slic3rutils/test_moonraker_printer_agent.cpp +++ b/tests/slic3rutils/test_moonraker_printer_agent.cpp @@ -30,12 +30,12 @@ #include #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -242,13 +242,6 @@ public: return m_close_frames; } - // The printer answers a close frame before its own read completes, so the agent's stop can return first. - bool wait_for_close_frames(int count) - { - std::unique_lock lock(m_mutex); - return m_changed.wait_for(lock, 10s, [&] { return m_close_frames >= count; }); - } - // The answer to the gcodes directory listing, which reports the free space in disk_usage. Null leaves disk_usage out. void set_gcodes_listing(nlohmann::json disk_usage) { @@ -424,14 +417,17 @@ private: beast::flat_buffer message; bool reading = true; bool writing = false; + // Counted on arrival: the read completes only after the reply and the teardown, by which time the + // agent's stop may have returned and the test's release closed this socket, failing the read instead. + ws.control_callback([&](websocket::frame_type kind, beast::string_view) { + if (kind == websocket::frame_type::close) { + std::lock_guard lock(m_mutex); + ++m_close_frames; + } + }); std::function read_next = [&] { ws.async_read(message, [&](beast::error_code ec, std::size_t) { message.clear(); - if (ec == websocket::error::closed) { - std::lock_guard lock(m_mutex); - ++m_close_frames; - m_changed.notify_all(); - } if (ec) reading = false; else @@ -688,7 +684,6 @@ TEST_CASE("Stopping the status stream sends the printer a close frame", "[Moonra REQUIRE(f.printer.wait_for_ready_connections(1)); CHECK(f.stops_within(3s)); - CHECK(f.printer.wait_for_close_frames(1)); CHECK(f.printer.close_frames() == 1); } @@ -848,7 +843,7 @@ TEST_CASE("The status stream reports a printer's status over TLS", "[MoonrakerPr CHECK(reports.wait_for(1)); CHECK(f.stops_within(3s)); - CHECK(f.printer.wait_for_close_frames(1)); + CHECK(f.printer.close_frames() == 1); } TEST_CASE("The status stream sends no heartbeat while the printer has nothing new to report", "[MoonrakerPrinterAgent][StatusStream]") From 99fada6aab6df08e022382f29e6fb692e306fb5a Mon Sep 17 00:00:00 2001 From: Gazi Faysal Jubayer Date: Wed, 4 Nov 2026 17:27:10 +0600 Subject: [PATCH 05/24] Travel back from a lift at the lifted height, then descend (#16933) * Travel back from a lift at the lifted height, then descend After a tool change on the Bambu Lab prime tower, the nozzle is lifted at the tower and then travels to the next object. That travel is forced to set the layer Z, which sent it down the final branch of travel_to_xyz(): it cancelled the lift and emitted one combined XYZ move, so the nozzle sank over the print and left color streaks. When the nozzle is lifted and the target is lower, move in XY first and descend at the target, as the branch already does after a filament change. Fixes #14968 Co-Authored-By: Claude Opus 5.5 * Keep a lifted nozzle up over every travel that descends to the print A multi-point avoid-crossing or exclusion-volume travel now stays at the lifted height and descends only at its last point. The split descent also covers printers with an axis remap, takes its Z move from the target position, and is skipped when X and Y do not change. The test parses with GCodeReader and runs with arc fitting both off and on. Co-Authored-By: Claude Opus 5.5 * Check exclusion volumes from the height a lifted nozzle travels at Co-Authored-By: Claude Opus 5.5 * Merge the lifted and multi-point travel branches into one loop The 2-point travel, the lifted detour and the avoid-crossing detour now share one loop; a detour only moves to the layer height at its first point when the nozzle is not staying lifted. A new test lifts at each layer change of a concave part with avoid crossing walls on, so lifted detours of more than two points are checked for a nozzle that comes down before the end. Co-Authored-By: Claude Opus 5.5 * Keep an exclusion-volume detour lifted when its lift is still pending A retraction leaves its lift pending until the first leg of the travel. The interpolated-Z detour only checked for a lift already made, so it lifted on the first leg and then lowered at each later waypoint. A lift the first leg will make now skips the interpolation, so the detour stays lifted and descends at its last point. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Kris Austin --- src/libslic3r/GCode.cpp | 48 ++++---- src/libslic3r/GCodeWriter.cpp | 25 ++-- tests/fff_print/test_gcodewriter.cpp | 164 +++++++++++++++++++++++++++ 3 files changed, 202 insertions(+), 35 deletions(-) diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 9b90f7ccb5..abcdce56b2 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -8089,7 +8089,7 @@ LayerResult GCode::process_layer( m_nominal_z = entry.sub_z; // Use the same lazy-Z mechanism as change_layer(): set the flag so travel_to // fires even when m_last_pos coincides with the first extrusion point, - // ensuring Z reaches sub_z via the combined XY+Z move. + // ensuring Z reaches sub_z on the travel to it. m_need_change_layer_lift_z = true; for (ObjectByExtruder::Island &island : instance_to_print.object_by_extruder.islands) { @@ -10521,9 +10521,6 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string result.append(to_local_point(gcode_point)); return result; }; - const auto nominal_writer_z = [this]() { - return m_writer.get_position().z() - m_writer.get_zhop(); - }; const auto route_around_exclusion_volumes = [&]( Polyline &path, const std::optional &start_z_override, @@ -10532,7 +10529,8 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string return false; const double target_z = z == DBL_MAX ? m_nominal_z : z; - double route_start_z = start_z_override.value_or(nominal_writer_z()); + // A lifted nozzle travels at its lifted height, so the route is checked from there. + double route_start_z = start_z_override.value_or(m_writer.get_position().z()); double route_end_z = target_z; if (include_planned_lift) { const Vec2d destination_xy = this->point_to_gcode(path.back()); @@ -10681,13 +10679,15 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string gcode += m_writer.travel_to_xy(this->point_to_gcode(travel.points[i]), comment); } } else { - if (travel.size() == 2) { - // No extra movements emitted by avoid_crossing_perimeters, simply move to the end point with z change - const auto& dest2d = this->point_to_gcode(travel.points.back()); - Vec3d dest3d(dest2d(0), dest2d(1), z == DBL_MAX ? m_nominal_z : z); - gcode += m_writer.travel_to_xyz(dest3d, comment, m_need_change_layer_lift_z); - m_need_change_layer_lift_z = false; - } else if (exclusion_volume_travel_rerouted && z != DBL_MAX) { + const double target_z = z == DBL_MAX ? m_nominal_z : z; + // A lifted nozzle keeps its height over the whole detour and descends only at the last + // point, so it never sinks over the print. + const bool stay_lifted = m_writer.get_zhop() > EPSILON && m_writer.get_position().z() > target_z + EPSILON; + // A lift left pending by the retraction happens on the first leg, so that detour is lifted too. + const Vec2d first2d = this->point_to_gcode(travel.points[1]); + const bool lift_pending = + m_writer.planned_travel_z(Vec3d(first2d.x(), first2d.y(), target_z), m_need_change_layer_lift_z).second > target_z + EPSILON; + if (exclusion_volume_travel_rerouted && z != DBL_MAX && !stay_lifted && !lift_pending) { // Preserve the original sloped-Z move over the longer detour. // The router activates every volume touched by the complete Z // range, so this interpolation remains conservative. @@ -10706,23 +10706,19 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string m_need_change_layer_lift_z = false; } } else { - // Extra movements emitted by avoid_crossing_perimeters, lift the z to normal height at the beginning, then apply the z - // ratio at the last point + // Extra movements emitted by avoid_crossing_perimeters move to the layer height at the first point, + // unless the nozzle stays lifted. The target Z is applied at the last point. + const bool layer_z_first = travel.size() > 2 && !stay_lifted; for (size_t i = 1; i < travel.size(); ++i) { - if (i == 1) { - // Lift to normal z at beginning - Vec2d dest2d = this->point_to_gcode(travel.points[i]); - Vec3d dest3d(dest2d(0), dest2d(1), m_nominal_z); - gcode += m_writer.travel_to_xyz(dest3d, comment, m_need_change_layer_lift_z); + const Vec2d dest2d = this->point_to_gcode(travel.points[i]); + if (i == 1 && layer_z_first) { + gcode += m_writer.travel_to_xyz(Vec3d(dest2d.x(), dest2d.y(), m_nominal_z), comment, m_need_change_layer_lift_z); + m_need_change_layer_lift_z = false; + } else if (i == travel.size() - 1 && (z != DBL_MAX || !layer_z_first)) { + gcode += m_writer.travel_to_xyz(Vec3d(dest2d.x(), dest2d.y(), target_z), comment, m_need_change_layer_lift_z); m_need_change_layer_lift_z = false; - } else if (z != DBL_MAX && i == travel.size() - 1) { - // Apply z_ratio for the very last point - Vec2d dest2d = this->point_to_gcode(travel.points[i]); - Vec3d dest3d(dest2d(0), dest2d(1), z); - gcode += m_writer.travel_to_xyz(dest3d, comment); } else { - // For all points in between, no z change - gcode += m_writer.travel_to_xy(this->point_to_gcode(travel.points[i]), comment); + gcode += m_writer.travel_to_xy(dest2d, comment); } } } diff --git a/src/libslic3r/GCodeWriter.cpp b/src/libslic3r/GCodeWriter.cpp index 761e89293d..20c2e45691 100644 --- a/src/libslic3r/GCodeWriter.cpp +++ b/src/libslic3r/GCodeWriter.cpp @@ -1104,28 +1104,35 @@ std::string GCodeWriter::travel_to_xyz(const Vec3d &point, const std::string &co this->set_current_position_clear(true); return this->travel_to_xy(to_2d(point)); } - else { - /* In all the other cases, we perform an actual XYZ move and cancel - the lift. */ - m_lifted = 0; - } + // A lifted nozzle that has to end lower travels at the lifted height and descends at the + // target, so it never sinks while crossing the print. + const bool descend_after_xy = m_lifted > EPSILON && point(2) < m_pos(2) - EPSILON && this->is_current_position_clear() && + (to_2d(point) - to_2d(m_pos)).norm() > EPSILON; + /* In all the other cases, we move to the target Z and cancel the lift: in a single XYZ move, + or XY first and then Z after a filament change or when coming down from a lift. */ + m_lifted = 0; //BBS: take plate offset into consider Vec3d point_on_plate = { dest_point(0) - m_x_offset, dest_point(1) - m_y_offset, dest_point(2) }; std::string out_string; GCodeG1Formatter w(config.high_precision_gcode.value); - if (has_axis_remap()) { + if (has_axis_remap() && !descend_after_xy) { // Remap may couple XY with Z; emit full XYZ in machine coordinates. w.emit_xyz(apply_axis_remap(point_on_plate)); w.emit_f(final_travel_speed * 60.0); w.emit_comment(GCodeWriter::full_gcode_comment, comment); out_string = w.string(); - } else if (!this->is_current_position_clear()) + } else if (!this->is_current_position_clear() || descend_after_xy) { - //force to move xy first then z after filament change - w.emit_xy(Vec2d(point_on_plate.x(), point_on_plate.y())); + //force to move xy first then z after filament change, or when coming down from a lift + if (has_axis_remap()) + w.emit_xyz(apply_axis_remap(Vec3d(point_on_plate.x(), point_on_plate.y(), m_pos(2)))); + else + w.emit_xy(Vec2d(point_on_plate.x(), point_on_plate.y())); w.emit_f(final_travel_speed * 60.0); w.emit_comment(GCodeWriter::full_gcode_comment, comment); + // The Z move happens at the target, so it is emitted and timed from there. + m_pos = Vec3d(dest_point.x(), dest_point.y(), m_pos(2)); out_string = w.string() + _travel_to_z(point_on_plate.z(), comment); } else { GCodeG1Formatter w(config.high_precision_gcode.value); diff --git a/tests/fff_print/test_gcodewriter.cpp b/tests/fff_print/test_gcodewriter.cpp index 4183db735f..a42cd2474d 100644 --- a/tests/fff_print/test_gcodewriter.cpp +++ b/tests/fff_print/test_gcodewriter.cpp @@ -7,6 +7,7 @@ #include "libslic3r/PrintConfig.hpp" #include "libslic3r/BoundingBox.hpp" #include "libslic3r/Point.hpp" +#include "libslic3r/TriangleMesh.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/Extruder.hpp" #include "libslic3r/Flow.hpp" @@ -2041,3 +2042,166 @@ TEST_CASE("Initial filament start G-code tolerates a list shorter than the filam REQUIRE_NOTHROW(Slic3r::Test::gcode(print)); } + +// Counts the travels (no E) that move in X or Y while lowering Z: each drags the nozzle down over the print. +static int count_descending_travels(const std::string &gcode) +{ + int descending_travels = 0; + GCodeReader reader; + reader.parse_buffer(gcode, [&descending_travels](GCodeReader &self, const GCodeReader::GCodeLine &line) { + if (line.travel() && line.dist_Z(self) < -EPSILON && (line.dist_X(self) != 0.f || line.dist_Y(self) != 0.f)) { + UNSCOPED_INFO(line.raw()); + ++descending_travels; + } + }); + return descending_travels; +} + +// Counts the travels made after the nozzle came straight down, before it printed or rose again: +// the nozzle dropped from its lift short of the destination and crosses the print low. Moves before +// the first extrusion come down from the start G-code and are not counted. +static int count_travels_after_descent(const std::string &gcode) +{ + int travels = 0; + bool printed = false; + bool descended = false; + GCodeReader reader; + reader.parse_buffer(gcode, [&travels, &printed, &descended](GCodeReader &self, const GCodeReader::GCodeLine &line) { + if (!line.cmd_is("G0") && !line.cmd_is("G1") && !line.cmd_is("G2") && !line.cmd_is("G3")) + return; + const bool xy = line.dist_X(self) != 0.f || line.dist_Y(self) != 0.f; + if (line.has(E) || line.dist_Z(self) > EPSILON) { + printed |= xy && line.extruding(self); + descended = false; + } else if (xy) { + if (descended) { + UNSCOPED_INFO(line.raw()); + ++travels; + } + descended = false; + } else if (line.dist_Z(self) < -EPSILON) { + descended = printed; + } + }); + return travels; +} + +TEST_CASE("A lifted nozzle reaches its target height only after the travel back to the print", "[GCodeWriter]") { + // Two filaments on one nozzle with a prime tower: after each tool change the nozzle is + // lifted at the tower and travels back to the object. + const int lift = GENERATE(int(zhtNormal), int(zhtSlope), int(zhtSpiral), int(zhtAuto)); + const std::string arc_fitting = GENERATE("disabled", "enabled"); + CAPTURE(lift, arc_fitting); + DynamicPrintConfig config = Test::multifilament_config(2, { + {"filament_self_index", "1,2"}, + {"filament_extruder_variant", "Direct Drive Standard;Direct Drive Standard"}, + {"z_hop", "0.4"}, + {"retract_lift_below", "0"}, + {"enable_prime_tower", 1}, + {"wipe_tower_x", "50"}, + {"wipe_tower_y", "50"}, + {"skirt_loops", 0}, + {"brim_type", "no_brim"}, + // A spiral lift is written as G2/G3 when arc fitting is on. + {"enable_arc_fitting", arc_fitting}, + }); + config.option("z_hop_types", true)->values = {lift}; + Print print; + Model model; + print.is_BBL_printer() = true; + const std::vector> overrides{{{"extruder", "1"}}, {{"extruder", "2"}}}; + Test::init_print({Test::cube(20), Test::cube(20)}, print, model, config, &overrides); + + CHECK(count_descending_travels(Test::gcode(print)) == 0); +} + +TEST_CASE("A lifted nozzle keeps its height over a detour around a concave part", "[GCodeWriter]") { + // A Bambu Lab printer lifts at each layer change, and avoiding crossing walls detours the travel + // to the next layer's start around the notch of the L. + const int lift = GENERATE(int(zhtNormal), int(zhtSlope), int(zhtSpiral)); + CAPTURE(lift); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + {"z_hop", "0.4"}, + {"retract_lift_below", "0"}, + {"retract_when_changing_layer", "1"}, + {"reduce_crossing_wall", 1}, + {"seam_position", "random"}, + {"enable_arc_fitting", "disabled"}, + {"skirt_loops", 0}, + {"brim_type", "no_brim"}, + }); + config.option("z_hop_types", true)->values = {lift}; + Print print; + Model model; + print.is_BBL_printer() = true; + Test::init_print({TestMesh::L}, print, model, config); + + const std::string gcode = Test::gcode(print); + CHECK(count_descending_travels(gcode) == 0); + CHECK(count_travels_after_descent(gcode) == 0); +} + +TEST_CASE("A lifted nozzle keeps its height over an exclusion-volume detour", "[GCodeWriter]") { + // A collision volume stands between two parts, so the travel between them is rerouted around it. + // The retraction before that travel leaves its lift pending, and the scarf seam of the outer wall, + // printed first, gives the travel an explicit Z below the layer. + const int lift = GENERATE(int(zhtNormal), int(zhtSlope), int(zhtSpiral)); + CAPTURE(lift); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + {"bed_exclude_volumes", "0..10;45x10,55x10,55x90,45x90"}, + {"z_hop", "0.4"}, + {"retract_lift_below", "0"}, + {"seam_slope_type", "all"}, + {"seam_slope_conditional", 0}, + {"wall_sequence", "outer wall/inner wall"}, + {"enable_arc_fitting", "disabled"}, + {"skirt_loops", 0}, + {"brim_type", "no_brim"}, + }); + config.option("z_hop_types", true)->values = {lift}; + std::vector meshes; + for (const float x : {20.f, 70.f}) { + TriangleMesh mesh = make_cube(10., 10., 2.); + mesh.translate(x, 45.f, 0.f); + meshes.push_back(std::move(mesh)); + } + Print print; + Model model; + Test::init_print(std::move(meshes), print, model, config, nullptr, false); + + const std::string gcode = Test::gcode(print); + // Short unlifted travels still slope down to a scarf start, so only travels after a descent are checked. + CHECK(count_travels_after_descent(gcode) == 0); +} + +TEST_CASE("A lifted travel that ends lower descends only at its destination", "[GCodeWriter]") { + // Reverse X maps the X and Z of a move together, so the descent re-emits X and Y. + const bool remap = GENERATE(false, true); + // Forced: a layer change. Not forced: a destination below the layer, like a scarf seam start. + const bool force_z = GENERATE(false, true); + CAPTURE(remap, force_z); + GCodeWriter writer; + configure_lift_writer(writer); + if (remap) { + writer.set_axis_remap(6, 1, 2); + writer.set_build_volume_max(Vec3d(250.0, 250.0, 250.0)); + } + // The whole output is parsed, so the reader starts from the position the writer is at. + std::string gcode = writer.travel_to_xyz(Vec3d(20.0, 20.0, 5.0)); + gcode += writer.lazy_lift(LiftType::NormalLift); + gcode += writer.travel_to_xyz(Vec3d(30.0, 30.0, 5.0)); + REQUIRE_THAT(writer.get_position().z(), Catch::Matchers::WithinAbs(5.4, EPSILON)); + + const double target_z = force_z ? 5.0 : 4.9; + gcode += writer.travel_to_xyz(Vec3d(40.0, 40.0, target_z), "", force_z); + INFO(gcode); + CHECK(count_descending_travels(gcode) == 0); + CHECK_THAT(writer.get_position().z(), Catch::Matchers::WithinAbs(target_z, EPSILON)); + + // Already above the destination, the descent is a single move. + writer.lazy_lift(LiftType::NormalLift); + writer.travel_to_xyz(Vec3d(50.0, 50.0, target_z)); + CHECK(count_g1(writer.travel_to_xyz(Vec3d(50.0, 50.0, target_z), "", true)) == 1); +} From 88c4c1e915781acf6d07f229b5459b8316712651 Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Tue, 3 Nov 2026 17:22:52 -0300 Subject: [PATCH 06/24] Print gap fill after the lines next to it in fills that keep their order insert_gap_fill() put each piece of gap fill wherever it added the least travel, which could be before the extrusions bordering it: the centre gap of a Spiral Inset printed before the spiral that starts there, and gaps where spirals meet printed before the later spiral. Each piece now only goes after the last extrusion of its fill that passes within half its widest width and a line spacing of it. --- docs/HLSD/travel-optimization.md | 16 ++++++---- src/libslic3r/Fill/FillBase.cpp | 35 ++++++++++++++++++++++ tests/fff_print/test_fill.cpp | 51 ++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 6 deletions(-) diff --git a/docs/HLSD/travel-optimization.md b/docs/HLSD/travel-optimization.md index 79774f7ff9..09e1c78efd 100644 --- a/docs/HLSD/travel-optimization.md +++ b/docs/HLSD/travel-optimization.md @@ -108,12 +108,16 @@ order, such as monotonic, would print all of its lines and then come back for every piece of gap fill, most of which lies at the walls where the lines end. So each piece, in turn, goes between the two extrusions of the fill where it -adds the least travel, flipped when that is shorter. A closed piece counts from -its point nearest the nozzle, where `GCode::extrude_loop()` starts it. The two -ends of the fill cost nothing, since the travel to and from them depends on what -is printed before and after. The fill's own extrusions keep their order and -direction, so a monotonic fill stays monotonic. When the result travels no less -than the gap fill printed after the lines in its own order, that order is kept. +adds the least travel, flipped when that is shorter. A piece fills what the +extrusions around it left, so it only goes after the last extrusion of the fill +that passes within half its widest width and a line spacing of it: a spiral +that starts at a gap in its middle prints that gap when it is done. A closed +piece counts from its point nearest the nozzle, where `GCode::extrude_loop()` +starts it. The two ends of the fill cost nothing, since the travel to and from +them depends on what is printed before and after. The fill's own extrusions keep +their order and direction, so a monotonic fill stays monotonic. When the result +travels no less than the gap fill printed after the lines in its own order, that +order is kept. ## The search diff --git a/src/libslic3r/Fill/FillBase.cpp b/src/libslic3r/Fill/FillBase.cpp index 6338bc3208..ce35b145d2 100644 --- a/src/libslic3r/Fill/FillBase.cpp +++ b/src/libslic3r/Fill/FillBase.cpp @@ -252,6 +252,36 @@ static void insert_gap_fill(const ThickPolylines &gaps, const Flow &flow, Extrus return sum; }; + // The last extrusion of the fill that borders each gap: the gap fill goes after it. + std::vector after(gaps.size(), npos); + { + Lines lines; + std::vector owner; + for (size_t i = 0; i < entities.size(); ++ i) + for (const Polyline &pl : entities[i]->as_polylines()) + for (const Line &line : pl.lines()) { + lines.push_back(line); + owner.push_back(i); + } + const AABBTreeLines::LinesDistancer distancer(std::move(lines)); + const double spacing = flow.scaled_spacing(); + for (size_t gap = 0; gap < gaps.size(); ++ gap) { + const ThickPolyline &pl = gaps[gap]; + if (pl.width.empty()) + continue; + const double radius = 0.5 * *std::max_element(pl.width.begin(), pl.width.end()) + spacing; + for (size_t j = 0; j + 1 < pl.points.size(); ++ j) { + const Vec2d a = pl.points[j].cast(); + const Vec2d b = pl.points[j + 1].cast(); + const size_t steps = std::max(1, size_t(std::ceil((b - a).norm() / (0.5 * spacing)))); + for (size_t k = 0; k <= steps; ++ k) + for (size_t line : distancer.all_lines_in_radius(Point((a + double(k) / double(steps) * (b - a)).cast()), radius)) + if (after[gap] == npos || owner[line] > after[gap]) + after[gap] = owner[line]; + } + } + } + std::vector items, appended; items.reserve(entities.size() + gaps.size()); for (const ExtrusionEntity *ee : entities) @@ -262,7 +292,12 @@ static void insert_gap_fill(const ThickPolylines &gaps, const Flow &flow, Extrus double best = std::numeric_limits::max(); size_t best_slot = 0; Item best_item{}; + size_t extrusions_before = 0; for (size_t slot = 0; slot <= items.size(); ++ slot) { + if (slot > 0 && items[slot - 1].gap == npos) + ++ extrusions_before; + if (after[gap] != npos && extrusions_before <= after[gap]) + continue; const Point *prev = slot > 0 ? &items[slot - 1].out : nullptr; const Point *next = slot < items.size() ? &items[slot].in : nullptr; auto consider = [&](const Point &in, const Point &out, bool reversed) { diff --git a/tests/fff_print/test_fill.cpp b/tests/fff_print/test_fill.cpp index f6e7c55b4b..523bd55b88 100644 --- a/tests/fff_print/test_fill.cpp +++ b/tests/fff_print/test_fill.cpp @@ -13,6 +13,7 @@ #include #include "libslic3r/Polygon.hpp" #include "libslic3r/ExtrusionEntity.hpp" +#include "libslic3r/ExtrusionEntityCollection.hpp" #include "libslic3r/Line.hpp" #include "libslic3r/ExPolygon.hpp" #include "libslic3r/TriangleMesh.hpp" @@ -2505,3 +2506,53 @@ TEST_CASE("Monotonic line top surfaces print their gap fill next to their lines REQUIRE(gap_fills > 0); CHECK(gap_fills_before_a_line > 0); } + +// Orca: counts the gap fills of the fills that keep their order, and those printed before an extrusion of the fill they touch. +static std::pair gap_fills_and_those_before_an_extrusion_they_touch(const Print &print) +{ + size_t gap_fills = 0, before = 0; + for (const Layer *layer : print.objects().front()->layers()) + for (const LayerRegion *region : layer->regions()) + for (const ExtrusionEntity *entity : region->fills.entities) { + auto *fill = dynamic_cast(entity); + if (fill == nullptr || ! fill->no_sort) + continue; + for (size_t i = 0; i < fill->entities.size(); ++ i) { + if (fill->entities[i]->role() != erGapFill) + continue; + ++ gap_fills; + const Polygons gap = fill->entities[i]->polygons_covered_by_width(float(scale_(0.05))); + before += std::any_of(fill->entities.begin() + i + 1, fill->entities.end(), [&gap](const ExtrusionEntity *ee) { + return ee->role() != erGapFill && ! intersection(gap, ee->polygons_covered_by_width()).empty(); + }); + } + } + return { gap_fills, before }; +} + +TEST_CASE("Gap fill of a fill that keeps its order prints after the extrusions it touches", "[Fill]") +{ + using Slic3r::Test::TestMesh; + const auto [pattern_key, pattern, target] = GENERATE(table({ + { "internal_solid_infill_pattern", "spiralinset", "everywhere" }, + { "top_surface_pattern", "concentric", "topbottom" }, + { "top_surface_pattern", "monotonic", "topbottom" }, + { "top_surface_pattern", "monotonicline", "topbottom" }, + })); + // The slanted legs of the V and the hole of the cube leave gap fill next to the lines of each pattern. + const TestMesh mesh = GENERATE(TestMesh::V, TestMesh::cube_with_hole); + auto config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({{pattern_key, pattern}, + {"gap_fill_target", target}, + {"filter_out_gap_fill", 0}, + {"layer_height", 0.2}, + {"initial_layer_print_height", 0.2}}); + Print print; + Model model; + Slic3r::Test::init_print({mesh}, print, model, config); + print.process(); + const auto [gap_fills, before] = gap_fills_and_those_before_an_extrusion_they_touch(print); + INFO(pattern << " on " << Slic3r::Test::mesh_names.at(mesh)); + REQUIRE(gap_fills > 0); + CHECK(before == 0); +} From 9afa96e92f720436d6d3518fb1165b5c8b322998 Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Tue, 3 Nov 2026 20:13:34 -0300 Subject: [PATCH 07/24] Fill internal solid Spiral Inset with Arachne walls Internal solid infill fell back to fixed width loops so that Arachne's open walls would not be printed after an outward spiral, which ends at the edge and travelled back to the centre for them. Fixed width loops leave strips up to two lines wide in the middle of an island and wedges where it branches: on calicat.3mf they need 218 mm of gap fill against 53 mm with Arachne, and with gap fill off for internal solid those gaps stay empty. Keep Arachne for every solid surface and print each open wall at the centre end of the nearest spiral instead: before an outward spiral, which starts there, and after an inward one, which ends there. --- src/libslic3r/Fill/FillSpiralInset.cpp | 71 +++++++++++++++++++++----- tests/fff_print/test_fill.cpp | 50 ++++++++++++++++++ 2 files changed, 108 insertions(+), 13 deletions(-) diff --git a/src/libslic3r/Fill/FillSpiralInset.cpp b/src/libslic3r/Fill/FillSpiralInset.cpp index 5931e813cf..ff811aa920 100644 --- a/src/libslic3r/Fill/FillSpiralInset.cpp +++ b/src/libslic3r/Fill/FillSpiralInset.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -352,16 +353,6 @@ void FillSpiralInset::_fill_surface_single(const FillParams& params, assert(params.use_arachne); assert(this->print_config != nullptr && this->print_object_config != nullptr); - // Internal solid infill must not add Arachne's standalone thin walls: one of those walls can - // become the extra centre point after the spiral has finished. Top and bottom surfaces keep - // Arachne, including the centre plug handled by generate_spiral_insets(). - if (params.extrusion_role == erSolidInfill) { - Polylines polylines; - this->_fill_surface_single(params, thickness_layers, direction, expolygon, polylines); - append(thick_polylines_out, to_thick_polylines(std::move(polylines), scaled(this->spacing))); - return; - } - // Only a solid surface is worth the variable width walls; a sparse one falls back to plain loops. if (params.density <= 0.9999f || params.dont_adjust) { Polylines polylines; @@ -440,11 +431,65 @@ void FillSpiralInset::_fill_surface_single(const FillParams& params, if (parent[i] < 0) descend(int(i)); - ThickPolylines spiral_result = + ThickPolylines spirals = generate_spiral_insets(params, ordered, outlines, min_spacing, expolygon); + if (spirals.empty()) { + append(thick_polylines_out, std::move(open_walls)); + return; + } - append(thick_polylines_out, std::move(spiral_result)); - append(thick_polylines_out, std::move(open_walls)); + // The open walls lie mostly down the middle of an island, so each one prints at the centre end + // of the nearest spiral, before an outward spiral and after an inward one, rather than after + // every spiral, which brought the nozzle back across the surface for them. + const bool outward = params.fill_order != SurfaceFillOrder::Inward; + auto centre = [outward](const ThickPolyline& spiral) { return outward ? spiral.first_point() : spiral.last_point(); }; + auto dist2 = [](const Point& a, const Point& b) { return (a - b).cast().squaredNorm(); }; + std::vector beside(spirals.size()); + for (ThickPolyline& wall : open_walls) { + size_t nearest = 0; + double best = std::numeric_limits::max(); + for (size_t k = 0; k < spirals.size(); ++k) { + const Point c = centre(spirals[k]); + if (const double d = std::min(dist2(wall.first_point(), c), dist2(wall.last_point(), c)); d < best) { + best = d; + nearest = k; + } + } + beside[nearest].emplace_back(std::move(wall)); + } + + for (size_t k = 0; k < spirals.size(); ++k) { + // Chain the walls away from the centre end, nearest end first. + ThickPolylines& walls = beside[k]; + Point pos = centre(spirals[k]); + for (size_t i = 0; i < walls.size(); ++i) { + size_t next = i; + bool flip = false; + double best = std::numeric_limits::max(); + for (size_t j = i; j < walls.size(); ++j) + for (const bool f : {false, true}) + if (const double d = dist2(f ? walls[j].last_point() : walls[j].first_point(), pos); d < best) { + best = d; + next = j; + flip = f; + } + std::swap(walls[i], walls[next]); + if (flip) + walls[i].reverse(); + pos = walls[i].last_point(); + } + if (outward) { + // Printed backwards, the chain ends at the centre, where the spiral starts. + std::reverse(walls.begin(), walls.end()); + for (ThickPolyline& wall : walls) + wall.reverse(); + append(thick_polylines_out, std::move(walls)); + thick_polylines_out.emplace_back(std::move(spirals[k])); + } else { + thick_polylines_out.emplace_back(std::move(spirals[k])); + append(thick_polylines_out, std::move(walls)); + } + } } } // namespace Slic3r diff --git a/tests/fff_print/test_fill.cpp b/tests/fff_print/test_fill.cpp index 523bd55b88..843e16c209 100644 --- a/tests/fff_print/test_fill.cpp +++ b/tests/fff_print/test_fill.cpp @@ -1059,6 +1059,56 @@ TEST_CASE("Spiral inset fill closes the gaps with variable width walls", "[Fill] CHECK(2 * spirals < walls_across); } +TEST_CASE("Spiral inset fill prints the open walls at the centre end of the spiral", "[Fill][Regression]") +{ + // Arachne leaves the middle of this ellipse as an open wall. Printed after an outward spiral, which + // ends at the edge, it sent the nozzle back across the surface to the centre. + const double spacing = 0.45; + Slic3r::Polygon ellipse; + for (int i = 0; i < 90; ++i) { + const double angle = 2.0 * PI * i / 90.0; + ellipse.points.emplace_back(Slic3r::Point::new_scale(10 * std::cos(angle), 5 * std::sin(angle))); + } + const Slic3r::SurfaceFillOrder order = GENERATE(Slic3r::SurfaceFillOrder::Default, Slic3r::SurfaceFillOrder::Inward); + CAPTURE(int(order)); + + Slic3r::PrintConfig print_config; + Slic3r::PrintObjectConfig object_config; + const Slic3r::Surface surface(Slic3r::stTop, Slic3r::ExPolygon(ellipse)); + auto fill = [&](Slic3r::ExtrusionRole role) { + std::unique_ptr filler(Slic3r::Fill::new_from_type("spiralinset")); + filler->spacing = spacing; + filler->overlap = 0.5 * spacing; + filler->print_config = &print_config; + filler->print_object_config = &object_config; + + Slic3r::FillParams params; + params.density = 1.f; + params.dont_adjust = false; + params.layer_height = 0.2; + params.use_arachne = true; + params.extrusion_role = role; + params.fill_order = order; + return filler->fill_surface_arachne(&surface, params); + }; + + const Slic3r::ThickPolylines paths = fill(Slic3r::erTopSolidInfill); + REQUIRE(paths.size() > 1); + // The spiral goes last when it runs outwards and first when it runs inwards. + const auto spiral = std::max_element(paths.begin(), paths.end(), [](const Slic3r::ThickPolyline &a, const Slic3r::ThickPolyline &b) { + return a.length() < b.length(); + }); + CHECK(spiral == (order == Slic3r::SurfaceFillOrder::Inward ? paths.begin() : paths.end() - 1)); + + // Internal solid infill gets the same walls rather than fixed width loops, which leave gaps. + const Slic3r::ThickPolylines solid = fill(Slic3r::erSolidInfill); + REQUIRE(solid.size() == paths.size()); + for (size_t i = 0; i < paths.size(); ++i) { + CHECK(solid[i].points == paths[i].points); + CHECK(solid[i].width == paths[i].width); + } +} + TEST_CASE("Honeycomb infill rounds its cell corners with the smooth factor", "[Fill]") { // A cell whose sides are several times the line width, so that the corners have room to be rounded. From 2873db9e06c55f1bd9746788b1d4fd86549cd97c Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Tue, 3 Nov 2026 20:46:38 -0300 Subject: [PATCH 08/24] Draw the Spiral Inset icon as a square spiral that follows the outline --- resources/images/param_spiralinset.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/images/param_spiralinset.svg b/resources/images/param_spiralinset.svg index 6ec1ab36aa..38020c9578 100644 --- a/resources/images/param_spiralinset.svg +++ b/resources/images/param_spiralinset.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file From d607d7f4ad2723693c8a7ae6607a1dea319efcdd Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Wed, 4 Nov 2026 09:30:34 -0300 Subject: [PATCH 09/24] Fix gap infill printing with the outer wall filament with classic walls (#17229) --- src/libslic3r/GCode/ToolOrdering.cpp | 4 +++- tests/fff_print/test_multifilament.cpp | 31 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/libslic3r/GCode/ToolOrdering.cpp b/src/libslic3r/GCode/ToolOrdering.cpp index e5c36d34c7..6f7cdce70f 100644 --- a/src/libslic3r/GCode/ToolOrdering.cpp +++ b/src/libslic3r/GCode/ToolOrdering.cpp @@ -157,7 +157,9 @@ static unsigned int region_filament(const ExtrusionEntityCollection &extrusions, return config.bottom_surface_filament_id.value; return config.internal_solid_filament_id.value; } - // Walls, and the gap fill between them. + // Orca: Classic gap fill lies inside the outer wall. With one wall, the inner wall filament is not in use. + if (extrusions.role() == erGapFill) + return config.wall_loops.value > 1 ? config.inner_wall_filament_id.value : config.outer_wall_filament_id.value; const ExtrusionEntitiesPtr &walls = extrusions.entities; return !walls.empty() && std::all_of(walls.begin(), walls.end(), [](const ExtrusionEntity *ee) { return is_inner_wall(*ee); }) ? config.inner_wall_filament_id.value : config.outer_wall_filament_id.value; diff --git a/tests/fff_print/test_multifilament.cpp b/tests/fff_print/test_multifilament.cpp index 049e3b4494..2e11470d34 100644 --- a/tests/fff_print/test_multifilament.cpp +++ b/tests/fff_print/test_multifilament.cpp @@ -492,6 +492,37 @@ TEST_CASE("Gap fill between walls does not schedule the sparse infill filament", CHECK(idle_tool_changes(gcode) == 0); } +// Gap fill lies inside the outer wall, so choosing the outer wall filament must not move it. +TEST_CASE("Gap fill between walls prints with the inner wall filament", "[MultiFilament]") +{ + const std::string gcode = slice({ make_cube(20., 1.9, 5.) }, + multifilament_config(2, { + { "wall_generator", "classic" }, + { "wall_loops", 2 }, + { "outer_wall_filament_id", 2 }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + })); + REQUIRE(tools_for_feature(gcode, "Gap infill") == std::set{ 0 }); + CHECK(tools_for_feature(gcode, "Outer wall") == std::set{ 1 }); + CHECK(idle_tool_changes(gcode) == 0); +} + +// One wall leaves a 1.1mm plate a gap between its two sides, and the inner wall filament is not in use. +TEST_CASE("Gap fill with a single wall does not use the inner wall filament", "[MultiFilament]") +{ + const std::string gcode = slice({ make_cube(20., 1.1, 5.) }, + multifilament_config(2, { + { "wall_generator", "classic" }, + { "wall_loops", 1 }, + { "inner_wall_filament_id", 2 }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + })); + REQUIRE(tools_for_feature(gcode, "Gap infill") == std::set{ 0 }); + CHECK(idle_tool_changes(gcode) == 0); +} + // A 20x20x2mm base carrying a 0.5mm fin: the fin's layers fit a single wall, so they must not switch to the inner // wall filament the base uses. TEST_CASE("A layer without inner walls does not switch to the inner wall filament", "[MultiFilament]") From 3bda653448cf14faa52b44b3b556a461796d1c22 Mon Sep 17 00:00:00 2001 From: anjis Date: Wed, 4 Nov 2026 20:31:08 +0800 Subject: [PATCH 10/24] Fix Type 1 wipe tower filament statistics for non-Bambu printers (#17199) --- docs/HLSD/prime-tower-sparse-layers.md | 18 +++---- src/libslic3r/GCode.cpp | 23 --------- src/libslic3r/GCode.hpp | 7 +-- src/libslic3r/GCode/WipeTower.cpp | 3 -- src/libslic3r/GCode/WipeTower2.cpp | 3 -- src/libslic3r/Print.cpp | 3 ++ tests/fff_print/test_wipe_tower.cpp | 67 +++++++++++++++++++++----- 7 files changed, 65 insertions(+), 59 deletions(-) diff --git a/docs/HLSD/prime-tower-sparse-layers.md b/docs/HLSD/prime-tower-sparse-layers.md index 47a0ff4163..5175c4239e 100644 --- a/docs/HLSD/prime-tower-sparse-layers.md +++ b/docs/HLSD/prime-tower-sparse-layers.md @@ -167,18 +167,12 @@ its accumulation points; Type 2 guards the equivalent block in `finish_layer`, which also stops a merged-away layer from adding height of its own โ€” the layer that prints the run carries all of it. -A merged layer is the only case where the tower's layer height differs from the -object layer it sits on, and therefore the only case where the height the -exporter already emitted for that layer is wrong for the tower. Both generators -do declare a height, but each hardcodes a tag dialect โ€” the block tower forces -the BBL tag, the other writes the compatible one โ€” while the G-code processor -reads only the tag its printer uses. On a non-BBL printer with a Type 1 tower the -declaration is dropped, and the merged layer is drawn and costed as a thin one. -`WipeTowerIntegration::tower_height_tag` therefore declares it at export time, -where the printer is known, and only when the tower's own G-code does not already -carry the tag that will be read. The object's height returns on the next object -path, because emission forces the processor role to the tower on any layer that -carries one. +A merged tower layer can be thicker than the object layer it sits on. Both +generators declare the tower's layer height in their own G-code blocks. +`Print::_make_wipe_tower` selects the printer's tag format before either +generator runs, so the G-code processor recognises the tower's height and +extrusion role. The object's height returns on the next object path, because +emission forces the processor role to the tower on any layer that carries one. ## Constraints diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index abcdce56b2..25052308c1 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -1070,27 +1070,6 @@ static std::vector get_path_of_change_filament(const Print& print) return gcode; } - // A folded tower layer is thicker than the object layer it sits on, so the height process_layer - // emitted is not the tower's. Both writers declare one, but each hardcodes a tag dialect - Type 1 - // forces s_IsBBLPrinter and writes "; LAYER_HEIGHT:", Type 2 writes ";HEIGHT:" - and the processor - // reads only its printer's, so a Type 1 tower on a non-BBL printer loses it and the merged layer - // is drawn and costed as a thin one. Declare it here, where the printer is known, unless the tower - // already wrote the right tag. _extrude puts the object's height back on the next object path, - // since process_layer forces the role to erWipeTower on any layer with a tower. - std::string WipeTowerIntegration::tower_height_tag(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr, - const std::string &tcr_gcode) const - { - const std::string tag = ";" + GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Height); - if (! m_sparse_layers_combined || std::abs(gcodegen.m_last_height - tcr.layer_height) <= EPSILON || - tcr_gcode.find(tag) != std::string::npos) - return {}; - // Keep m_last_height what the G-code last declared, so a second visit does not repeat it. - gcodegen.m_last_height = tcr.layer_height; - char buf[64]; - sprintf(buf, "%s%g\n", tag.c_str(), tcr.layer_height); - return buf; - } - // FanMover consumes these markers (and drops them) to avoid splitting a G1 inside custom gcode. // Only written when FanMover runs, the same gate as its construction in GCode::process_layers. static std::string wrap_custom_gcode_for_fan_mover(const FullPrintConfig &config, const std::string &gcode) @@ -1640,7 +1619,6 @@ static std::vector get_path_of_change_filament(const Print& print) config.set_key_value("filament_start_gcode", new ConfigOptionString(start_filament_gcode_str)); std::string tcr_gcode, tcr_escaped_gcode = gcodegen.placeholder_parser_process("tcr_rotated_gcode", tcr_rotated_gcode, new_filament_id, &config); unescape_string_cstyle(tcr_escaped_gcode, tcr_gcode); - gcode += tower_height_tag(gcodegen, tcr, tcr_gcode); gcode += tcr_gcode; // Count the toolchange only when the emitted block really changed the tool โ€” // tower visits without a filament change must not advance the ordinal. @@ -1955,7 +1933,6 @@ static std::vector get_path_of_change_filament(const Print& print) std::string tcr_gcode, tcr_escaped_gcode = gcodegen.placeholder_parser_process("tcr_rotated_gcode", tcr_rotated_gcode, new_extruder_id, &config); unescape_string_cstyle(tcr_escaped_gcode, tcr_gcode); - gcode += tower_height_tag(gcodegen, tcr, tcr_gcode); gcode += tcr_gcode; check_add_eol(toolchange_gcode_str); diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index 9d9f12877b..9a68c3a429 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -127,8 +127,7 @@ public: m_is_first_print(true), m_print_config(&print_config), m_last_wipe_tower_print_z(print_config.z_offset.value), - m_sparse_layers_skipped(wipe_tower_sparse_layers_skipped(print_config)), - m_sparse_layers_combined(wipe_tower_sparse_layers_combined(print_config)) + m_sparse_layers_skipped(wipe_tower_sparse_layers_skipped(print_config)) { // Precomputed rather than accumulated while emitting, so that the clearance validator and // the emitter cannot disagree about where the compacted tower sits on any given layer. @@ -161,7 +160,6 @@ public: private: WipeTowerIntegration& operator=(const WipeTowerIntegration&); std::string append_tcr(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr, int new_extruder_id, double z = -1.) const; - std::string tower_height_tag(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr, const std::string &tcr_gcode) const; Polyline generate_path_to_wipe_tower(const Point &start_pos, const Point &end_pos, const BoundingBox &avoid_polygon, const Polygons &bed_polygons) const; std::string append_tcr2(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr, int new_extruder_id, double z = -1.) const; std::string travel_to_tower_gap(GCode &gcodegen, const Point &route_start, const Point &start_wipe_pos) const; @@ -202,9 +200,6 @@ private: // wipe_tower_no_sparse_layers, as answered by the shared compaction rule rather than by the raw // option: smooth timelapse and wrapping detection keep a tower on every layer regardless. const bool m_sparse_layers_skipped; - // Combined tower layers are thicker than the object layer they sit on, the only case where the - // tower's height is not the one process_layer already declared. - const bool m_sparse_layers_combined; // Print z of the compacted tower per planned layer. Empty when the tower is not compacted. std::vector m_compacted_tower_z; }; diff --git a/src/libslic3r/GCode/WipeTower.cpp b/src/libslic3r/GCode/WipeTower.cpp index 135600d6d7..8880c465bf 100644 --- a/src/libslic3r/GCode/WipeTower.cpp +++ b/src/libslic3r/GCode/WipeTower.cpp @@ -746,9 +746,6 @@ public: m_enable_arc_fitting(enable_arc_fitting), m_filpar(filament_parameters) { - // ORCA: This class is only used by BBL printers, so set the parameter appropriately. - // This fixes an issue where the wipe tower was using BBL tags resulting in statistics for purging in the purge tower not being displayed. - GCodeProcessor::s_IsBBLPrinter = true; // adds tag for analyzer: std::ostringstream str; str << ";" << GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Height) << Slic3r::float_to_string_decimal_point(m_layer_height, 6) << "\n"; // don't rely on GCodeAnalyzer knowing the layer height - it knows nothing at priming diff --git a/src/libslic3r/GCode/WipeTower2.cpp b/src/libslic3r/GCode/WipeTower2.cpp index 5e310e3bdd..9f79f2bd11 100644 --- a/src/libslic3r/GCode/WipeTower2.cpp +++ b/src/libslic3r/GCode/WipeTower2.cpp @@ -353,9 +353,6 @@ public: m_gcode_flavor(flavor), m_filpar(filament_parameters) //m_enable_arc_fitting(enable_arc_fitting) { - // ORCA: This class is only used by non BBL printers, so set the parameter appropriately. - // This fixes an issue where the wipe tower was using BBL tags resulting in statistics for purging in the purge tower not being displayed. - GCodeProcessor::s_IsBBLPrinter = false; // adds tag for analyzer: std::ostringstream str; str << ";" << GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Height) << m_layer_height << "\n"; // don't rely on GCodeAnalyzer knowing the layer height - it knows nothing at priming diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index a207657eba..d1810f2645 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -5310,6 +5310,9 @@ bool Print::enable_timelapse_print() const void Print::_make_wipe_tower() { + // Use the printer's G-code tag format so the processor can classify wipe tower filament usage. + GCodeProcessor::s_IsBBLPrinter = is_BBL_printer(); + m_wipe_tower_data.clear(); // BBS diff --git a/tests/fff_print/test_wipe_tower.cpp b/tests/fff_print/test_wipe_tower.cpp index f5b33701d5..f1cb6733de 100644 --- a/tests/fff_print/test_wipe_tower.cpp +++ b/tests/fff_print/test_wipe_tower.cpp @@ -30,6 +30,7 @@ #include "libslic3r/GCode/WipeTower.hpp" #include "libslic3r/LocalesUtils.hpp" #include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Utils.hpp" #include "test_helpers.hpp" #include "test_utils.hpp" @@ -197,6 +198,39 @@ static std::string slice_with_prime_tower(const DynamicPrintConfig &config) return gcode(print); } +TEST_CASE("Tower consumption is classified separately for each printer kind", "[WipeTower][Regression]") +{ + const auto [is_bbl, tower_type] = GENERATE(table({ + { false, "type1" }, { false, "type2" }, { true, "type1" } })); + CAPTURE(is_bbl, tower_type); + const bool previous_bbl = GCodeProcessor::s_IsBBLPrinter; + const ScopeGuard restore_bbl([previous_bbl] { GCodeProcessor::s_IsBBLPrinter = previous_bbl; }); + + DynamicPrintConfig config = wipe_tower_toolchange_config("marlin"); + config.set_deserialize_strict({ { "wipe_tower_type", tower_type } }); + Print print; + print.is_BBL_printer() = is_bbl; + Model model; + init_print({ cube(10) }, print, model, config); + print.apply(model, config); + + // Cover the initial non-BBL slice (the global defaults to true) and a change of printer kind. + GCodeProcessor::s_IsBBLPrinter = !is_bbl; + print.process(); + + GCodeProcessorResult result; + gcode(print, &result); + const auto &statistics = result.print_statistics; + REQUIRE(statistics.wipe_tower_volumes_per_extruder.size() == 2); + for (size_t filament_id : { size_t(0), size_t(1) }) { + CAPTURE(filament_id); + REQUIRE(statistics.wipe_tower_volumes_per_extruder.count(filament_id) == 1); + CHECK(statistics.wipe_tower_volumes_per_extruder.at(filament_id) > 0.); + REQUIRE(statistics.model_volumes_per_extruder.count(filament_id) == 1); + CHECK(statistics.model_volumes_per_extruder.at(filament_id) > 0.); + } +} + TEST_CASE("The wipe tower's toolchange planner flush follows the gcode flavor", "[WipeTower]") { auto [flavor, expected, unexpected] = GENERATE(table({ @@ -247,6 +281,10 @@ TEST_CASE("The wipe tower's G-code moves keep a decimal point in a comma-decimal TEST_CASE("The wipe tower's flow tags keep a decimal point in a comma-decimal locale", "[WipeTower]") { + const bool is_bbl = GENERATE(false, true); + CAPTURE(is_bbl); + const bool previous_bbl = GCodeProcessor::s_IsBBLPrinter; + const ScopeGuard restore_bbl([previous_bbl] { GCodeProcessor::s_IsBBLPrinter = previous_bbl; }); // GCodeProcessor parses these values with the C locale: a comma makes it log an error and // ignore the tag, leaving the extrusion width and height it assumes to its own defaults. CommaNumericLocale comma; @@ -255,17 +293,23 @@ TEST_CASE("The wipe tower's flow tags keep a decimal point in a comma-decimal lo SKIP("no locale with a comma decimal separator is installed"); DynamicPrintConfig config = wipe_tower_toolchange_config("klipper"); config.set_deserialize_strict({ { "wipe_tower_type", "type1" } }); - const std::string gcode = slice_with_prime_tower(config); - // WipeTowerWriter forces the BBL flag, so the tower writes these spellings on every printer. - // By the time the test asks, export has reset the flag for this Klipper config and - // reserved_tag() would hand back the main G-code's ";HEIGHT:" / ";WIDTH:" instead. + Print print; + print.is_BBL_printer() = is_bbl; + Model model; + init_print({ cube(10) }, print, model, config); + print.apply(model, config); + print.process(); + std::string tower_gcode; + for (const auto &layer : print.wipe_tower_data().tool_changes) + for (const auto &change : layer) + tower_gcode += change.gcode; // The width and height tags are both written by the writer's constructor, before the - // tower's start tag, so scan the whole slice. - const std::string height_tag = "; LAYER_HEIGHT: "; - const std::string width_tag = "; LINE_WIDTH: "; + // tower's start tag, so scan the complete tower blocks without the model's tags. + const std::string height_tag = is_bbl ? "; LAYER_HEIGHT: " : ";HEIGHT:"; + const std::string width_tag = is_bbl ? "; LINE_WIDTH: " : ";WIDTH:"; size_t heights = 0; size_t widths = 0; - std::istringstream lines(gcode); + std::istringstream lines(tower_gcode); for (std::string line; std::getline(lines, line);) { const bool is_height = line.compare(0, height_tag.size(), height_tag) == 0; const bool is_width = line.compare(0, width_tag.size(), width_tag) == 0; @@ -506,9 +550,8 @@ TEST_CASE("A run too thin to reach the nozzle's layer height is left alone", "[W TEST_CASE("A merged tower layer declares its own height to the G-code processor", "[WipeTower]") { - // Each writer declares a height in a hardcoded tag dialect while the processor reads only its - // printer's, so one of them is always dropped. A merged layer is the first time that shows, as a - // thick layer drawn and costed as a thin one. 0.2 mm layers under a 0.42 mm maximum merge in pairs. + // The processor must read the merged tower's height rather than the object's layer height. + // 0.2 mm layers under a 0.42 mm maximum merge in pairs. const SparseRunResult plain = slice_sparse_run(sparse_run_config(0.2, "0.42", false)); const SparseRunResult combined = slice_sparse_run(sparse_run_config(0.2, "0.42", true)); @@ -635,7 +678,7 @@ TEST_CASE("Without sparse layers the filament change starts at the tallest print GCodeReader parser; parser.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { const std::string_view raw = line.raw(); - // Objects are tagged with the processor's ;TYPE:, the tower with its own ; FEATURE:. + // Track the extrusion role using the tag format emitted for the printer. if (raw.rfind(";TYPE:", 0) == 0 || raw.rfind("; FEATURE: ", 0) == 0) in_tower = raw.find("Prime tower") != std::string_view::npos; else if (line.extruding(self) && (line.has_x() || line.has_y())) { // not an unretract From 0b1d825142e8d96844000f54182df4a7fde0e44c Mon Sep 17 00:00:00 2001 From: Kris Austin Date: Wed, 4 Nov 2026 07:40:11 -0600 Subject: [PATCH 11/24] Fix the freeze before the Creality send dialog opens on a printer without a CFS (#17177) Fixes #17128 Clicking Print on a Creality printer asked it for its CFS slots on the UI thread, with the 10 s command timeout. A K1C without a CFS never answers that query, so OrcaSlicer froze for 10 s on every click. The send dialog now opens right away and reads the printer on a background thread. Upload works at once, and Upload and Print turns on when the read ends. The slot query waits 5 s, or the full 10 s once the printer reports `"cfsConnect": 1`, and stops as soon as it reports `"cfsConnect": 0`. When there is no filament mapping, the dialog says whether the printer reports no CFS, lists no slots, or can't be reached. --- src/slic3r/GUI/PrintHostDialogs.cpp | 168 ++++++++++++++--- src/slic3r/GUI/PrintHostDialogs.hpp | 20 ++ src/slic3r/Utils/CrealityPrint.cpp | 87 +++++++-- src/slic3r/Utils/CrealityPrint.hpp | 24 ++- src/slic3r/Utils/CrealityPrintAgent.cpp | 18 +- tests/slic3rutils/test_creality_print.cpp | 218 +++++++++++++++++++++- 6 files changed, 474 insertions(+), 61 deletions(-) diff --git a/src/slic3r/GUI/PrintHostDialogs.cpp b/src/slic3r/GUI/PrintHostDialogs.cpp index 39ddff648c..a1fe05a0c1 100644 --- a/src/slic3r/GUI/PrintHostDialogs.cpp +++ b/src/slic3r/GUI/PrintHostDialogs.cpp @@ -1,6 +1,7 @@ #include "PrintHostDialogs.hpp" #include +#include #include #include #include @@ -9,6 +10,7 @@ #include #include #include +#include #include #include "libslic3r/ProjectTask.hpp" #include @@ -16,6 +18,7 @@ #include "libslic3r/Config.hpp" #include +#include #include #include #include @@ -27,11 +30,15 @@ #include #include "slic3r/GUI/Widgets/StateColor.hpp" #include +#include +#include #include #include #include +#include #include #include +#include #include "slic3r/GUI/Widgets/RadioBox.hpp" #include #include @@ -39,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -75,6 +83,7 @@ #include "ExtraRenderers.hpp" #include "format.hpp" #include "../Utils/CrealityPrint.hpp" +#include "../Utils/Http.hpp" #include "BitmapComboBox.hpp" #include "libslic3r_version.h" #include "wxExtensions.hpp" @@ -1919,25 +1928,133 @@ CrealityPrintHostSendDialog::CrealityPrintHostSendDialog(const fs::path& , m_printhost(printhost) {} +CrealityPrintHostSendDialog::~CrealityPrintHostSendDialog() +{ + m_alive->store(false, std::memory_order_release); +} + +// Serializes reads per printer, so a reopened dialog waits for an earlier read of the same printer. +// Never freed, since a detached read may still hold a lock while static destructors run at exit. +static std::mutex& creality_read_mutex(const std::string& print_host) +{ + static auto* guard = new std::mutex; + static auto* mutexes = new std::map; + std::lock_guard lock(*guard); + std::string port; + const std::string host = Http::get_host_from_url(print_host, &port); + return (*mutexes)[host + ":" + port]; +} + void CrealityPrintHostSendDialog::init() { PrintHostSendDialog::init(); - auto* creality_host = static_cast(m_printhost); - bool multi_color; - std::string printer_name; - { - wxBusyCursor wait; - multi_color = creality_host->supports_multi_color_print(); - if (multi_color) - printer_name = creality_host->model_name(); - } - if (!multi_color) - return; + // Upload and Print stays off until the read ends, since a CFS printer given no mapping prints from the spool holder. + if (Button* btn_print = get_button(wxID_YES)) + btn_print->Enable(false); + m_status_label = new wxStaticText(this, wxID_ANY, _L("Reading the printer's filament slots...")); + m_status_label->SetFont(::Label::Body_13); + m_status_label->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#323A3D"))); + content_sizer->Add(m_status_label); - auto* group_box = new wxStaticBox(this, wxID_ANY, - wxString::Format(_L("Printer: %s"), printer_name)); - auto* group_sizer = new wxStaticBoxSizer(group_box, wxVERTICAL); + // Reads off the UI thread, since a printer without a CFS may never answer the slot query. + // The read gets its own host, since the upload job uses m_printhost once the dialog closes. + try { + std::thread([this, alive = m_alive, host = *static_cast(m_printhost)]() { + CrealityPrinterInfo info; + try { + std::lock_guard lock(creality_read_mutex(host.get_host())); + if (!alive->load(std::memory_order_acquire)) + return; + info = host.read_printer_info(); + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(error) << "CrealityPrint dialog: Failed to read the printer: " << e.what(); + } catch (...) { + BOOST_LOG_TRIVIAL(error) << "CrealityPrint dialog: Failed to read the printer"; + } + if (wxTheApp == nullptr || wxGetApp().is_closing()) + return; + wxGetApp().CallAfter([this, alive, info = std::move(info)]() { + if (!wxGetApp().is_closing() && alive->load(std::memory_order_acquire)) + show_printer(info); + }); + }).detach(); + } catch (const std::system_error& e) { + BOOST_LOG_TRIVIAL(error) << "CrealityPrint dialog: Failed to start reading the printer: " << e.what(); + show_read_failure(_L("Could not read the printer. Close this dialog and try again.")); + } + GetSizer()->SetSizeHints(this); + Layout(); +} + +void CrealityPrintHostSendDialog::show_printer(const CrealityPrinterInfo& info) +{ + if (!info.reachable) { + show_read_failure(_L("Could not connect to the printer. Check that it is on, then reopen this dialog.")); + return; + } + m_status_label->Destroy(); + m_status_label = nullptr; + if (info.multi_color) + add_printer_box(info); + end_read(); +} + +void CrealityPrintHostSendDialog::show_read_failure(const wxString& message) +{ + m_status_label->SetLabel(message); + end_read(); +} + +void CrealityPrintHostSendDialog::end_read() +{ + if (Button* btn_print = get_button(wxID_YES)) + btn_print->Enable(true); + fit_content(); +} + +void CrealityPrintHostSendDialog::on_dpi_changed(const wxRect& suggested_rect) +{ + PrintHostSendDialog::on_dpi_changed(suggested_rect); + fit_content(); +} + +// Wraps the status and notice text to the width of the rest of the content, so the text does not widen the dialog. +void CrealityPrintHostSendDialog::fit_content() +{ + for (wxStaticText* text : {m_status_label, m_notice}) + if (text) + text->Hide(); + GetSizer()->SetSizeHints(this); + const int width = content_sizer->GetSize().GetWidth(); + if (m_status_label) { + m_status_label->Show(); + m_status_label->Wrap(-1); + m_status_label->Wrap(width); + } + if (m_notice) { + int border_top, border_side; + m_printer_box->GetBordersForSizer(&border_top, &border_side); + m_notice->Show(); + m_notice->Wrap(-1); + m_notice->Wrap(width - 2 * border_side); + } + GetSizer()->SetSizeHints(this); + Layout(); + Refresh(); + + // Keeps the buttons on the display, since the dialog grows after MsgDialog::finalize centers it. + const wxRect area = wxDisplay(this).GetClientArea(); + const wxRect rect = GetScreenRect(); + if (rect.GetBottom() > area.GetBottom()) + Move(rect.x, std::max(area.y, area.GetBottom() - rect.height)); +} + +void CrealityPrintHostSendDialog::add_printer_box(const CrealityPrinterInfo& info) +{ + m_printer_box = new wxStaticBox(this, wxID_ANY, + wxString::Format(_L("Printer: %s"), info.model_name)); + auto* group_sizer = new wxStaticBoxSizer(m_printer_box, wxVERTICAL); content_sizer->Add(group_sizer, 0, wxEXPAND); const AppConfig* app_config = wxGetApp().app_config; @@ -1974,13 +2091,11 @@ void CrealityPrintHostSendDialog::init() auto* filament_types = full_config.option("filament_type"); int gcode_filament_count = filament_colors ? (int)filament_colors->values.size() : 0; - // Query printer for loaded materials + // Loaded materials { - wxBusyCursor wait; - std::string boxes_json = creality_host->query_boxes_info(); - if (!boxes_json.empty()) { + if (!info.boxes_json.empty()) { try { - auto resp = nlohmann::json::parse(boxes_json); + auto resp = nlohmann::json::parse(info.boxes_json); if (resp.contains("boxsInfo") && resp["boxsInfo"].contains("materialBoxs")) { for (auto& box : resp["boxsInfo"]["materialBoxs"]) { int box_id = box["id"].get(); @@ -2127,10 +2242,19 @@ void CrealityPrintHostSendDialog::init() }); } } + } else if (m_printer_slots.empty()) { + wxString text; + if (info.no_cfs) + // TRN Creality send dialog. CFS is Creality's multi-filament unit. + text = _L("The printer reports no CFS connected, so the print will use the external spool."); + else + // TRN Creality send dialog, when the printer lists no CFS slots or does not answer + text = _L("The printer did not report any filament slots, so the print will use the external spool."); + m_notice = new wxStaticText(this, wxID_ANY, text); + m_notice->SetFont(::Label::Body_13); + m_notice->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#323A3D"))); + group_sizer->Add(m_notice); } - - this->Layout(); - this->Fit(); } std::map CrealityPrintHostSendDialog::extendedInfo() const diff --git a/src/slic3r/GUI/PrintHostDialogs.hpp b/src/slic3r/GUI/PrintHostDialogs.hpp index b398a97eb4..de57427967 100644 --- a/src/slic3r/GUI/PrintHostDialogs.hpp +++ b/src/slic3r/GUI/PrintHostDialogs.hpp @@ -1,8 +1,10 @@ #ifndef slic3r_PrintHostSendDialog_hpp_ #define slic3r_PrintHostSendDialog_hpp_ +#include #include #include +#include #include #include #include @@ -12,6 +14,7 @@ #include #include #include +#include #include "GUI_Utils.hpp" #include "MsgDialog.hpp" @@ -25,6 +28,7 @@ class wxComboBox; class ComboBox; class wxDataViewListCtrl; class wxFlexGridSizer; +class wxStaticBox; class wxStaticText; class wxWrapSizer; class CheckBox; @@ -33,6 +37,8 @@ namespace Slic3r { namespace GUI { class BitmapComboBox; } } namespace Slic3r { +struct CrealityPrinterInfo; + namespace GUI { class PrintHostSendDialog : public GUI::MsgDialog @@ -202,15 +208,29 @@ public: const wxArrayString& storage_names, bool switch_to_device_tab, PrintHost* printhost); + ~CrealityPrintHostSendDialog() override; virtual void init() override; virtual std::map extendedInfo() const override; +protected: + void on_dpi_changed(const wxRect& suggested_rect) override; + private: static constexpr const char* CONFIG_KEY_ENABLESELFTEST = "crealityprint_enable_self_test"; + void show_printer(const CrealityPrinterInfo& info); + void show_read_failure(const wxString& message); + void end_read(); + void fit_content(); + void add_printer_box(const CrealityPrinterInfo& info); + bool m_enableSelfTest; PrintHost* m_printhost; + wxStaticText* m_status_label{nullptr}; + wxStaticBox* m_printer_box{nullptr}; + wxStaticText* m_notice{nullptr}; + std::shared_ptr> m_alive{std::make_shared>(true)}; struct SlotInfo { std::string tool_id; // e.g. "T1A" diff --git a/src/slic3r/Utils/CrealityPrint.cpp b/src/slic3r/Utils/CrealityPrint.cpp index 0d5eff4e5c..f2e7f5be46 100644 --- a/src/slic3r/Utils/CrealityPrint.cpp +++ b/src/slic3r/Utils/CrealityPrint.cpp @@ -92,7 +92,12 @@ wxString CrealityPrint::get_test_failed_msg(wxString& msg) const } bool CrealityPrint::test(wxString& msg) const -{ +{ + return probe_info(&msg); +} + +bool CrealityPrint::probe_info(wxString* msg) const +{ bool res = true; const char* name = get_name(); auto url = make_url("info"); @@ -106,7 +111,8 @@ bool CrealityPrint::test(wxString& msg) const BOOST_LOG_TRIVIAL(error) << boost::format("%1%: Error getting version: %2%, HTTP %3%, body: `%4%`") % name % error % status % body; res = false; - msg = format_error(body, error, status); + if (msg) + *msg = format_error(body, error, status); }) .on_complete([&, this](std::string body, unsigned) { BOOST_LOG_TRIVIAL(debug) << boost::format("%1%: Got version: %2%") % name % body; @@ -125,7 +131,8 @@ bool CrealityPrint::test(wxString& msg) const .on_ip_resolve([&](std::string address) { // Workaround for Windows 10/11 mDNS resolve issue, where two mDNS resolves in succession fail. // Remember resolved address to be reused at successive REST API call. - msg = GUI::from_u8(address); + if (msg) + *msg = GUI::from_u8(address); }) #endif // WIN32 .perform_sync(); @@ -257,18 +264,39 @@ static beast::error_code ws_read(net::io_context& ioc, websocket::stream& ws, const json& cmd, const std::string& expected_key, int max_reads = 20) +// Returns a status's cfsConnect value, 0 without a CFS or 1 with one, or -1 when the message holds neither. +static int reported_cfs_connect(const std::string& msg) { - ws_send(ioc, ws, cmd); + if (msg.find("cfsConnect") == std::string::npos) + return -1; + const json status = json::parse(msg, nullptr, false); + if (!status.is_object() || !status.contains("cfsConnect")) + return -1; + const json& cfs_connect = status["cfsConnect"]; + if (cfs_connect == 0) + return 0; + return cfs_connect == 1 ? 1 : -1; +} - // total caps the loop if the printer sends a continuous stream of heartbeats - for (int reads = 0, total = 0; reads < max_reads && total < max_reads * 3; ++total) { +// Sends the CFS slot query and returns the reply, or nothing once a status reports no CFS connected, which also sets *no_cfs. +// The query gets slots_reply, or the later of slots_reply and cfs_reply once a status reports a CFS connected, since such a printer does answer. +static std::string ws_query_slots(net::io_context& ioc, + websocket::stream& ws, + std::chrono::milliseconds slots_reply, + std::chrono::milliseconds cfs_reply, + bool* no_cfs) +{ + const auto sent = std::chrono::steady_clock::now(); + auto deadline = sent + slots_reply; + beast::get_lowest_layer(ws).expires_at(deadline); + ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"boxsInfo", 1}}}}); + + // The deadline also ends the read when the printer keeps sending heartbeats or status updates. + while (std::chrono::steady_clock::now() < deadline) { beast::flat_buffer buf; const beast::error_code ec = ws_read(ioc, ws, buf); - if (ec == beast::error::timeout) { - BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a '" << expected_key << "' response"; - return {}; - } + if (ec == beast::error::timeout) + break; if (ec) throw beast::system_error{ec}; std::string msg = beast::buffers_to_string(buf.data()); @@ -278,11 +306,21 @@ static std::string ws_send_and_read(net::io_context& ioc, websocket::stream ws{ioc}; ws_connect(ioc, ws, m_host, ws_settings.port, ws_settings.connect); - beast::get_lowest_layer(ws).expires_after(ws_settings.reply); - json boxs_query = {{"method", "get"}, {"params", {{"boxsInfo", 1}}}}; - std::string result = ws_send_and_read(ioc, ws, boxs_query, "boxsInfo"); + std::string result = ws_query_slots(ioc, ws, ws_settings.slots_reply, ws_settings.reply, no_cfs); ws_close(ioc, ws, ws_settings.close); return result; @@ -388,6 +426,19 @@ std::string CrealityPrint::query_boxes_info() const } } +CrealityPrinterInfo CrealityPrint::read_printer_info() const +{ + CrealityPrinterInfo info; + info.reachable = probe_info(nullptr); + info.multi_color = info.reachable && model_supports_multi_color(m_model); + // model_name() probes /info again when the reply names no model. + if (info.reachable) + info.model_name = m_model.empty() ? std::string("unknown") : model_name(); + if (info.multi_color) + info.boxes_json = query_boxes_info(&info.no_cfs); + return info; +} + std::vector CrealityPrint::start_print_commands(bool multi_color, const std::string& gcode_path, const std::map& extended_info) diff --git a/src/slic3r/Utils/CrealityPrint.hpp b/src/slic3r/Utils/CrealityPrint.hpp index 213ecab74b..060581a89b 100644 --- a/src/slic3r/Utils/CrealityPrint.hpp +++ b/src/slic3r/Utils/CrealityPrint.hpp @@ -16,6 +16,16 @@ namespace Slic3r { class DynamicPrintConfig; class Http; + +struct CrealityPrinterInfo +{ + bool reachable{false}; + bool multi_color{false}; + bool no_cfs{false}; // The printer reports that no CFS is connected + std::string model_name; + std::string boxes_json; // Empty unless the printer lists its CFS slots +}; + class CrealityPrint : public PrintHost { public: @@ -39,7 +49,10 @@ public: // value: an F-code on the K2 platform, a literal name on K1-family. static bool model_supports_multi_color(const std::string& model); static std::string model_display_name(const std::string& model); - std::string query_boxes_info() const; + // Sets *no_cfs to whether the printer reports that no CFS is connected. + std::string query_boxes_info(bool* no_cfs = nullptr) const; + // Reads the model and, for a CFS-capable model, the CFS slots, without translating any text, so it is safe off the UI thread. + CrealityPrinterInfo read_printer_info() const; std::string model_name() const; // The WebSocket commands that start gcode_path, built from the send dialog's // extended_info (enableSelfTest and the colorMatch_ slot mapping). @@ -53,9 +66,10 @@ protected: struct WsSettings { std::string port{"9999"}; - std::chrono::milliseconds connect{std::chrono::seconds(5)}; // Per resolved address tried, then again for the opening handshake - std::chrono::milliseconds reply{std::chrono::seconds(10)}; // Commands and the replies read after them - std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake + std::chrono::milliseconds connect{std::chrono::seconds(5)}; // Per resolved address tried, then again for the opening handshake + std::chrono::milliseconds reply{std::chrono::seconds(10)}; // Commands and the replies read after them + std::chrono::milliseconds slots_reply{std::chrono::seconds(5)}; // The CFS slot query, extended to reply once a status reports a CFS connected + std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake } ws_settings; private: @@ -71,6 +85,8 @@ private: bool start_print(wxString& msg, const std::string& filename, const std::map& extended_info) const; std::string safe_filename(const std::string& filename) const; void query_model() const; + // Reads /info and caches the model. When msg is not null, it gets a translated error, or on Windows the resolved address. + bool probe_info(wxString* msg) const; }; } // namespace Slic3r diff --git a/src/slic3r/Utils/CrealityPrintAgent.cpp b/src/slic3r/Utils/CrealityPrintAgent.cpp index 510ad9135d..b55499d60c 100644 --- a/src/slic3r/Utils/CrealityPrintAgent.cpp +++ b/src/slic3r/Utils/CrealityPrintAgent.cpp @@ -313,25 +313,29 @@ bool CrealityPrintAgent::fetch_filament_info(std::string dev_id, FilamentSyncMod cfg.set_key_value("printhost_apikey", new ConfigOptionString(device_info.api_key)); cfg.set_key_value("printhost_ssl_ignore_revoke", new ConfigOptionBool(false)); - CrealityPrint host(&cfg); + CrealityPrint host(&cfg); + const CrealityPrinterInfo info = host.read_printer_info(); // Defer to base if this isn't a K-series board with CFS firmware support. - if (!host.supports_multi_color_print()) { + if (!info.multi_color) { BOOST_LOG_TRIVIAL(info) - << "CrealityPrintAgent: " << host.model_name() + << "CrealityPrintAgent: " << (info.reachable ? info.model_name : std::string("unreachable")) << " is not CFS-capable, deferring to base Moonraker agent"; return MoonrakerPrinterAgent::fetch_filament_info(std::move(dev_id)); } - BOOST_LOG_TRIVIAL(info) - << "CrealityPrintAgent: querying CFS slots on " << host.model_name(); + if (info.no_cfs) { + BOOST_LOG_TRIVIAL(info) << "CrealityPrintAgent: " << info.model_name << " reports no CFS connected, deferring to base agent"; + return MoonrakerPrinterAgent::fetch_filament_info(std::move(dev_id)); + } - const std::string response = host.query_boxes_info(); + BOOST_LOG_TRIVIAL(info) + << "CrealityPrintAgent: read CFS slots from " << info.model_name; std::vector slots; int box_count = 0; std::string parse_err; - if (!parse_cfs_response(response, slots, box_count, parse_err)) { + if (!parse_cfs_response(info.boxes_json, slots, box_count, parse_err)) { BOOST_LOG_TRIVIAL(warning) << "CrealityPrintAgent: CFS query failed (" << parse_err << "), " << "falling back to base agent"; diff --git a/tests/slic3rutils/test_creality_print.cpp b/tests/slic3rutils/test_creality_print.cpp index a9660f1d0a..8167e5e35b 100644 --- a/tests/slic3rutils/test_creality_print.cpp +++ b/tests/slic3rutils/test_creality_print.cpp @@ -55,9 +55,15 @@ using tcp = net::ip::tcp; using namespace std::chrono_literals; enum class Behavior { + HangsUp, // Closes every connection without answering SilentBeforeHandshake, // Never answers the websocket upgrade Silent, // Completes the websocket upgrade, then never reads or sends Answers, // Sends a heartbeat, and the CFS slots once the heartbeat is acknowledged + ReportsNoCfs, // Sends a status reporting no CFS connected, then never sends the CFS slots + ReportsCfs, // Sends a status reporting a CFS connected, then the CFS slots + ReportsCfsSlowly, // Sends a status reporting a CFS connected, then the CFS slots 1.5 s later + StreamsCfs, // Sends a status reporting a CFS connected every 50 ms and never sends the CFS slots + StreamsCfsThenSlots, // Sends 25 statuses reporting a CFS connected 50 ms apart, then the CFS slots }; struct Message @@ -97,6 +103,12 @@ public: return m_messages; } + int http_requests() + { + std::lock_guard lock(m_mutex); + return m_http_requests; + } + // Hangs up every connection that is waiting. void release() { @@ -125,7 +137,7 @@ private: http::request request; beast::error_code ec; http::read(socket, buffer, request, ec); - if (ec) + if (ec || m_behavior == Behavior::HangsUp) return; if (!websocket::is_upgrade(request)) { serve_http(socket, request); @@ -157,15 +169,43 @@ private: std::lock_guard lock(m_mutex); m_messages.push_back({ws.got_text(), payload}); } - if (first) + const std::string slots = R"({"boxsInfo":{"materialBoxs":[]}})"; + if (first && m_behavior == Behavior::ReportsNoCfs) { + ws.write(net::buffer(std::string(R"({"cfsConnect":0,"nozzleTemp":"25.000000"})")), ec); + wait_for_release(); + return; + } + if (first && (m_behavior == Behavior::StreamsCfs || m_behavior == Behavior::StreamsCfsThenSlots)) { + const bool forever = m_behavior == Behavior::StreamsCfs; + for (int count = 0; !ec && !released() && (forever || count < 25); ++count) { + ws.write(net::buffer(std::string(R"({"cfsConnect":1,"nozzleTemp":"25.000000"})")), ec); + std::this_thread::sleep_for(50ms); + } + if (forever) { + wait_for_release(); + return; + } + ws.write(net::buffer(slots), ec); + continue; + } + if (first && (m_behavior == Behavior::ReportsCfs || m_behavior == Behavior::ReportsCfsSlowly)) { + ws.write(net::buffer(std::string(R"({"cfsConnect":1,"nozzleTemp":"25.000000"})")), ec); + if (m_behavior == Behavior::ReportsCfsSlowly) + std::this_thread::sleep_for(1500ms); + ws.write(net::buffer(slots), ec); + } else if (first) ws.write(net::buffer(std::string(R"({"ModeCode":"heart_beat"})")), ec); else if (payload == "ok") - ws.write(net::buffer(std::string(R"({"boxsInfo":{"materialBoxs":[]}})")), ec); + ws.write(net::buffer(slots), ec); } } void serve_http(tcp::socket& socket, const http::request& request) { + { + std::lock_guard lock(m_mutex); + ++m_http_requests; + } http::response response{http::status::ok, request.version()}; response.keep_alive(false); // The upload only needs a success status. @@ -175,6 +215,12 @@ private: http::write(socket, response, ec); } + bool released() + { + std::lock_guard lock(m_mutex); + return m_released; + } + void wait_for_release() { std::unique_lock lock(m_mutex); @@ -191,6 +237,7 @@ private: std::mutex m_mutex; std::condition_variable m_changed; std::vector m_messages; + int m_http_requests = 0; bool m_released = false; }; @@ -201,20 +248,27 @@ public: using CrealityPrint::ws_settings; }; -std::unique_ptr make_host(const FakeCrealityPrinter& printer, std::chrono::milliseconds deadline) +DynamicPrintConfig host_config(const std::string& url) { DynamicPrintConfig config; - config.set_key_value("print_host", new ConfigOptionString(printer.base_url())); + config.set_key_value("print_host", new ConfigOptionString(url)); config.set_key_value("print_host_webui", new ConfigOptionString("")); config.set_key_value("printhost_cafile", new ConfigOptionString("")); config.set_key_value("printhost_port", new ConfigOptionString("")); config.set_key_value("printhost_apikey", new ConfigOptionString("")); config.set_key_value("printhost_ssl_ignore_revoke", new ConfigOptionBool(false)); - auto host = std::make_unique(&config); - host->ws_settings.port = printer.port(); - host->ws_settings.connect = deadline; - host->ws_settings.reply = deadline; - host->ws_settings.close = deadline; + return config; +} + +std::unique_ptr make_host(const FakeCrealityPrinter& printer, std::chrono::milliseconds deadline) +{ + DynamicPrintConfig config = host_config(printer.base_url()); + auto host = std::make_unique(&config); + host->ws_settings.port = printer.port(); + host->ws_settings.connect = deadline; + host->ws_settings.reply = deadline; + host->ws_settings.slots_reply = deadline; + host->ws_settings.close = deadline; return host; } @@ -259,6 +313,75 @@ TEST_CASE("Querying the CFS slots gives a silent printer no more than its deadli CHECK(reply.empty()); } +TEST_CASE("The CFS slot query has a shorter default deadline than a command", "[CrealityPrint]") +{ + DynamicPrintConfig config = host_config("http://127.0.0.1"); + const TestHost host(&config); + + CHECK(host.ws_settings.slots_reply < host.ws_settings.reply); +} + +TEST_CASE("Querying the CFS slots waits on a silent printer for the slot deadline, not the command one", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::Silent, "F008"); + const auto host = make_host(printer, 200ms); + host->ws_settings.reply = 30s; + std::string reply; + + CHECK(finishes_within(printer, 2s, [&] { reply = host->query_boxes_info(); })); + CHECK(reply.empty()); +} + +TEST_CASE("Querying the CFS slots stops at a status reporting no CFS connected", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::ReportsNoCfs, "K1C"); + const auto host = make_host(printer, 200ms); + host->ws_settings.slots_reply = 30s; + std::string reply; + + CHECK(finishes_within(printer, 2s, [&] { reply = host->query_boxes_info(); })); + CHECK(reply.empty()); +} + +TEST_CASE("Querying the CFS slots waits past a status reporting a CFS connected", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::ReportsCfs, "K1C"); + const auto host = make_host(printer, 5s); + bool no_cfs = true; + + CHECK(host->query_boxes_info(&no_cfs) == R"({"boxsInfo":{"materialBoxs":[]}})"); + CHECK_FALSE(no_cfs); +} + +TEST_CASE("A status reporting a CFS connected never shortens the CFS slot deadline", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::ReportsCfsSlowly, "K1C"); + const auto host = make_host(printer, 200ms); + host->ws_settings.slots_reply = 5s; + + CHECK(host->query_boxes_info() == R"({"boxsInfo":{"materialBoxs":[]}})"); +} + +TEST_CASE("Querying the CFS slots keeps reading while the printer streams status updates", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::StreamsCfsThenSlots, "K1C"); + const auto host = make_host(printer, 1s); + host->ws_settings.reply = 5s; + + CHECK(host->query_boxes_info() == R"({"boxsInfo":{"materialBoxs":[]}})"); +} + +TEST_CASE("Querying the CFS slots gives a printer reporting a CFS connected no more than the command deadline", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::StreamsCfs, "K1C"); + const auto host = make_host(printer, 200ms); + host->ws_settings.reply = 400ms; + std::string reply; + + CHECK(finishes_within(printer, 2s, [&] { reply = host->query_boxes_info(); })); + CHECK(reply.empty()); +} + TEST_CASE("Querying the CFS slots acknowledges heartbeats in text frames", "[CrealityPrint]") { FakeCrealityPrinter printer(Behavior::Answers, "F008"); @@ -273,6 +396,81 @@ TEST_CASE("Querying the CFS slots acknowledges heartbeats in text frames", "[Cre CHECK(messages[1].payload == "ok"); } +TEST_CASE("Reading a CFS-capable printer gives its name and CFS slots", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::Answers, "F008"); + const auto host = make_host(printer, 5s); + + const CrealityPrinterInfo info = host->read_printer_info(); + CHECK(info.reachable); + CHECK(info.multi_color); + CHECK_FALSE(info.no_cfs); + CHECK(info.model_name == "K2 Plus"); + CHECK(info.boxes_json == R"({"boxsInfo":{"materialBoxs":[]}})"); +} + +TEST_CASE("Reading a CFS-capable printer that reports no CFS connected flags it", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::ReportsNoCfs, "K1C"); + const auto host = make_host(printer, 200ms); + host->ws_settings.slots_reply = 30s; + CrealityPrinterInfo info; + + CHECK(finishes_within(printer, 2s, [&] { info = host->read_printer_info(); })); + CHECK(info.multi_color); + CHECK(info.no_cfs); + CHECK(info.boxes_json.empty()); +} + +TEST_CASE("Reading a printer without CFS support does not query the slots", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::Answers, "F001"); + const auto host = make_host(printer, 5s); + + const CrealityPrinterInfo info = host->read_printer_info(); + CHECK(info.reachable); + CHECK_FALSE(info.multi_color); + CHECK(info.model_name == "unknown (F001)"); + CHECK(info.boxes_json.empty()); + CHECK(printer.messages().empty()); +} + +TEST_CASE("Reading a printer that names no model asks for its info once", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::Answers, ""); + const auto host = make_host(printer, 5s); + + const CrealityPrinterInfo info = host->read_printer_info(); + CHECK(info.reachable); + CHECK(info.model_name == "unknown"); + CHECK(printer.http_requests() == 1); +} + +TEST_CASE("Reading a CFS-capable printer that never answers the slot query gives no slots within the deadlines", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::Silent, "K1C"); + const auto host = make_host(printer, 200ms); + CrealityPrinterInfo info; + + CHECK(finishes_within(printer, 2s, [&] { info = host->read_printer_info(); })); + CHECK(info.reachable); + CHECK(info.multi_color); + CHECK_FALSE(info.no_cfs); + CHECK(info.model_name == "K1C"); + CHECK(info.boxes_json.empty()); +} + +TEST_CASE("Reading a printer that hangs up reports it unreachable", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::HangsUp, "K1C"); + const auto host = make_host(printer, 5s); + + const CrealityPrinterInfo info = host->read_printer_info(); + CHECK_FALSE(info.reachable); + CHECK_FALSE(info.multi_color); + CHECK(info.boxes_json.empty()); +} + TEST_CASE("Starting a print gives a silent printer no more than its deadlines", "[CrealityPrint]") { // F008 is a multi-color model and F001 a plain one. Without a handshake the start command is never sent, so the upload fails. From 6839c9d3443adc9a2641bb9a98a7193b0d54770d Mon Sep 17 00:00:00 2001 From: Lam Wei Lun Date: Wed, 4 Nov 2026 21:45:25 +0800 Subject: [PATCH 12/24] Invalidate filament grouping when the AMS material inventory changes (#17195) Print::m_extruder_filament_info feeds filament grouping, but it was a plain member with no change detection and no invalidation entry point. Changing only the device-side AMS material inventory, such as a spool colour, therefore left a finished slice valid: Print::apply() reported UNCHANGED, the grouping steps stayed done, and export re-emitted the previous G-code with a stale filament_map. Compare the inventory in Print::apply() and invalidate the grouping steps when it changed: - set_extruder_filament_info() now only stashes the payload, so apply() can compare it against the installed one and act on the change under the state lock. - The comparison projects both payloads exactly as grouping does: colour, type, tray name, support flag and filament id per tray. Volatile AMS keys such as remaining amount, temperatures and filament_changed therefore do not count. - A changed inventory invalidates psWipeTower and psSkirtBrim, matching what extruder_ams_count already does, and escalates to APPLY_STATUS_INVALIDATED only when a step was actually taken back. - A payload carrying no tray configs at all is treated as "not known yet" rather than "no filaments", so an AMS reconnect does not invalidate a finished slice, while clearing the last spool still does. - The Plater hands the inventory to apply() before applying, so the change rides the same pass. Adds comparator tests for the inventory projection and an integration test that drives process() and apply() over a two-extruder auto-match print. --- src/libslic3r/FilamentGroupUtils.cpp | 59 ++++- src/libslic3r/FilamentGroupUtils.hpp | 11 + src/libslic3r/Print.hpp | 11 +- src/libslic3r/PrintApply.cpp | 16 ++ src/slic3r/GUI/Plater.cpp | 4 +- tests/fff_print/test_print.cpp | 109 ++++++++ .../test_toolordering_nozzle_group.cpp | 237 +++++++++++++++++- 7 files changed, 423 insertions(+), 24 deletions(-) diff --git a/src/libslic3r/FilamentGroupUtils.cpp b/src/libslic3r/FilamentGroupUtils.cpp index 47ddda0df2..b035697a85 100644 --- a/src/libslic3r/FilamentGroupUtils.cpp +++ b/src/libslic3r/FilamentGroupUtils.cpp @@ -103,11 +103,11 @@ namespace FilamentGroupUtils } - static std::vector> build_full_machine_filaments(const std::vector>& filament_configs) + std::vector> build_full_machine_filaments(const std::vector>& filament_configs) { auto extract_filament_type = [](const std::string& s)->std::string { - std::regex r1(R"(^Sup.(\w+)$)"); - std::regex r2(R"(^(\w+)-S$)"); + static const std::regex r1(R"(^Sup.(\w+)$)"); + static const std::regex r2(R"(^(\w+)-S$)"); std::smatch m; if (std::regex_match(s, m, r1)) @@ -118,8 +118,9 @@ namespace FilamentGroupUtils }; // change filament type to type format in preset - // defualt size set to 2 - std::vector> machine_filaments(2); + // One bucket per extruder, at least two, never fewer than the payload so the loop below + // cannot index out of bounds. + std::vector> machine_filaments(std::max(filament_configs.size(), 2)); for (size_t idx = 0; idx < filament_configs.size(); ++idx) { auto& arr = filament_configs[idx]; for (auto& item : arr) { @@ -129,15 +130,15 @@ namespace FilamentGroupUtils std::string tray_name; bool is_support_filament = false; - if (auto color_ptr = item.option("filament_colour"); color_ptr) + if (auto color_ptr = item.option("filament_colour"); color_ptr && !color_ptr->values.empty()) color = color_ptr->get_at(0); - if (auto type_ptr = item.option("filament_type"); type_ptr) { + if (auto type_ptr = item.option("filament_type"); type_ptr && !type_ptr->values.empty()) { type = type_ptr->get_at(0); type = extract_filament_type(type); } - if (auto tray_ptr = item.option("tray_name"); tray_ptr) + if (auto tray_ptr = item.option("tray_name"); tray_ptr && !tray_ptr->values.empty()) tray_name = tray_ptr->get_at(0); - if (auto support_ptr = item.option("filament_is_support"); support_ptr) + if (auto support_ptr = item.option("filament_is_support"); support_ptr && !support_ptr->values.empty()) is_support_filament = support_ptr->get_at(0); if (auto id_ptr = item.option("filament_id"); id_ptr && !id_ptr->values.empty()) temp.filament_id = id_ptr->get_at(0); @@ -156,12 +157,48 @@ namespace FilamentGroupUtils return machine_filaments; } + bool machine_filaments_changed(const std::vector>& old_configs, + const std::vector>& new_configs) + { + // A payload carrying no tray configs at all means "inventory not known yet" (AMS not + // connected), not "the AMS has no filaments": a connected device reports one config per slot, + // so clearing the last spool still has to count as a change. + const auto has_any_tray = [](const std::vector>& payload) { + for (const std::vector& extruder : payload) + if (!extruder.empty()) + return true; + return false; + }; + const std::vector> old_projected = build_full_machine_filaments(old_configs); + const std::vector> new_projected = build_full_machine_filaments(new_configs); + if (!has_any_tray(old_configs) || !has_any_tray(new_configs)) + return false; + if (old_projected.size() != new_projected.size()) + return true; + for (size_t idx = 0; idx < old_projected.size(); ++idx) { + const std::vector& old_slots = old_projected[idx]; + const std::vector& new_slots = new_projected[idx]; + // Slot order is significant: build_machine_filaments() groups by slot position. + if (old_slots.size() != new_slots.size()) + return true; + for (size_t i = 0; i < old_slots.size(); ++i) { + const MachineFilamentInfo& a = old_slots[i]; + const MachineFilamentInfo& b = new_slots[i]; + const bool slot_changed = a.color != b.color || a.type != b.type || a.is_support != b.is_support + || a.is_extended != b.is_extended || a.filament_id != b.filament_id; + if (slot_changed) + return true; + } + } + return false; + } + std::vector> build_machine_filaments(const std::vector>& filament_configs, const std::vector>& ams_counts, bool ignore_ext_filament) { std::vector> ret(2); std::vector ams_size(2, 0); std::vector> full_machine_filaments = build_full_machine_filaments(filament_configs); - assert(full_machine_filaments.size() == 2); + assert(full_machine_filaments.size() >= 2); for (size_t idx = 0; idx < std::min(ams_counts.size(),ams_size.size()); ++idx) { const auto& ams_count = ams_counts[idx]; for (auto iter = ams_count.begin(); iter != ams_count.end(); ++iter) { @@ -169,7 +206,7 @@ namespace FilamentGroupUtils } } - assert(full_machine_filaments.size() == ams_size.size()); + assert(full_machine_filaments.size() >= ams_size.size()); for (size_t idx = 0; idx < std::min(ams_size.size(), full_machine_filaments.size()); ++idx) { std::vector tmp; for (size_t j = 0; j < full_machine_filaments[idx].size(); ++j) { diff --git a/src/libslic3r/FilamentGroupUtils.hpp b/src/libslic3r/FilamentGroupUtils.hpp index e4f5740463..6784093d9c 100644 --- a/src/libslic3r/FilamentGroupUtils.hpp +++ b/src/libslic3r/FilamentGroupUtils.hpp @@ -82,6 +82,17 @@ namespace Slic3r std::vector> build_machine_filaments(const std::vector>& filament_configs, const std::vector>& ams_counts, bool ignore_ext_filament); + // Per-extruder projection of an AMS inventory payload: only the keys the grouping consumes + // (colour, type, tray_name, filament_is_support, filament_id); slots lacking colour, type or + // tray_name are dropped. + std::vector> build_full_machine_filaments(const std::vector>& filament_configs); + + // Compares two AMS inventory payloads by that projection, so volatile keys (remaining amount, + // temperatures, filament_changed) never count as a change. A payload carrying no tray configs at + // all is "unknown" (AMS not connected) and reports no change. + bool machine_filaments_changed(const std::vector>& old_configs, + const std::vector>& new_configs); + bool collect_unprintable_limits(const std::vector>& physical_unprintables, const std::vector>& geometric_unprintables, std::vector>& unprintable_limits); bool remove_intersection(std::set& a, std::set& b); diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index 0aca2dcde0..85b3a28b30 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -1238,7 +1238,13 @@ public: const std::map& sequential_dynamic_orderings() const { return m_sequential_dynamic_orderings; } const std::vector>& get_extruder_filament_info() const { return m_extruder_filament_info; } - void set_extruder_filament_info(const std::vector>& filament_info) { m_extruder_filament_info = filament_info; } + // Two-phase: the setter only stashes the payload, so Print::apply() can invalidate the grouping + // steps once the inventory actually changed. + void set_extruder_filament_info(const std::vector>& filament_info) + { + m_pending_extruder_filament_info = filament_info; + m_extruder_filament_info_pending = true; + } void set_geometric_unprintable_filaments(const std::vector> &unprintables_filament_ids) { m_geometric_unprintable_filaments = unprintables_filament_ids; } std::vector> get_geometric_unprintable_filaments() const { return m_geometric_unprintable_filaments;} @@ -1538,6 +1544,9 @@ private: Points m_skirt_convex_hull; std::vector> m_extruder_filament_info; + // Payload handed to set_extruder_filament_info(), installed by Print::apply(). See the setter. + std::vector> m_pending_extruder_filament_info; + bool m_extruder_filament_info_pending { false }; // Logical (extruder, nozzle) grouping result, set by ToolOrdering during reorder. std::shared_ptr m_nozzle_group_result; diff --git a/src/libslic3r/PrintApply.cpp b/src/libslic3r/PrintApply.cpp index 0160cf75b8..a19f23c60c 100644 --- a/src/libslic3r/PrintApply.cpp +++ b/src/libslic3r/PrintApply.cpp @@ -34,6 +34,7 @@ #include #include #include +#include "FilamentGroupUtils.hpp" #include "MultiNozzleUtils.hpp" #include "ObjectID.hpp" #include "PlaceholderParser.hpp" @@ -1654,6 +1655,21 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_ // Grab the lock for the Print / PrintObject milestones. std::scoped_lock lock(this->state_mutex()); + // The device-owned AMS inventory only feeds filament grouping, so a changed payload invalidates + // the grouping steps. + if (m_extruder_filament_info_pending) { + if (FilamentGroupUtils::machine_filaments_changed(m_extruder_filament_info, m_pending_extruder_filament_info)) { + // Both steps are attempted on purpose, and the status escalates only when one was actually + // taken back, so a print that is already invalid stays UNCHANGED. + const bool wipe_tower_invalidated = this->invalidate_step(psWipeTower); + const bool skirt_brim_invalidated = this->invalidate_step(psSkirtBrim); + if (wipe_tower_invalidated || skirt_brim_invalidated) + update_apply_status(true); + } + m_extruder_filament_info = std::move(m_pending_extruder_filament_info); + m_extruder_filament_info_pending = false; + } + // The following call may stop the background processing. if (! print_diff.empty()) update_apply_status(this->invalidate_state_by_config_options(new_full_config, print_diff)); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 93e39ae892..be35caca78 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -11708,8 +11708,10 @@ unsigned int Plater::priv::update_background_process(bool force_validation, bool if (f_volume_maps.empty()) { f_volume_maps = preset_bundle->get_default_nozzle_volume_types_for_filaments(f_maps); } - invalidated = background_process.apply(this->model, preset_bundle->full_config(false, f_maps, f_volume_maps)); + // Set the device filament info before Print::apply: it compares the payload and invalidates the + // grouping steps when the AMS material inventory changed, so apply must see it in the same pass. background_process.fff_print()->set_extruder_filament_info(get_extruder_filament_info()); + invalidated = background_process.apply(this->model, preset_bundle->full_config(false, f_maps, f_volume_maps)); } else invalidated = background_process.apply(this->model, preset_bundle->full_config(false)); diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 833ac23f4f..ddbab9d204 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -2910,3 +2910,112 @@ TEST_CASE("Height range settings follow a Z shrinkage change that comes with a m check_thin_dense_height_range(*print.objects().front(), 95.); } + +namespace { + +// One tray of the device AMS inventory, with the keys build_filament_ams_list() puts in the payload. +DynamicPrintConfig loaded_filament_tray(const std::string &colour, const std::string &type, const std::string &tray_name) +{ + DynamicPrintConfig tray; + tray.set_key_value("filament_colour", new ConfigOptionStrings{ colour }); + tray.set_key_value("filament_type", new ConfigOptionStrings{ type }); + tray.set_key_value("tray_name", new ConfigOptionStrings{ tray_name }); + tray.set_key_value("filament_id", new ConfigOptionStrings{ "GFA00" }); + tray.set_key_value("filament_is_support", new ConfigOptionBools{ false }); + return tray; +} + +// Two extruders with one nozzle each, slicing red and green PLA in Convenience (auto for match) mode +// with the prime tower that the grouping step feeds. +DynamicPrintConfig machine_inventory_config() +{ + DynamicPrintConfig config = multifilament_config(2, { + { "printer_technology", "FFF" }, + { "print_sequence", "by layer" }, + { "nozzle_diameter", "0.4,0.4" }, + { "printer_extruder_id", "1,2" }, + { "printer_extruder_variant", "Direct Drive Standard;Direct Drive Standard" }, + { "extruder_printable_height", "0,0" }, + { "single_extruder_multi_material", 0 }, + { "extruder_ams_count", "1#0|4#1;1#0|4#1" }, + { "filament_ids", "GFA00;GFA00" }, + { "filament_map", "1,1" }, + { "filament_map_mode", "Auto For Match" }, + { "enable_prime_tower", 1 }, + { "wipe_tower_type", "type1" }, + { "prime_tower_width", 35 }, + { "wipe_tower_x", "50" }, + { "wipe_tower_y", "50" }, + { "layer_height", "0.3" }, + // init_print applies it on top, so re-applying this config has no diff of its own. + { "gcode_comments", "1" }, + }); + size_flush_to_nozzles(config); + return config; +} + +} // namespace + +// The AMS inventory is device state that only feeds filament grouping. A changed inventory has to +// invalidate the grouping steps, while the refreshes a connected device keeps sending -- the same +// trays, volatile metadata, or an empty payload while it reconnects -- must not. +TEST_CASE("A changed AMS filament inventory invalidates the grouping steps", "[Print][MultiNozzle][Regression]") +{ + DynamicPrintConfig config = machine_inventory_config(); + Print print; + Model model; + init_print({ cube(20) }, print, model, config); + // A single-extruder print returns early in grouping, which would make the test vacuous. + REQUIRE(print.config().nozzle_diameter.size() == 2); + + print.is_BBL_printer() = true; + print.process(); + // invalidate_step() only takes back a step that is done. + REQUIRE(print.is_step_done(psWipeTower)); + REQUIRE(print.is_step_done(psSkirtBrim)); + + const std::vector> red_green = { + { loaded_filament_tray("#FF0000", "PLA", "A1") }, + { loaded_filament_tray("#00FF00", "PLA", "Ext") }, + }; + + // The setter only stashes the payload, apply() installs it. + print.set_extruder_filament_info(red_green); + CHECK(print.get_extruder_filament_info().empty()); + // No inventory on the print before this pass means "unknown", not a change. + print.apply(model, config); + REQUIRE(print.get_extruder_filament_info().size() == 2); + + // The same inventory sent again must not invalidate, even though the engine wrote its grouping + // result back into the filament maps during process(), which on its own reports a config change. + print.set_extruder_filament_info(red_green); + CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED); + + // The grouping steps must still be done here, or the invalidation below proves nothing. + REQUIRE(print.is_step_done(psWipeTower)); + REQUIRE(print.is_step_done(psSkirtBrim)); + + // One tray's colour changed and both grouping steps were done, so they are taken back. + std::vector> cyan_green = red_green; + cyan_green[0] = { loaded_filament_tray("#00FFFF", "PLA", "A1") }; + print.set_extruder_filament_info(cyan_green); + CHECK(print.apply(model, config) == PrintBase::APPLY_STATUS_INVALIDATED); + CHECK_FALSE(print.is_step_done(psWipeTower)); + CHECK_FALSE(print.is_step_done(psSkirtBrim)); + + print.process(); + REQUIRE(print.is_step_done(psWipeTower)); + + // Volatile device metadata: the loaded filaments are unchanged, so nothing is invalidated. + std::vector> retagged = cyan_green; + retagged[0][0].set_key_value("filament_changed", new ConfigOptionBool(true)); + retagged[0][0].set_key_value("tag_uid", new ConfigOptionStrings{ "A1B2C3D4" }); + retagged[0][0].set_key_value("slot_id", new ConfigOptionStrings{ "0" }); + print.set_extruder_filament_info(retagged); + CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED); + + // An empty payload means "inventory unknown" (AMS disconnected): install it, never invalidate. + print.set_extruder_filament_info({}); + CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED); + CHECK(print.get_extruder_filament_info().empty()); +} diff --git a/tests/libslic3r/test_toolordering_nozzle_group.cpp b/tests/libslic3r/test_toolordering_nozzle_group.cpp index 4a4baccb46..8526564c3d 100644 --- a/tests/libslic3r/test_toolordering_nozzle_group.cpp +++ b/tests/libslic3r/test_toolordering_nozzle_group.cpp @@ -234,6 +234,15 @@ DynamicPrintConfig loaded_filament(const std::string &colour, const std::string return tray; } +// The AMS inventory rides the next Print::apply(), which is where the grouping steps get invalidated, +// so it has to be set before the apply, not after it. +void apply_with_filament_info(Print &print, const Model &model, const DynamicPrintConfig &config, + const std::vector> &filament_info) +{ + print.set_extruder_filament_info(filament_info); + print.apply(model, config); +} + // A two-extruder Bambu printer whose master is the second extruder, as on the H2D (one nozzle on // each extruder) and the H2C (six on the second), printing PLA in the given colours. A change // between two of them flushes extruder_flush[e] on extruder e. @@ -274,11 +283,11 @@ TEST_CASE("Filament-saving grouping puts a filament on the extruder the printer Model model; model.add_object("cube", "", make_cube(20, 20, 20))->add_instance(); Print print; - print.apply(model, master_second_extruder_config(1, {"#F98C36"})); print.is_BBL_printer() = true; // Only the first (non-master) extruder holds the printed PLA. - print.set_extruder_filament_info({{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#BCBCBC", "PETG", "A2")}, - {loaded_filament("#F95D73", "PETG", "Ext")}}); + apply_with_filament_info(print, model, master_second_extruder_config(1, {"#F98C36"}), + {{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#BCBCBC", "PETG", "A2")}, + {loaded_filament("#F95D73", "PETG", "Ext")}}); auto result = ToolOrdering::get_recommended_filament_maps({{0}, {0}, {0}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {}); @@ -306,9 +315,9 @@ TEST_CASE("Filament-saving grouping prefers the master extruder when the printer Model model; model.add_object("cube", "", make_cube(20, 20, 20))->add_instance(); Print print; - print.apply(model, master_second_extruder_config(1, {"#FFFFFF", "#000000", "#808080"}, {10., 100.})); print.is_BBL_printer() = true; - print.set_extruder_filament_info({{loaded_filament("#FF0000", "PETG", "A1")}, {loaded_filament("#F95D73", "PETG", "Ext")}}); + apply_with_filament_info(print, model, master_second_extruder_config(1, {"#FFFFFF", "#000000", "#808080"}, {10., 100.}), + {{loaded_filament("#FF0000", "PETG", "A1")}, {loaded_filament("#F95D73", "PETG", "Ext")}}); auto result = ToolOrdering::get_recommended_filament_maps({{0}, {1}, {2}, {0}, {1}, {2}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {}); @@ -328,10 +337,10 @@ TEST_CASE("Convenience-mode grouping puts a filament where the printer holds its Model model; model.add_object("cube", "", make_cube(20, 20, 20))->add_instance(); Print print; - print.apply(model, config); print.is_BBL_printer() = true; - print.set_extruder_filament_info({{loaded_filament("#FFFFFF", "PLA", "A1", "GFL99")}, - {loaded_filament("#FFFFFF", "PLA", "A1", "GFA00")}}); + apply_with_filament_info(print, model, config, + {{loaded_filament("#FFFFFF", "PLA", "A1", "GFL99")}, + {loaded_filament("#FFFFFF", "PLA", "A1", "GFA00")}}); auto result = ToolOrdering::get_recommended_filament_maps({{0}, {0}, {0}}, &print, FilamentMapMode::fmmAutoForMatch, {}, {}); @@ -347,10 +356,10 @@ TEST_CASE("Filament-saving grouping on a multi-nozzle printer keeps filaments on Model model; model.add_object("cube", "", make_cube(20, 20, 20))->add_instance(); Print print; - print.apply(model, master_second_extruder_config(6, {"#F98C36", "#FFFFFF"})); print.is_BBL_printer() = true; - print.set_extruder_filament_info({{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#FFFFFF", "PLA", "A2")}, - {loaded_filament("#F95D73", "PETG", "Ext")}}); + apply_with_filament_info(print, model, master_second_extruder_config(6, {"#F98C36", "#FFFFFF"}), + {{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#FFFFFF", "PLA", "A2")}, + {loaded_filament("#F95D73", "PETG", "Ext")}}); auto result = ToolOrdering::get_recommended_filament_maps({{0}, {1}, {0}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {}); @@ -1248,3 +1257,209 @@ TEST_CASE("parse_cyclic_order parses user cyclic toolchange sequences", "[ToolOr REQUIRE(parse_cyclic_order("3,1", 4) == std::vector({2, 0})); } } + +namespace { +// One AMS slot in the raw per-tray shape the device reports it. +DynamicPrintConfig make_tray(const std::string &colour, const std::string &type, const std::string &tray_name, + bool is_support, const std::string &filament_id) +{ + DynamicPrintConfig tray; + tray.set_key_value("filament_colour", new ConfigOptionStrings{colour}); + tray.set_key_value("filament_type", new ConfigOptionStrings{type}); + tray.set_key_value("tray_name", new ConfigOptionStrings{tray_name}); + tray.set_key_value("filament_is_support", new ConfigOptionBools{is_support}); + tray.set_key_value("filament_id", new ConfigOptionStrings{filament_id}); + return tray; +} + +// The same slot plus the keys the grouping does not consume: remaining amount, temperatures, the +// change counters and the tray tags. +DynamicPrintConfig with_volatile_keys(DynamicPrintConfig tray, double remaining, int temperature, bool changed) +{ + tray.set_key_value("remaining", new ConfigOptionFloats{remaining}); + tray.set_key_value("nozzle_temperature", new ConfigOptionInts{temperature}); + tray.set_key_value("filament_changed", new ConfigOptionBools{changed}); + tray.set_key_value("tag_uid", new ConfigOptionStrings{"0123456789ABCDEF"}); + tray.set_key_value("filament_exist", new ConfigOptionBools{changed}); + return tray; +} + +// An AMS inventory payload: outer index = extruder, inner = that extruder's slots in slot order. +using AmsPayload = std::vector>; + +bool filaments_changed(const AmsPayload &old_payload, const AmsPayload &new_payload) +{ + return FilamentGroupUtils::machine_filaments_changed(old_payload, new_payload); +} +} // namespace + +// The filament grouping is invalidated by a change of the device's material inventory; a polled +// inventory that reports the same materials must leave the grouping alone. +TEST_CASE("An unchanged AMS inventory reports no filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + const AmsPayload payload = { + {make_tray("#161616", "PLA", "A1", false, "GFL99"), make_tray("#FFFFFF", "PETG", "A2", false, "GFG99")}, + {make_tray("#F95D73", "PLA", "Ext", false, "GFL99")}, + }; + + CHECK_FALSE(filaments_changed(payload, payload)); +} + +TEST_CASE("A tray colour change reports a filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + const AmsPayload before = { + {make_tray("#161616", "PLA", "A1", false, "GFL99")}, + {make_tray("#F95D73", "PLA", "Ext", false, "GFL99")}, + }; + AmsPayload after = before; + after[0][0] = make_tray("#00FFFF", "PLA", "A1", false, "GFL99"); + + CHECK(filaments_changed(before, after)); +} + +TEST_CASE("Changing only volatile AMS slot keys reports no filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + const AmsPayload before = { + {make_tray("#161616", "PLA", "A1", false, "GFL99"), make_tray("#FFFFFF", "PETG", "A2", false, "GFG99")}, + }; + AmsPayload after = before; + after[0][0] = with_volatile_keys(before[0][0], 92., 220, true); + after[0][1] = with_volatile_keys(before[0][1], 3., 250, true); + + REQUIRE(after[0][0].has("remaining")); + REQUIRE(after[0][0].has("nozzle_temperature")); + REQUIRE(after[0][0].has("filament_changed")); + REQUIRE(after[0][0].has("tag_uid")); + REQUIRE(after[0][0].has("filament_exist")); + + CHECK_FALSE(filaments_changed(before, after)); +} + +TEST_CASE("A filament sub-type change reports a filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + // Same colour and type, a different preset id: PLA Translucent instead of Generic PLA. + const AmsPayload before = {{make_tray("#161616", "PLA", "A1", false, "GFL99")}}; + AmsPayload after = before; + after[0][0] = make_tray("#161616", "PLA", "A1", false, "GFA17"); + + CHECK(filaments_changed(before, after)); +} + +TEST_CASE("Moving a tray to the external spool reports a filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + // The tray name tells an AMS slot ("A1") from the external spool ("Ext"); the same filament + // loaded in either place groups differently. + const AmsPayload in_ams = {{make_tray("#F95D73", "PLA", "A1", false, "GFL99")}}; + const AmsPayload on_ext = {{make_tray("#F95D73", "PLA", "Ext", false, "GFL99")}}; + + CHECK(filaments_changed(in_ams, on_ext)); + CHECK(filaments_changed(on_ext, in_ams)); +} + +TEST_CASE("A tray losing its support flag reports a filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + const AmsPayload support = {{make_tray("#FFFFFF", "PLA", "A1", true, "GFL99")}}; + const AmsPayload not_support = {{make_tray("#FFFFFF", "PLA", "A1", false, "GFL99")}}; + + CHECK(filaments_changed(support, not_support)); +} + +TEST_CASE("Swapping two AMS slot positions reports a filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + // The grouping keys slots by position, so two swapped trays are a different inventory even + // though the set of loaded materials is the same. + const AmsPayload before = { + {make_tray("#161616", "PLA", "A1", false, "GFL99"), make_tray("#FFFFFF", "PLA", "A2", false, "GFL99")}, + }; + AmsPayload after = before; + after[0][0] = before[0][1]; + after[0][1] = before[0][0]; + + CHECK(filaments_changed(before, after)); +} + +TEST_CASE("Adding an AMS tray reports a filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + const AmsPayload two_trays = { + {make_tray("#161616", "PLA", "A1", false, "GFL99"), make_tray("#FFFFFF", "PLA", "A2", false, "GFL99")}, + }; + const AmsPayload one_tray = {{make_tray("#161616", "PLA", "A1", false, "GFL99")}}; + + CHECK(filaments_changed(one_tray, two_trays)); + CHECK(filaments_changed(two_trays, one_tray)); +} + +TEST_CASE("An empty AMS inventory reports no filament change", "[ToolOrdering][FilamentGroup][Regression]") +{ + const AmsPayload filled = {{make_tray("#161616", "PLA", "A1", false, "GFL99")}}; + + // No payload at all is "the device has not reported yet", in either direction. + CHECK_FALSE(filaments_changed(AmsPayload{}, filled)); + CHECK_FALSE(filaments_changed(filled, AmsPayload{})); + + // A reported slot with no colour is still a reported tray, so it counts as inventory: a connected + // device that reports empty slots is not "unknown", and losing a filament there is a change. + CHECK(filaments_changed(AmsPayload{{make_tray("", "PLA", "A1", false, "GFL99")}}, filled)); +} + +TEST_CASE("An AMS slot missing a projected key is ignored by the inventory comparison", "[ToolOrdering][FilamentGroup][Regression]") +{ + const DynamicPrintConfig keeper = make_tray("#FFFFFF", "PLA", "A2", false, "GFL99"); + + SECTION("no tray name") { + // A slot that names no tray cannot be placed in the AMS, so its colour is not inventory. + DynamicPrintConfig recoloured = make_tray("#00FFFF", "PLA", "A1", false, "GFL99"); + REQUIRE(recoloured.erase("tray_name")); + DynamicPrintConfig unnamed = make_tray("#161616", "PLA", "A1", false, "GFL99"); + REQUIRE(unnamed.erase("tray_name")); + + CHECK_FALSE(filaments_changed(AmsPayload{{unnamed, keeper}}, AmsPayload{{recoloured, keeper}})); + } + + SECTION("empty tray name") { + const AmsPayload before = {{make_tray("#161616", "PLA", "", false, "GFL99"), keeper}}; + const AmsPayload after = {{make_tray("#00FFFF", "PLA", "", false, "GFL99"), keeper}}; + + CHECK_FALSE(filaments_changed(before, after)); + } + + SECTION("no filament type") { + DynamicPrintConfig retyped = make_tray("#00FFFF", "PLA", "A1", false, "GFL99"); + REQUIRE(retyped.erase("filament_type")); + DynamicPrintConfig untyped = make_tray("#161616", "PLA", "A1", false, "GFL99"); + REQUIRE(untyped.erase("filament_type")); + + CHECK_FALSE(filaments_changed(AmsPayload{{untyped, keeper}}, AmsPayload{{retyped, keeper}})); + } + + SECTION("no colour") { + const AmsPayload before = {{make_tray("", "PLA", "A1", false, "GFL99"), keeper}}; + const AmsPayload after = {{make_tray("", "PETG", "A1", false, "GFL99"), keeper}}; + + CHECK_FALSE(filaments_changed(before, after)); + } +} + +TEST_CASE("Different extruder counts are compared bucket by bucket", "[ToolOrdering][FilamentGroup][Regression]") +{ + const DynamicPrintConfig tray = make_tray("#161616", "PLA", "A1", false, "GFL99"); + + SECTION("a further extruder holding a tray is a change") { + const AmsPayload two_extruders = {{tray}, {tray}}; + AmsPayload three_extruders = two_extruders; + three_extruders.push_back({make_tray("#FFFFFF", "PETG", "A2", false, "GFG99")}); + + CHECK(filaments_changed(two_extruders, three_extruders)); + CHECK(filaments_changed(three_extruders, two_extruders)); + } + + SECTION("a second extruder that gains a tray is a change") { + // The projection always keeps two buckets, so a one-extruder payload still has an empty + // second bucket to differ from. + CHECK(filaments_changed(AmsPayload{{tray}}, AmsPayload{{tray}, {tray}})); + } + + SECTION("an extruder that holds no tray is the same as a missing one") { + CHECK_FALSE(filaments_changed(AmsPayload{{tray}}, AmsPayload{{tray}, {}})); + } +} From b2d254921c183546cc499450954761fd3b13c332 Mon Sep 17 00:00:00 2001 From: SoftFever <103989404+SoftFever@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:10:14 +0800 Subject: [PATCH 13/24] Update issue dedupe to upstream's current workflow on Claude Haiku 5.5 (#17264) --- .claude/commands/dedupe.md | 34 ++++------ .github/workflows/dedupe-issues.yml | 25 +++++--- scripts/comment-on-duplicates.sh | 95 ++++++++++++++++++++++++++++ scripts/gh.sh | 96 +++++++++++++++++++++++++++++ 4 files changed, 218 insertions(+), 32 deletions(-) create mode 100755 scripts/comment-on-duplicates.sh create mode 100755 scripts/gh.sh diff --git a/.claude/commands/dedupe.md b/.claude/commands/dedupe.md index 646a4d7fbe..e3f717aec8 100644 --- a/.claude/commands/dedupe.md +++ b/.claude/commands/dedupe.md @@ -1,5 +1,5 @@ --- -allowed-tools: Bash(gh issue view:*), Bash(gh search:*), Bash(gh issue list:*), Bash(gh api:*), Bash(gh issue comment:*) +allowed-tools: Bash(./scripts/gh.sh:*), Bash(./scripts/comment-on-duplicates.sh:*) description: Find duplicate GitHub issues --- @@ -11,28 +11,16 @@ To do this, follow these steps precisely: 2. Use an agent to view a Github issue, and ask the agent to return a summary of the issue 3. Then, launch 5 parallel agents to search Github for duplicates of this issue, using diverse keywords and search approaches, using the summary from #1 4. Next, feed the results from #1 and #2 into another agent, so that it can filter out false positives, that are likely not actually duplicates of the original issue. If there are no duplicates remaining, do not proceed. -5. Finally, comment back on the issue with a list of up to three duplicate issues (or zero, if there are no likely duplicates) +5. Finally, use the comment script to post duplicates: + ``` + ./scripts/comment-on-duplicates.sh --potential-duplicates + ``` Notes (be sure to tell this to your agents, too): -- Use `gh` to interact with Github, rather than web fetch -- Do not use other tools, beyond `gh` (eg. don't use other MCP servers, file edit, etc.) -- Make a todo list first -- For your comment, follow the following format precisely (assuming for this example that you found 3 suspected duplicates): - ---- - -Found 3 possible duplicate issues: - -1. -2. -3. - -This issue will be automatically closed as a duplicate in 3 days. - -- If your issue is a duplicate, please close it and ๐Ÿ‘ the existing issue instead -- To prevent auto-closure, add a comment or ๐Ÿ‘Ž this comment - -๐Ÿค– OrcaSlicer bot - ---- +- Use `./scripts/gh.sh` to interact with Github, rather than web fetch or raw `gh`. Examples: + - `./scripts/gh.sh issue view 123` โ€” view an issue + - `./scripts/gh.sh issue view 123 --comments` โ€” view with comments + - `./scripts/gh.sh issue list --state open --limit 20` โ€” list issues + - `./scripts/gh.sh search issues "query" --limit 10` โ€” search for issues +- Do not use other tools, beyond `./scripts/gh.sh` and the comment script (eg. don't use other MCP servers, file edit, etc.) diff --git a/.github/workflows/dedupe-issues.yml b/.github/workflows/dedupe-issues.yml index a8c21edd01..10d79c1ab4 100644 --- a/.github/workflows/dedupe-issues.yml +++ b/.github/workflows/dedupe-issues.yml @@ -23,22 +23,28 @@ jobs: uses: actions/checkout@v7 - name: Run Claude Code slash command - uses: anthropics/claude-code-base-action@beta + uses: anthropics/claude-code-action@v1 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CLAUDE_CODE_SCRIPT_CAPS: '{"comment-on-duplicates.sh":1}' with: + github_token: ${{ secrets.GITHUB_TOKEN }} + # Issues are opened by users without write access; the job's permissions and the + # allowed-tools list in .claude/commands/dedupe.md keep what Claude can do narrow. + allowed_non_write_users: "*" prompt: "/dedupe ${{ github.repository }}/issues/${{ github.event.issue.number || inputs.issue_number }}" claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} - model: "claude-sonnet-4-5-20250929" - claude_env: | - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + claude_args: '--model claude-haiku-5-5 --disallowedTools "WebFetch,WebSearch,Write,Edit,MultiEdit,NotebookEdit"' - name: Log duplicate comment event to Statsig if: always() env: STATSIG_API_KEY: ${{ secrets.STATSIG_API_KEY }} + ISSUE_NUMBER: ${{ github.event.issue.number || inputs.issue_number }} + REPO: ${{ github.repository }} + TRIGGERED_BY: ${{ github.event_name }} + WORKFLOW_RUN_ID: ${{ github.run_id }} run: | - ISSUE_NUMBER=${{ github.event.issue.number || inputs.issue_number }} - REPO=${{ github.repository }} - if [ -z "$STATSIG_API_KEY" ]; then echo "STATSIG_API_KEY not found, skipping Statsig logging" exit 0 @@ -48,7 +54,8 @@ jobs: EVENT_PAYLOAD=$(jq -n \ --arg issue_number "$ISSUE_NUMBER" \ --arg repo "$REPO" \ - --arg triggered_by "${{ github.event_name }}" \ + --arg triggered_by "$TRIGGERED_BY" \ + --arg workflow_run_id "$WORKFLOW_RUN_ID" \ '{ events: [{ eventName: "github_duplicate_comment_added", @@ -57,7 +64,7 @@ jobs: repository: $repo, issue_number: ($issue_number | tonumber), triggered_by: $triggered_by, - workflow_run_id: "${{ github.run_id }}" + workflow_run_id: $workflow_run_id }, time: (now | floor | tostring) }] diff --git a/scripts/comment-on-duplicates.sh b/scripts/comment-on-duplicates.sh new file mode 100755 index 0000000000..d42d5c8789 --- /dev/null +++ b/scripts/comment-on-duplicates.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# +# Comments on a GitHub issue with a list of potential duplicates. +# Usage: ./comment-on-duplicates.sh --potential-duplicates 456 789 101 +# +# The base issue number is read from the workflow event payload. +# + +set -euo pipefail + +REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY not set}" + +# Read from event payload so the issue number is bound to the triggering event. +# Falls back to workflow_dispatch inputs for manual runs. +BASE_ISSUE=$(jq -r '.issue.number // .inputs.issue_number // empty' "${GITHUB_EVENT_PATH:?GITHUB_EVENT_PATH not set}") +if ! [[ "$BASE_ISSUE" =~ ^[0-9]+$ ]]; then + echo "Error: no issue number in event payload" >&2 + exit 1 +fi + +DUPLICATES=() + +# Parse arguments +while [[ $# -gt 0 ]]; do + case $1 in + --potential-duplicates) + shift + while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do + DUPLICATES+=("$1") + shift + done + ;; + *) + echo "Error: unknown argument (only --potential-duplicates is accepted)" >&2 + exit 1 + ;; + esac +done + +# Validate duplicates +if [[ ${#DUPLICATES[@]} -eq 0 ]]; then + echo "Error: --potential-duplicates requires at least one issue number" >&2 + exit 1 +fi + +if [[ ${#DUPLICATES[@]} -gt 3 ]]; then + echo "Error: --potential-duplicates accepts at most 3 issues" >&2 + exit 1 +fi + +for dup in "${DUPLICATES[@]}"; do + if ! [[ "$dup" =~ ^[0-9]+$ ]]; then + echo "Error: duplicate issue must be a number, got: $dup" >&2 + exit 1 + fi +done + +# Validate that base issue exists +if ! gh issue view "$BASE_ISSUE" --repo "$REPO" &>/dev/null; then + echo "Error: issue #$BASE_ISSUE does not exist in $REPO" >&2 + exit 1 +fi + +# Validate that all duplicate issues exist +for dup in "${DUPLICATES[@]}"; do + if ! gh issue view "$dup" --repo "$REPO" &>/dev/null; then + echo "Error: issue #$dup does not exist in $REPO" >&2 + exit 1 + fi +done + +# Build comment body +COUNT=${#DUPLICATES[@]} +if [[ $COUNT -eq 1 ]]; then + HEADER="Found 1 possible duplicate issue:" +else + HEADER="Found $COUNT possible duplicate issues:" +fi + +BODY="$HEADER"$'\n\n' +INDEX=1 +for dup in "${DUPLICATES[@]}"; do + BODY+="$INDEX. https://github.com/$REPO/issues/$dup"$'\n' + ((INDEX++)) +done + +BODY+=$'\n'"This issue will be automatically closed as a duplicate in 3 days."$'\n\n' +BODY+="- If your issue is a duplicate, please close it and ๐Ÿ‘ the existing issue instead"$'\n' +BODY+="- To prevent auto-closure, add a comment or ๐Ÿ‘Ž this comment"$'\n\n' +BODY+="๐Ÿค– OrcaSlicer bot" + +# Post the comment +gh issue comment "$BASE_ISSUE" --repo "$REPO" --body "$BODY" + +echo "Posted duplicate comment on issue #$BASE_ISSUE" diff --git a/scripts/gh.sh b/scripts/gh.sh new file mode 100755 index 0000000000..f9ac524ae2 --- /dev/null +++ b/scripts/gh.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Wrapper around gh CLI that only allows specific subcommands and flags. +# All commands are scoped to the current repository via GH_REPO or GITHUB_REPOSITORY. +# +# Usage: +# ./scripts/gh.sh issue view 123 +# ./scripts/gh.sh issue view 123 --comments +# ./scripts/gh.sh issue list --state open --limit 20 +# ./scripts/gh.sh search issues "search query" --limit 10 +# ./scripts/gh.sh label list --limit 100 + +export GH_HOST=github.com + +REPO="${GH_REPO:-${GITHUB_REPOSITORY:-}}" +if [[ -z "$REPO" || "$REPO" == */*/* || "$REPO" != */* ]]; then + echo "Error: GH_REPO or GITHUB_REPOSITORY must be set to owner/repo format (e.g., GITHUB_REPOSITORY=OrcaSlicer/OrcaSlicer)" >&2 + exit 1 +fi +export GH_REPO="$REPO" + +ALLOWED_FLAGS=(--comments --state --limit --label) +FLAGS_WITH_VALUES=(--state --limit --label) + +SUB1="${1:-}" +SUB2="${2:-}" +CMD="$SUB1 $SUB2" +case "$CMD" in + "issue view"|"issue list"|"search issues"|"label list") + ;; + *) + echo "Error: only 'issue view', 'issue list', 'search issues', 'label list' are allowed (e.g., ./scripts/gh.sh issue view 123)" >&2 + exit 1 + ;; +esac + +shift 2 + +# Separate flags from positional arguments +POSITIONAL=() +FLAGS=() +skip_next=false +for arg in "$@"; do + if [[ "$skip_next" == true ]]; then + FLAGS+=("$arg") + skip_next=false + elif [[ "$arg" == -* ]]; then + flag="${arg%%=*}" + matched=false + for allowed in "${ALLOWED_FLAGS[@]}"; do + if [[ "$flag" == "$allowed" ]]; then + matched=true + break + fi + done + if [[ "$matched" == false ]]; then + echo "Error: only --comments, --state, --limit, --label flags are allowed (e.g., ./scripts/gh.sh issue list --state open --limit 20)" >&2 + exit 1 + fi + FLAGS+=("$arg") + # If flag expects a value and isn't using = syntax, skip next arg + if [[ "$arg" != *=* ]]; then + for vflag in "${FLAGS_WITH_VALUES[@]}"; do + if [[ "$flag" == "$vflag" ]]; then + skip_next=true + break + fi + done + fi + else + POSITIONAL+=("$arg") + fi +done + +if [[ "$CMD" == "search issues" ]]; then + QUERY="${POSITIONAL[0]:-}" + QUERY_LOWER=$(echo "$QUERY" | tr '[:upper:]' '[:lower:]') + if [[ "$QUERY_LOWER" == *"repo:"* || "$QUERY_LOWER" == *"org:"* || "$QUERY_LOWER" == *"user:"* ]]; then + echo "Error: search query must not contain repo:, org:, or user: qualifiers (e.g., ./scripts/gh.sh search issues \"bug report\" --limit 10)" >&2 + exit 1 + fi + gh "$SUB1" "$SUB2" "$QUERY" --repo "$REPO" "${FLAGS[@]}" +elif [[ "$CMD" == "issue view" ]]; then + if [[ ${#POSITIONAL[@]} -ne 1 ]] || ! [[ "${POSITIONAL[0]}" =~ ^[0-9]+$ ]]; then + echo "Error: issue view requires exactly one numeric issue number (e.g., ./scripts/gh.sh issue view 123)" >&2 + exit 1 + fi + gh "$SUB1" "$SUB2" "${POSITIONAL[0]}" "${FLAGS[@]}" +else + if [[ ${#POSITIONAL[@]} -ne 0 ]]; then + echo "Error: issue list and label list do not accept positional arguments (e.g., ./scripts/gh.sh issue list --state open, ./scripts/gh.sh label list --limit 100)" >&2 + exit 1 + fi + gh "$SUB1" "$SUB2" "${FLAGS[@]}" +fi From 6114c7b496ca64bd3e5d372c5df6f12a6deac248 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 5 Nov 2026 00:23:52 +0800 Subject: [PATCH 14/24] Fix the duplicate backfill workflow and run it in paced batches of open issues --- .../workflows/backfill-duplicate-comments.yml | 23 ++++++++--- scripts/backfill-duplicate-comments.ts | 38 ++++++++++++++----- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/.github/workflows/backfill-duplicate-comments.yml b/.github/workflows/backfill-duplicate-comments.yml index 118e619369..5b46df8331 100644 --- a/.github/workflows/backfill-duplicate-comments.yml +++ b/.github/workflows/backfill-duplicate-comments.yml @@ -4,10 +4,20 @@ description: Triggers duplicate detection for old issues that don't have duplica on: workflow_dispatch: inputs: - days_back: - description: 'How many days back to look for old issues' + min_issue_number: + description: 'Lowest issue number to process' required: false - default: '90' + default: '1' + type: string + max_issue_number: + description: 'Only process issues below this number (empty for no upper bound); the previous run logs the value to continue from' + required: false + default: '' + type: string + limit: + description: 'Maximum number of dedupe runs to start, one every 30 seconds' + required: false + default: '100' type: string dry_run: description: 'Dry run mode (true to only log what would be done)' @@ -21,7 +31,8 @@ on: jobs: backfill-duplicate-comments: runs-on: ubuntu-latest - timeout-minutes: 30 + # Dispatches are spaced 30 seconds apart, so a large limit runs for hours + timeout-minutes: 360 permissions: contents: read issues: read @@ -40,5 +51,7 @@ jobs: run: bun run scripts/backfill-duplicate-comments.ts env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DAYS_BACK: ${{ inputs.days_back }} + MIN_ISSUE_NUMBER: ${{ inputs.min_issue_number }} + MAX_ISSUE_NUMBER: ${{ inputs.max_issue_number }} + LIMIT: ${{ inputs.limit }} DRY_RUN: ${{ inputs.dry_run }} \ No newline at end of file diff --git a/scripts/backfill-duplicate-comments.ts b/scripts/backfill-duplicate-comments.ts index 5c024d6abf..2ad5042553 100644 --- a/scripts/backfill-duplicate-comments.ts +++ b/scripts/backfill-duplicate-comments.ts @@ -14,6 +14,7 @@ interface GitHubIssue { user: { id: number }; created_at: string; closed_at?: string; + pull_request?: unknown; } interface GitHubComment { @@ -57,7 +58,7 @@ async function triggerDedupeWorkflow( } await githubRequest( - `/repos/${owner}/${repo}/actions/workflows/claude-dedupe-issues.yml/dispatches`, + `/repos/${owner}/${repo}/actions/workflows/dedupe-issues.yml/dispatches`, token, 'POST', { @@ -82,19 +83,25 @@ Usage: Environment Variables: GITHUB_TOKEN - GitHub personal access token with repo and actions permissions (required) DRY_RUN - Set to "false" to actually trigger workflows (default: true for safety) - MAX_ISSUE_NUMBER - Only process issues with numbers less than this value (default: 4050)`); + MIN_ISSUE_NUMBER - Only process issues with numbers at or above this value (default: 1) + MAX_ISSUE_NUMBER - Only process issues with numbers less than this value (default: no limit) + LIMIT - Stop after triggering this many workflows (default: 100)`); } console.log("[DEBUG] GitHub token found"); const owner = "OrcaSlicer"; const repo = "OrcaSlicer"; const dryRun = process.env.DRY_RUN !== "false"; - const maxIssueNumber = parseInt(process.env.MAX_ISSUE_NUMBER || "11000", 10); + const maxIssueNumber = process.env.MAX_ISSUE_NUMBER ? parseInt(process.env.MAX_ISSUE_NUMBER, 10) : Infinity; const minIssueNumber = parseInt(process.env.MIN_ISSUE_NUMBER || "1", 10); + const limit = parseInt(process.env.LIMIT || "100", 10); + // A dedupe run takes about 2.5 minutes, so this keeps about five running at once and + // leaves the rest of the Actions runners and the Claude subscription free for other work. + const dispatchIntervalMs = 30_000; console.log(`[DEBUG] Repository: ${owner}/${repo}`); console.log(`[DEBUG] Dry run mode: ${dryRun}`); - console.log(`[DEBUG] Looking at issues between #${minIssueNumber} and #${maxIssueNumber}`); + console.log(`[DEBUG] Looking at open issues between #${minIssueNumber} and #${maxIssueNumber}, triggering at most ${limit}`); console.log(`[DEBUG] Fetching issues between #${minIssueNumber} and #${maxIssueNumber}...`); const allIssues: GitHubIssue[] = []; @@ -103,15 +110,15 @@ Environment Variables: while (true) { const pageIssues: GitHubIssue[] = await githubRequest( - `/repos/${owner}/${repo}/issues?state=all&per_page=${perPage}&page=${page}&sort=created&direction=desc`, + `/repos/${owner}/${repo}/issues?state=open&per_page=${perPage}&page=${page}&sort=created&direction=desc`, token ); if (pageIssues.length === 0) break; - // Filter to only include issues within the specified range + // Filter to only include issues within the specified range; the issues endpoint also lists pull requests const filteredIssues = pageIssues.filter(issue => - issue.number >= minIssueNumber && issue.number < maxIssueNumber + !issue.pull_request && issue.number >= minIssueNumber && issue.number < maxIssueNumber ); allIssues.push(...filteredIssues); @@ -141,8 +148,13 @@ Environment Variables: let processedCount = 0; let candidateCount = 0; let triggeredCount = 0; + let lowestTriggered: number | undefined; for (const issue of allIssues) { + if (triggeredCount >= limit) { + console.log(`[DEBUG] Reached the limit of ${limit} workflows, stopping`); + break; + } processedCount++; console.log( `[DEBUG] Processing issue #${issue.number} (${processedCount}/${allIssues.length}): ${issue.title}` @@ -150,7 +162,7 @@ Environment Variables: console.log(`[DEBUG] Fetching comments for issue #${issue.number}...`); const comments: GitHubComment[] = await githubRequest( - `/repos/${owner}/${repo}/issues/${issue.number}/comments`, + `/repos/${owner}/${repo}/issues/${issue.number}/comments?per_page=100`, token ); console.log( @@ -192,19 +204,25 @@ Environment Variables: ); } triggeredCount++; + lowestTriggered = issue.number; } catch (error) { console.error( `[ERROR] Failed to trigger workflow for issue #${issue.number}: ${error}` ); } - // Add a delay between workflow triggers to avoid overwhelming the system - await new Promise(resolve => setTimeout(resolve, 1000)); + if (!dryRun) { + await new Promise(resolve => setTimeout(resolve, dispatchIntervalMs)); + } } console.log( `[DEBUG] Script completed. Processed ${processedCount} issues, found ${candidateCount} candidates without duplicate comments, ${dryRun ? 'would trigger' : 'triggered'} ${triggeredCount} workflows` ); + // Issues with no duplicates get no comment, so a later run would pick them again; continue below this batch instead. + if (lowestTriggered !== undefined) { + console.log(`[INFO] To continue with older issues, run again with max_issue_number set to ${lowestTriggered}`); + } } backfillDuplicateComments().catch(console.error); From 91b0c36c5434bfc0fa80840a1767a68617d256b1 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 5 Nov 2026 00:32:51 +0800 Subject: [PATCH 15/24] Let backfill-dispatched issue dedupe runs start --- .github/workflows/dedupe-issues.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/dedupe-issues.yml b/.github/workflows/dedupe-issues.yml index 10d79c1ab4..100cb01fee 100644 --- a/.github/workflows/dedupe-issues.yml +++ b/.github/workflows/dedupe-issues.yml @@ -32,6 +32,8 @@ jobs: # Issues are opened by users without write access; the job's permissions and the # allowed-tools list in .claude/commands/dedupe.md keep what Claude can do narrow. allowed_non_write_users: "*" + # The backfill workflow dispatches this one with GITHUB_TOKEN, so those runs come from github-actions[bot] + allowed_bots: "github-actions" prompt: "/dedupe ${{ github.repository }}/issues/${{ github.event.issue.number || inputs.issue_number }}" claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} claude_args: '--model claude-haiku-5-5 --disallowedTools "WebFetch,WebSearch,Write,Edit,MultiEdit,NotebookEdit"' From 8add55f17b65b853b56ca2c2b38ed67344d42803 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 5 Nov 2026 01:11:12 +0800 Subject: [PATCH 16/24] Allow the issue dedupe agents to use the GitHub helper scripts --- .claude/commands/dedupe.md | 3 ++- .github/workflows/dedupe-issues.yml | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.claude/commands/dedupe.md b/.claude/commands/dedupe.md index e3f717aec8..8097ea0478 100644 --- a/.claude/commands/dedupe.md +++ b/.claude/commands/dedupe.md @@ -20,7 +20,8 @@ Notes (be sure to tell this to your agents, too): - Use `./scripts/gh.sh` to interact with Github, rather than web fetch or raw `gh`. Examples: - `./scripts/gh.sh issue view 123` โ€” view an issue - - `./scripts/gh.sh issue view 123 --comments` โ€” view with comments + - `./scripts/gh.sh issue view 123 --comments` โ€” view only the comments (prints nothing when there are none) - `./scripts/gh.sh issue list --state open --limit 20` โ€” list issues - `./scripts/gh.sh search issues "query" --limit 10` โ€” search for issues +- Run each script call as a plain command like the examples, with no `cd`, environment variables, pipes, redirects or `;`/`&&` chains: anything else is refused - Do not use other tools, beyond `./scripts/gh.sh` and the comment script (eg. don't use other MCP servers, file edit, etc.) diff --git a/.github/workflows/dedupe-issues.yml b/.github/workflows/dedupe-issues.yml index 100cb01fee..e10f79ba7e 100644 --- a/.github/workflows/dedupe-issues.yml +++ b/.github/workflows/dedupe-issues.yml @@ -36,7 +36,9 @@ jobs: allowed_bots: "github-actions" prompt: "/dedupe ${{ github.repository }}/issues/${{ github.event.issue.number || inputs.issue_number }}" claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} - claude_args: '--model claude-haiku-5-5 --disallowedTools "WebFetch,WebSearch,Write,Edit,MultiEdit,NotebookEdit"' + # The allowed-tools in .claude/commands/dedupe.md cover only the command's own turn, not the + # agents it starts, so the same two scripts are allowed for the whole session here. + claude_args: '--model claude-haiku-5-5 --allowedTools "Bash(./scripts/gh.sh:*),Bash(./scripts/comment-on-duplicates.sh:*)" --disallowedTools "WebFetch,WebSearch,Write,Edit,MultiEdit,NotebookEdit"' - name: Log duplicate comment event to Statsig if: always() From 79985162e4c83a0749dbebeb77dff562aeca45da Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 5 Nov 2026 01:31:46 +0800 Subject: [PATCH 17/24] Keep issue dedupe agents in the foreground so runs finish --- .github/workflows/dedupe-issues.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/dedupe-issues.yml b/.github/workflows/dedupe-issues.yml index e10f79ba7e..3e9809a9f8 100644 --- a/.github/workflows/dedupe-issues.yml +++ b/.github/workflows/dedupe-issues.yml @@ -27,6 +27,9 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} CLAUDE_CODE_SCRIPT_CAPS: '{"comment-on-duplicates.sh":1}' + # The action stops at Claude's first result, so a turn that ends while a background agent + # still works would drop the rest of the dedupe; keep agents in the foreground. + CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1" with: github_token: ${{ secrets.GITHUB_TOKEN }} # Issues are opened by users without write access; the job's permissions and the From dd0079ec64ac4d9fc7077ec6b5d67683e8a531eb Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:57:23 +0800 Subject: [PATCH 18/24] Start the Orca Cloud Sync Cursor at Zero (#17263) Fixes #17256 On a machine with no saved `sync_state`, the first `sync/pull` sent whatever was in memory as `?cursor=`. The server answered 400, nothing was downloaded, and the account's presets never arrived because only a 410 clears the cursor. `SyncState::last_sync_timestamp` now starts at zero, so a session with no saved state pulls everything. `SyncPullResponse::next_cursor` had the same problem on a 304, where a stray value would have been saved to `sync_state` and sent on every later pull, so it and the other scalars in `ProfileUpsert` and `SyncPushResult` start at zero too. --- src/slic3r/Utils/OrcaCloudServiceAgent.hpp | 18 +++++++-------- tests/slic3rutils/test_orca_cloud_agent.cpp | 25 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/slic3r/Utils/OrcaCloudServiceAgent.hpp b/src/slic3r/Utils/OrcaCloudServiceAgent.hpp index 6518159c8c..7768c02f25 100644 --- a/src/slic3r/Utils/OrcaCloudServiceAgent.hpp +++ b/src/slic3r/Utils/OrcaCloudServiceAgent.hpp @@ -81,28 +81,28 @@ struct ProfileUpsert { std::string id; std::string name; nlohmann::json content; - long long updated_time; - long long created_time; + long long updated_time = 0; + long long created_time = 0; }; struct SyncPullResponse { - long long next_cursor; + long long next_cursor = 0; std::vector upserts; std::vector deletes; }; struct SyncPushResult { - bool success; - int http_code; - int conflict_code; - long long new_updated_time; + bool success = false; + int http_code = 0; + int conflict_code = 0; + long long new_updated_time = 0; ProfileUpsert server_version; - bool server_deleted; + bool server_deleted = false; std::string error_message; }; struct SyncState { - long long last_sync_timestamp; + long long last_sync_timestamp = 0; }; #endif // ORCA_SYNC_STRUCTS_DEFINED diff --git a/tests/slic3rutils/test_orca_cloud_agent.cpp b/tests/slic3rutils/test_orca_cloud_agent.cpp index 5f70d8c62a..b386a15fd6 100644 --- a/tests/slic3rutils/test_orca_cloud_agent.cpp +++ b/tests/slic3rutils/test_orca_cloud_agent.cpp @@ -876,3 +876,28 @@ TEST_CASE("A delete that fails to reach the gateway keeps its .info for a later CHECK(fs::exists(fixture.info_path)); CHECK(fixture.queue.size() == 1); } + +TEST_CASE_METHOD(HealthCheckFixture, "A session with no saved sync state pulls without a cursor", "[OrcaCloudServiceAgent]") +{ + // Nothing has been pulled yet, so there is no cursor to resume from. + CHECK(agent->get_sync_state().last_sync_timestamp == 0); + + sign_in("user-a"); + server.set_reply("200 OK", R"({"upserts":[],"deletes":[],"next_cursor":0})"); + REQUIRE(agent->get_setting_list2("", nullptr, nullptr, nullptr) == BAMBU_NETWORK_SUCCESS); + + const auto requests = server.requests(); + REQUIRE(requests.size() == 1); + CHECK(requests.front().request_line == "GET /api/v1/sync/pull HTTP/1.1"); +} + +TEST_CASE_METHOD(HealthCheckFixture, "A pull answered 304 keeps the sync state it had", "[OrcaCloudServiceAgent]") +{ + sign_in("user-a"); + server.set_reply("304 Not Modified", ""); + REQUIRE(agent->get_setting_list2("", nullptr, nullptr, nullptr) == BAMBU_NETWORK_SUCCESS); + + // Nothing changed, so there is still no cursor and none is written for the next session. + CHECK(agent->get_sync_state().last_sync_timestamp == 0); + CHECK_FALSE(fs::exists(dir.path() / "user" / "user-a" / "sync_state")); +} From 1a61ffd32ed215eb724ae706a20c9b139754b48e Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:59:04 +0800 Subject: [PATCH 19/24] Keep a Filament Slot Past the Colour Arrays From Staying Frozen (#17262) PlaterPresetComboBox::update() froze the combo and returned without thawing it when the slot had no colour icon, which happens on a tool changer whenever filament_presets is topped up to the tool count while the colour arrays keep the project's shorter length. The leaked freeze count left the combo unpainted for the rest of the session. The slot now shows a blank swatch and still fills its list, and update_ams_color() grows the colour arrays to the slot before writing, as sync_colour_config() already does. --- src/slic3r/GUI/PresetComboBoxes.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/slic3r/GUI/PresetComboBoxes.cpp b/src/slic3r/GUI/PresetComboBoxes.cpp index 15b23a6cd1..ea0a41c39a 100644 --- a/src/slic3r/GUI/PresetComboBoxes.cpp +++ b/src/slic3r/GUI/PresetComboBoxes.cpp @@ -314,6 +314,11 @@ int PresetComboBox::update_ams_color() auto color_pack = static_cast(cfg->option("filament_multi_colour")->clone()); // multi color (all colors in all kinds of filament) auto color_type = static_cast(cfg->option("filament_colour_type")->clone()); // color type + // The slot can lie past the colour arrays (see sync_colour_config()). + if (m_filament_idx >= color_head->values.size()) color_head->values.resize(m_filament_idx + 1); + if (m_filament_idx >= color_pack->values.size()) color_pack->values.resize(m_filament_idx + 1); + if (m_filament_idx >= color_type->values.size()) color_type->values.resize(m_filament_idx + 1); + color_head->values[m_filament_idx] = color; color_type->values[m_filament_idx] = ctype; std::string color_str = ""; // Translate multi color info to config storage format @@ -1180,12 +1185,12 @@ void PlaterPresetComboBox::update() const Preset* selected_filament_preset = nullptr; if (m_type == Preset::TYPE_FILAMENT) { + // The slot can lie past the colour arrays: it still lists its presets, with a blank swatch. std::vector bitmaps = get_extruder_color_icons(true); - if (m_filament_idx < bitmaps.size()) { + if (m_filament_idx < bitmaps.size()) clr_picker->SetBitmap(*bitmaps[m_filament_idx]); - } else { - return; - } + else + clr_picker->SetBitmap(*get_extruder_color_icon("#F0F0F0FF", std::to_string(m_filament_idx + 1), lround(2 * m_em_unit), lround(2 * m_em_unit))); #ifdef __WXOSX__ clr_picker->SetLabel(clr_picker->GetLabel()); // Let setBezelStyle: be called clr_picker->Refresh(); From 834c6987e066b1ff565d57e47e21c8fb8f85eb7f Mon Sep 17 00:00:00 2001 From: Rodrigo Faselli <162915171+RF47@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:34:00 -0300 Subject: [PATCH 20/24] Hide lightning angles if there is no infill (#17277) --- src/slic3r/GUI/ConfigManipulation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slic3r/GUI/ConfigManipulation.cpp b/src/slic3r/GUI/ConfigManipulation.cpp index dd2d7e590e..97cf6b9cea 100644 --- a/src/slic3r/GUI/ConfigManipulation.cpp +++ b/src/slic3r/GUI/ConfigManipulation.cpp @@ -1349,7 +1349,7 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in for (auto el : { "lateral_lattice_angle_1", "lateral_lattice_angle_2"}) toggle_line(el, lattice_options, -1, _L("Select the Lateral Lattice sparse infill pattern to use this setting.")); - bool lightning_options = config->opt_enum("sparse_infill_pattern") == InfillPattern::ipLightning; + bool lightning_options = config->opt_enum("sparse_infill_pattern") == InfillPattern::ipLightning && have_infill; for (auto el : { "lightning_overhang_angle", "lightning_prune_angle", "lightning_straightening_angle" }) toggle_line(el, lightning_options, -1, _L("Select the Lightning sparse infill pattern to use this setting.")); From bd3e9aeb96b847e661750bf89ee4e8711a6b0e20 Mon Sep 17 00:00:00 2001 From: Lam Wei Lun Date: Thu, 5 Nov 2026 11:34:33 +0800 Subject: [PATCH 21/24] fix: stop the Speed Dial dismissing itself on the first open (#17245) * fix: stop the Speed Dial dismissing itself on the first open Opening the dial with Space and not touching anything closed it again a moment later, on GNOME and KDE, X11 and Wayland, and only on the first open. The dial hides on wxEVT_ACTIVATE(false), but wxGTK does not deliver that event to the window that lost the focus: gtk_frame_focus_out_callback sends it to g_activeFrame, the toplevel that was activated last (wx src/gtk/toplevel.cpp:192-205). A deactivation that belongs to another window, or the same one arriving while the dial is still taking the focus, therefore read as "the user dismissed the dial". The first open is the only one that maps the window, moves it, resizes it to its content and grabs focus into a web view that has never held it, so it is the only open exposed to that ordering. Validate the dismissal instead of trusting the event: arm a 150 ms one-shot, cancelled by any activation, and hide only if the dial is still shown and its window is no longer active. On GTK ask the window with gtk_window_is_active(), because wxTopLevelWindow::IsActive() resolves through wx focus tracking, which does not follow the focus that WebKit's native widget takes. Also skip the pre-map focus grab on the first open: at that point wxGTK has not mapped the window yet, so the grab cannot land. speed_dial_should_hide() is a free function, so the rule is covered by tests/slic3rutils/test_speed_dial_dismiss.cpp without a GUI. * docs(wxwidgets-skill): document the validated Speed Dial deactivation Section 10 described the dial's old handler, which hid on every wxEVT_ACTIVATE(false). The skill is the review ground truth, so it has to match the code: the deactivation is now validated after a settle interval against the window's real active state, because wxGTK sends that event to the last activated toplevel whatever window lost the focus. * Ignore Page Changes of Inner Books in the Main Tab Handler The main frame's tab-panel handler receives the page-changed event of any book inside a page, because wxBookCtrlEvent propagates and the Calibration page's Tabbook has no handler of its own. It then treated the inner page switch as a main tab change: it reset the selected tab, toggled the undo/redo buttons and called SetFocus() on the current page. On wxGTK, SetFocus() on a child of a visible but inactive top-level window presents that window. While the Calibration page is built in the background after start-up, this re-activated the main window and the Speed Dial, which hides when it loses the focus, closed by itself a moment after its first open on Linux. Only act on events whose object is the main tab panel. * Include wx/timer.h Where the Speed Dial Binds Its Timer * Describe the Real Cause of the Speed Dial's First-Open Close The deferred, re-checked hide absorbs a focus bounce shorter than its delay. It did not stop the first-open close, which was the main frame activating itself from its tab handler; say so in the comments, the test and the skill reference instead of describing a misdelivered deactivation. --------- Co-authored-by: Hanif Koh --- .../orca-wxwidgets/references/popups-menus.md | 40 +++++++++-- src/slic3r/GUI/MainFrame.cpp | 8 +++ src/slic3r/GUI/SpeedDialDialog.cpp | 66 +++++++++++++++++-- src/slic3r/GUI/SpeedDialDialog.hpp | 16 +++++ tests/slic3rutils/CMakeLists.txt | 1 + tests/slic3rutils/test_speed_dial_dismiss.cpp | 37 +++++++++++ 6 files changed, 158 insertions(+), 10 deletions(-) create mode 100644 tests/slic3rutils/test_speed_dial_dismiss.cpp diff --git a/.claude/skills/orca-wxwidgets/references/popups-menus.md b/.claude/skills/orca-wxwidgets/references/popups-menus.md index d165ceff0a..e96e00dfaa 100644 --- a/.claude/skills/orca-wxwidgets/references/popups-menus.md +++ b/.claude/skills/orca-wxwidgets/references/popups-menus.md @@ -81,6 +81,11 @@ Contents: [Rules](#rules) ยท [1. Choosing the window kind](#1-choosing-the-windo tooltip of a widget in that popup, or in a popup opened from it, is on screen: the tooltip has taken the keyboard while the user is still on the popup. `PopupWindow::topWindowActiavate` does it for every Orca popup; a popup outside `PopupWindow` with such a hook must do it itself. (ยง9) +31. When a dialog that hides on deactivation closes by itself, find the code that activated another window + instead of hardening the hook: on wxGTK, `SetFocus()` on a child of a visible, inactive toplevel presents + that toplevel. A handler bound on a book control acts only on events whose object is that book, because a + page-changed event from a book inside a page propagates up to it. A deferred, re-checked hide tolerates only + a focus bounce shorter than its delay. (ยง10) ## 1. Choosing the window kind @@ -827,8 +832,9 @@ created with `wxBORDER_NONE | wxFRAME_NO_TASKBAR | wxFRAME_FLOAT_ON_PARENT | wxF - `wxFRAME_NO_TASKBAR` gives no taskbar entry on MSW/GTK, on GTK only when the WM supports `_NET_WM_STATE_SKIP_TASKBAR` (`interface/wx/frame.h:97-103`). - `wxFRAME_FLOAT_ON_PARENT` requires a non-null parent (`interface/wx/frame.h:104-106`). -- Its `wxEVT_ACTIVATE` handler hides on deactivation and `Skip()`s. On activation it focuses the web view, because - modeless focus is granted asynchronously and a focus request made right after `Show()` is dropped. +- Its `wxEVT_ACTIVATE` handler focuses the web view on activation, because modeless focus is granted + asynchronously and a focus request made right after `Show()` is dropped. It hides on deactivation after a + short settle delay and a re-check of `gtk_window_is_active()` (Pitfalls below), and it `Skip()`s. - On Linux `focus_webview` grabs focus on the WebKit native widget (`gtk_widget_grab_focus` on `GetNativeBackend()`). `browser()->SetFocus()` focuses only the container. - Display-only web content can stay in a transient popup (`MarkdownTip`). @@ -847,13 +853,39 @@ created with `wxBORDER_NONE | wxFRAME_NO_TASKBAR | wxFRAME_FLOAT_ON_PARENT | wxF wxBORDER_NONE | wxFRAME_NO_TASKBAR | wxFRAME_FLOAT_ON_PARENT | wxFRAME_SHAPED) { Bind(wxEVT_ACTIVATE, [this](wxActivateEvent& e) { - if (e.GetActive() && IsShown()) focus_webview(browser(), m_page_ready); - else if (!e.GetActive() && IsShown()) Hide(); + if (!IsShown()) { e.Skip(); return; } + if (e.GetActive()) { m_hide_timer.Stop(); focus_webview(browser(), m_page_ready); } + else schedule_hide(); // validated, see the next rule e.Skip(); }); } ``` Cite: f142716e51, a86202b45b (`SpeedDialPopup.cpp` replaced by `SpeedDialDialog.{hpp,cpp}`; `GUI_App.cpp`). +- **Rule:** When a dialog that hides on deactivation closes by itself, find the code that activated another + window; do not harden the dismissal hook. A handler bound on a book control checks that `e.GetEventObject()` + is that book before acting. + **Why:** On wxGTK, `wxWindow::SetFocus()` on a child of a visible but inactive toplevel calls + `gtk_window_present` on that toplevel (`src/gtk/window.cpp:5157-5162`), so an unexpected `SetFocus()` anywhere + in the main frame takes the keyboard from a modeless dialog that hides on deactivation. The Speed Dial closed + by itself a moment after the first Space on Linux (GNOME and KDE, X11 and Wayland): the idle builder + constructed the Calibration page, whose `Tabbook::InsertPage` emitted `wxEVT_BOOKCTRL_PAGE_CHANGED`; the event + propagated, as every `wxNotifyEvent` does, to the main frame's `m_tabpanel` handler + (`wxEVT_NOTEBOOK_PAGE_CHANGED` is the same type, `include/wx/bookctrl.h:434`), which treated it as a main tab + change and ended with `panel->SetFocus()`. Found with a 10 ms focus poller and a backtrace on + `gtk_window_present`. MSW and macOS `SetFocus()` do not activate the toplevel, so the bug was Linux-only. The + dial's deferred, re-checked hide (`kHideSettleMs`, `gtk_window_is_active()`, since `wxTopLevelWindowGTK::IsActive()` + answers from `g_activeFrame`, which the deactivation has already cleared) absorbs only a focus bounce shorter + than the delay; it did not stop this. + ```cpp + // Wrong: the main book's handler acts on every page-changed event that reaches it + m_tabpanel->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, [this](wxBookCtrlEvent& e) { /* ... */ panel->SetFocus(); }); + // Right: only the book's own events + m_tabpanel->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, [this](wxBookCtrlEvent& e) { + if (e.GetEventObject() != m_tabpanel) { e.Skip(); return; } + /* ... */ + }); + ``` + Cite: #17245 (`MainFrame::init_tabpanel`; `SpeedDialWebDialog::on_hide_timer`). - **Rule:** When restoring the main frame after hiding a popup or overlay frame, call `Show()` only if `!IsShown()`, and `Raise()` unconditionally (top-level `Show`/`Raise` are owned by `references/windows-dialogs.md`). diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index 203af85de2..7feed2ca47 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -1510,6 +1510,14 @@ void MainFrame::init_tabpanel() { #else m_tabpanel->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, [this](wxBookCtrlEvent& e) { #endif + // A page's own book (the Calibration page's Tabbook) emits the same event, and it propagates + // up here. Treating it as a main tab change resets the selected tab and the undo/redo state, + // and the SetFocus() below re-activates the main window on wxGTK, which dismisses the Speed + // Dial when the page is built in the background while the dial is open. + if (e.GetEventObject() != m_tabpanel) { + e.Skip(); + return; + } //BBS wxWindow* panel = m_tabpanel->GetCurrentPage(); //wxString page_text = m_tabpanel->GetPageText(sel); diff --git a/src/slic3r/GUI/SpeedDialDialog.cpp b/src/slic3r/GUI/SpeedDialDialog.cpp index 17fe5ccfeb..e8086f71e5 100644 --- a/src/slic3r/GUI/SpeedDialDialog.cpp +++ b/src/slic3r/GUI/SpeedDialDialog.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -48,6 +49,10 @@ namespace { constexpr int kPopupWidth = 540; constexpr int kPopupMinHeight = 60; // just above the bare search-bar height, so the dialog hugs content constexpr int kPopupMaxHeight = 282; +// Delay between a deactivation and the auto-hide decision, so that a focus bounce shorter than this (the +// keyboard leaving and coming back within the interval) does not dismiss the dial. A window that really +// takes the focus still hides it when the timer fires. +constexpr int kHideSettleMs = 150; int json_int_or(const nlohmann::json& j, const char* key, int fallback) { @@ -146,6 +151,8 @@ wxPoint speed_dial_origin(const wxRect& parent_screen_rect, const wxRect& work_a std::clamp(y, work_area.y, work_area.y + std::max(0, work_area.height - box_size.GetHeight()))}; } +bool speed_dial_should_hide(bool shown, bool active) { return shown && !active; } + SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent) : WebViewHostDialog(parent, wxID_ANY, @@ -160,14 +167,26 @@ SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent) // keeps that position for every later Show(). position_over_parent() supplies the origin instead. gtk_window_set_position(GTK_WINDOW(GetHandle()), GTK_WIN_POS_NONE); #endif + // The dial dismisses itself when the focus leaves it. The hide is deferred by kHideSettleMs and + // re-checked, so a focus bounce shorter than that is not a dismissal. It does not protect against + // another window being activated: the first-open close on Linux was the main frame's tab handler + // calling SetFocus() while the Calibration page was built in the background, which on wxGTK presents + // the main window (fixed in MainFrame::init_tabpanel). + m_hide_timer.SetOwner(this); + Bind(wxEVT_TIMER, &SpeedDialWebDialog::on_hide_timer, this); Bind(wxEVT_ACTIVATE, [this](wxActivateEvent& event) { // Focus the WebKit widget exactly when the WM makes the popup the active window // (modeless focus is granted asynchronously, so a focus request made right after // Show() is dropped). Also re-corrects focus on every re-open. - if (event.GetActive() && IsShown()) + if (!IsShown()) { + event.Skip(); + return; + } + if (event.GetActive()) { + m_hide_timer.Stop(); focus_webview(browser(), m_page_ready); - else if (!event.GetActive() && IsShown()) - Hide(); + } else + schedule_hide(); event.Skip(); }); if (!create_webview("web/dialog/SpeedDial/index.html", wxEmptyString, wxSize(kPopupWidth, kPopupMaxHeight), @@ -192,7 +211,11 @@ SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent) position_over_parent(); } -SpeedDialWebDialog::~SpeedDialWebDialog() { m_alive->store(false, std::memory_order_release); } +SpeedDialWebDialog::~SpeedDialWebDialog() +{ + m_hide_timer.Stop(); + m_alive->store(false, std::memory_order_release); +} nlohmann::json SpeedDialWebDialog::localized_strings() const { return speed_dial_ui_strings(); } @@ -217,8 +240,36 @@ void SpeedDialWebDialog::position_over_parent() #endif } +void SpeedDialWebDialog::schedule_hide() +{ + if (IsShown()) + m_hide_timer.StartOnce(kHideSettleMs); +} + +bool SpeedDialWebDialog::is_active() +{ +#ifdef __WXGTK__ + GtkWindow* const window = GTK_WINDOW(GetHandle()); + return window && gtk_window_is_active(window); +#else + return IsActive(); +#endif +} + +void SpeedDialWebDialog::on_hide_timer(wxTimerEvent&) +{ + if (!m_alive->load(std::memory_order_acquire)) + return; + if (!speed_dial_should_hide(IsShown(), is_active())) + return; + Hide(); +} + void SpeedDialWebDialog::request_show() { + // A pending auto-hide belongs to the previous open. + m_hide_timer.Stop(); + // Re-derived on every open: the dialog is a long-lived hidden window, so without this the // coordinates stay at the frame's position from the first open and the dial stops following the // frame when it is moved, resized, or dragged to another display. @@ -237,8 +288,11 @@ void SpeedDialWebDialog::request_show() if (m_page_ready) send_actions(); // Grab focus now and again on wxEVT_ACTIVATE; grabbing directly on the WebKit widget is - // what makes typing reach the search field immediately on open. - focus_webview(browser(), m_page_ready); + // what makes typing reach the search field immediately on open. Skipped while the page is still + // loading: on the first open the window is not mapped yet, so the grab would land on a window the + // WM has not activated - the ACTIVATE handler grabs it once it has. + if (m_page_ready) + focus_webview(browser(), true); repaint_webview(); // A position requested before the window is mapped can be dropped, so reapply once it is up. wxGetApp().CallAfter([this, alive = m_alive]() { diff --git a/src/slic3r/GUI/SpeedDialDialog.hpp b/src/slic3r/GUI/SpeedDialDialog.hpp index 851aaea7f5..9fe28d7510 100644 --- a/src/slic3r/GUI/SpeedDialDialog.hpp +++ b/src/slic3r/GUI/SpeedDialDialog.hpp @@ -9,6 +9,7 @@ #include #include +#include class wxWindow; @@ -20,6 +21,11 @@ namespace Slic3r { namespace GUI { // resize in resize_to_content() never moves the window. wxPoint speed_dial_origin(const wxRect& parent_screen_rect, const wxRect& work_area, const wxSize& box_size); +// Whether a deactivation really dismissed the dial: only when it is still shown and no longer holds the +// focus. Evaluated after the settle delay, never on the event itself, so a focus bounce shorter than the +// delay is ignored. +bool speed_dial_should_hide(bool shown, bool active); + class SpeedDialWebDialog : public WebViewHostDialog { public: @@ -35,6 +41,14 @@ private: // on every open, since the dialog is a long-lived hidden window: without this the coordinates // stay at the frame's position from the first open (frozen at the first map by the WM). void position_over_parent(); + // Queues the auto-hide check that runs kHideSettleMs later; cancelled by any re-activation or + // re-open. A check that fires after the dial was hidden on purpose is a no-op. + void schedule_hide(); + void on_hide_timer(wxTimerEvent& event); + // Whether the dial is the window that currently holds the keyboard focus. On wxGTK IsActive() answers + // from wx's own bookkeeping (g_activeFrame), which the deactivation that armed the timer has already + // cleared, so ask the window itself instead. + bool is_active(); void resize_to_content(int height); void run_action(const std::string& id, const std::string& title, const std::string& param = ""); void open_wiki(const std::string& id); @@ -56,6 +70,8 @@ private: // Guards the CallAfter in on_script_message across dialog destruction, same as // PluginsDialog::m_alive (PluginsDialog.hpp:249). std::shared_ptr> m_alive = std::make_shared>(true); + // Pending auto-hide, armed by a deactivation and validated when it fires (see schedule_hide). + wxTimer m_hide_timer; }; }} diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 044ad0ea99..f0337066c5 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -50,6 +50,7 @@ add_executable(${_TEST_NAME}_tests test_plugin_audit.cpp test_plugin_json_depth.cpp test_shortcuts.cpp + test_speed_dial_dismiss.cpp test_speed_dial_position.cpp test_texture_color_palette.cpp test_texture_island_view.cpp diff --git a/tests/slic3rutils/test_speed_dial_dismiss.cpp b/tests/slic3rutils/test_speed_dial_dismiss.cpp new file mode 100644 index 0000000000..561e203b45 --- /dev/null +++ b/tests/slic3rutils/test_speed_dial_dismiss.cpp @@ -0,0 +1,37 @@ +#include + +#include "slic3r/GUI/SpeedDialDialog.hpp" + +using namespace Slic3r::GUI; + +// The dial hides only after a settle delay, and only if it is still shown and really lost the focus, +// so a focus bounce shorter than the delay does not dismiss it. + +TEST_CASE("Speed dial stays shown while it still holds the focus", "[SpeedDialDismiss][SpeedDial]") +{ + // A focus bounce: a deactivation arrived, but the dial is active again when the timer fires. + REQUIRE_FALSE(speed_dial_should_hide(true, true)); +} + +TEST_CASE("Speed dial hides once the focus has really left it", "[SpeedDialDismiss][SpeedDial]") +{ + // The user clicked into the application behind the dial, or switched to another application. + REQUIRE(speed_dial_should_hide(true, false)); +} + +TEST_CASE("Hidden speed dial never hides again", "[SpeedDialDismiss][SpeedDial]") +{ + // Already hidden: a second hide would restart the delay and re-trigger any dismissal side effects. + REQUIRE_FALSE(speed_dial_should_hide(false, true)); + REQUIRE_FALSE(speed_dial_should_hide(false, false)); +} + +TEST_CASE("Speed dial dismiss decision follows the shown and active truth table", "[SpeedDialDismiss][SpeedDial]") +{ + // The rule in full, so a refactor cannot go back to hiding on the raw deactivation event. + // shown && !active is the only combination that hides. + REQUIRE_FALSE(speed_dial_should_hide(true, true)); + REQUIRE(speed_dial_should_hide(true, false)); + REQUIRE_FALSE(speed_dial_should_hide(false, true)); + REQUIRE_FALSE(speed_dial_should_hide(false, false)); +} From 61e1841f9d529967f6b233cb2c86c48046a03422 Mon Sep 17 00:00:00 2001 From: Lam Wei Lun Date: Thu, 5 Nov 2026 13:32:32 +0800 Subject: [PATCH 22/24] fix: let the 3D navigator keep the mouse for the whole drag (#17284) The navigator is drawn into ImGuizmo's NoInputs "gizmo" window, so ImGui never owns the press (mouse_avail_to_imgui is false) and WantCaptureMouse only reflects what the previous frame requested. ViewManipulate asked for capture only on frames with a non-zero MouseDelta, so the still frame that follows the press dropped it. The next motion event then reached the canvas, which latched it as a camera drag. With an object behind the navigator that drag is refused at GLCanvas3D::on_mouse (the m_hover_volume_idxs gate of the rotate branch), so nothing marked the scene dirty, no frame rendered, and the navigator never rotated. The armed isClicking survived to the release frame and snapped the view to the pressed panel instead. Request capture for as long as the press is held, so the navigator owns the whole gesture. Fixes #17282 --- deps_src/imguizmo/ImGuizmo.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/deps_src/imguizmo/ImGuizmo.cpp b/deps_src/imguizmo/ImGuizmo.cpp index 64f30ff73a..ca3b687d89 100644 --- a/deps_src/imguizmo/ImGuizmo.cpp +++ b/deps_src/imguizmo/ImGuizmo.cpp @@ -3073,6 +3073,19 @@ namespace IMGUIZMO_NAMESPACE } isInside = gContext.mbMouseOver && ImRect(position, position + size).Contains(io.MousePos); + // The navigator is drawn into the NoInputs "gizmo" window, so ImGui never owns the press + // (mouse_avail_to_imgui is false) and WantCaptureMouse only reflects what the previous frame asked + // for. Hold the capture for the whole gesture, otherwise a still frame drops it and the next motion + // event reaches the canvas, which adopts it as a camera drag. + if ((isClicking || isDraging) && io.MouseDown[0]) + { +#if IMGUI_VERSION_NUM >= 18723 + ImGui::SetNextFrameWantCaptureMouse(true); +#else + ImGui::CaptureMouseFromApp(); +#endif + } + if (io.MouseDown[0] && (fabsf(io.MouseDelta[0]) || fabsf(io.MouseDelta[1])) && isClicking) { isClicking = false; From 70c12f5cba7135e4d0b208be0fe9a3837d6170b5 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:45:43 +0800 Subject: [PATCH 23/24] Warn When an Object Overrides Settings Spiral Vase Mode Needs (#17240) Enabling spiral vase mode in the GUI resets sparse infill, wall loops and top shell layers in the global config only. An object, part or height range that overrides them keeps its own values, and its layers with infill or more than one wall are printed without spiralizing, with no hint as to why. Print::validate now warns once per such object, naming it and the first conflicting setting so the notification jumps to it. --- src/libslic3r/Print.cpp | 17 ++++++++++ tests/fff_print/test_spiral_vase.cpp | 48 ++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index d1810f2645..de5a132dbc 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -2412,6 +2412,23 @@ StringObjectException Print::validate(std::vector *warnin return filament_id < is_mixed.size() && is_mixed[filament_id]; })) return {L("Spiral (vase) mode does not work when an object contains more than one material."), nullptr, "spiral_mode"}; + // Enabling spiral vase mode in the GUI resets these keys in the global config only, so an object, + // part or height range can still override them. Layers with infill or more than one wall are + // printed without spiralizing. + for (const PrintRegion ®ion : object->all_regions()) { + const PrintRegionConfig &cfg = region.config(); + const char *opt_key = cfg.sparse_infill_density.value > 0. ? "sparse_infill_density" : + cfg.wall_loops.value > 1 ? "wall_loops" : + cfg.top_shell_layers.value > 0 ? "top_shell_layers" : nullptr; + if (opt_key != nullptr) { + // TRN %1% is the object name. + warn(Slic3r::format(_u8L("Spiral vase mode needs no sparse infill, one wall loop and no top shell layers, " + "but the object %1% uses other values, so it will not print as a continuous spiral."), + object->model_object()->name), + opt_key, object); + break; + } + } } } diff --git a/tests/fff_print/test_spiral_vase.cpp b/tests/fff_print/test_spiral_vase.cpp index cbc8cf8a71..7db4a4d6d2 100644 --- a/tests/fff_print/test_spiral_vase.cpp +++ b/tests/fff_print/test_spiral_vase.cpp @@ -4,15 +4,25 @@ #include #include +#include #include +#include #include +#include "libslic3r/Config.hpp" #include "libslic3r/GCode/SpiralVase.hpp" #include "libslic3r/GCodeReader.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Print.hpp" +#include "libslic3r/PrintBase.hpp" #include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" #include "libslic3r/libslic3r.h" +#include "test_helpers.hpp" + using namespace Slic3r; +using namespace Slic3r::Test; namespace { @@ -63,3 +73,41 @@ TEST_CASE("Spiral vase keeps the selected coordinate and extrusion precision", " REQUIRE(last.size() == 4); CHECK_THAT(last[2].precise_value(E), Catch::Matchers::WithinAbs(high_precision ? 0.000927 : 0.00093, 1e-9)); } + +TEST_CASE("Spiral vase mode warns about an object that overrides infill, walls or top shells", "[SpiralVase]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "spiral_mode", 1 }, + { "sparse_infill_density", "0%" }, + { "wall_loops", 1 }, + { "top_shell_layers", 0 }, + { "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset + }); + const auto [opt_key, value] = GENERATE(table({ + { "", "" }, // no override: the vase-ready global config applies + { "sparse_infill_density", "13%" }, + { "wall_loops", "2" }, + { "top_shell_layers", "3" }, + })); + CAPTURE(opt_key); + std::vector> overrides(1); + if (!opt_key.empty()) + overrides.front().emplace_back(opt_key, value); + + Print print; + Model model; + init_print({cube(20)}, print, model, config, &overrides); + + std::vector warnings; + REQUIRE(print.validate(&warnings).string.empty()); + const PrintObject *object = print.objects().front(); + const auto warning = std::find_if(warnings.begin(), warnings.end(), + [object](const StringObjectException &w) { return w.object == object; }); + if (opt_key.empty()) { + CHECK(warning == warnings.end()); + } else { + REQUIRE(warning != warnings.end()); + CHECK(warning->opt_key == opt_key); + } +} From b2978d1c73abba8ff5a880ff57c563658e8a2648 Mon Sep 17 00:00:00 2001 From: yw4z Date: Thu, 5 Nov 2026 09:19:17 +0300 Subject: [PATCH 24/24] Fix: Prevent deselecting object and closing widget while clicking to toolbar background / divider (#15548) * init * simplify code * simplify comments * update * update --- src/slic3r/GUI/GLCanvas3D.cpp | 72 ++++++++++++++++++++--- src/slic3r/GUI/GLCanvas3D.hpp | 6 ++ src/slic3r/GUI/Gizmos/GLGizmosManager.hpp | 2 + 3 files changed, 73 insertions(+), 7 deletions(-) diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 11856cf33f..13584f5c51 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -62,6 +62,7 @@ #include #include #include +#include #include #include "slic3r/GUI/Selection.hpp" #include "GLCanvas3D.hpp" @@ -3981,6 +3982,7 @@ void GLCanvas3D::bind_event_handlers() down = false; } m_navigator_dragging = false; + m_mouse.down_on_toolbar = false; render(); }); m_event_handlers_bound = true; @@ -4781,6 +4783,12 @@ void GLCanvas3D::on_gesture(wxGestureEvent &evt) m_dirty = true; } +// ORCA true when the pressed button is the only one held, so no other drag is in progress +static bool is_only_one_button_down(const wxMouseEvent& evt) +{ + return int(evt.LeftIsDown()) + int(evt.MiddleIsDown()) + int(evt.RightIsDown()) + int(evt.Aux1IsDown()) + int(evt.Aux2IsDown()) == 1; +} + void GLCanvas3D::on_mouse(wxMouseEvent& evt) { if (!m_initialized || !_set_current()) @@ -4953,6 +4961,26 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) m_dirty = true; }; + // ORCA a press on toolbar empty areas must not reach the 3D scene (selection, camera, painting...). + // Swallow it with the drags and the release that follow, wherever the mouse goes. + if (m_mouse.down_on_toolbar) { + const bool button_event = evt.ButtonDown() || evt.ButtonUp() || evt.ButtonDClick(); + // all buttons released, also covers a release that never reached this handler. Clears down_on_toolbar + if (!evt.ButtonIsDown(wxMOUSE_BTN_ANY) && !evt.ButtonDown() && !evt.ButtonDClick()) + mouse_up_cleanup(); + if (button_event || evt.Dragging()) + return; + } + else if (!mouse_in_layer_editing && (evt.ButtonDown() || evt.ButtonDClick()) && is_only_one_button_down(evt) && + !m_gizmos.is_mouse_over_toolbar_icon(pos.cast()) && _is_mouse_over_top_toolbar(pos.cast())) { + m_mouse.down_on_toolbar = true; + m_mouse.set_start_position_2D_as_invalid(); + m_mouse.set_start_position_3D_as_invalid(); + if (!has_mouse_capture()) // keep getting the release when it happens outside the canvas + m_canvas->CaptureMouse(); + return; + } + if (!mouse_in_layer_editing && m_gizmos.on_mouse(evt)) { if (m_gizmos.is_running()) { _deactivate_arrange_menu(); @@ -6341,6 +6369,7 @@ void GLCanvas3D::mouse_up_cleanup() m_mouse.dragging = false; m_mouse.ignore_left_up = false; m_mouse.ignore_right_up = false; + m_mouse.down_on_toolbar = false; m_dirty = true; if (m_canvas->HasCapture()) @@ -8689,9 +8718,8 @@ void GLCanvas3D::_render_fps_overlay(int fps) const if (const ImGuiWindow* legend = ImGui::FindWindowByName("Legend"); m_canvas_type == ECanvasType::CanvasPreview && legend != nullptr && legend->Active) pos = ImVec2(legend->Pos.x - margin, legend->Pos.y); // The toolbar row can reach the corner on a narrow canvas; stack the overlay below it then. - else if (m_main_toolbar.is_enabled() && - get_main_toolbar_offset() + m_main_toolbar.get_width() + m_separator_toolbar.get_width() + m_gizmos.get_scaled_total_width() + m_assemble_view_toolbar.get_width() > left) - pos.y = std::max(m_main_toolbar.get_height(), m_gizmos.get_scaled_total_height()) + margin; + else if (m_main_toolbar.is_enabled() && get_main_toolbar_offset() + get_top_toolbar_width() > left) + pos.y = get_top_toolbar_height() + margin; ImGui::SetNextWindowPos(pos, ImGuiCond_Always, ImVec2(1.0f, 0.0f)); ImGui::SetNextWindowBgAlpha(0.35f); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 8.0f * get_scale()); @@ -10418,14 +10446,21 @@ void GLCanvas3D::_render_gizmos_overlay() } } +float GLCanvas3D::get_top_toolbar_width() const +{ + return m_main_toolbar.get_width() + m_separator_toolbar.get_width() + m_gizmos.get_scaled_total_width() + m_assemble_view_toolbar.get_width(); +} + +float GLCanvas3D::get_top_toolbar_height() const +{ + return std::max({ m_main_toolbar.get_height(), m_gizmos.get_scaled_total_height(), m_assemble_view_toolbar.get_height() }); +} + int GLCanvas3D::get_main_toolbar_offset() const { const float cnv_width = get_canvas_size().get_width(); const float collapse_toolbar_width = get_collapse_toolbar_width() * 2; - const float gizmo_width = m_gizmos.get_scaled_total_width(); - const float assemble_width = m_assemble_view_toolbar.get_width(); - const float separator_width = m_separator_toolbar.get_width(); - const float toolbar_total_width = m_main_toolbar.get_width() + separator_width + gizmo_width + assemble_width + collapse_toolbar_width; + const float toolbar_total_width = get_top_toolbar_width() + collapse_toolbar_width; if (cnv_width < toolbar_total_width) { return is_collapse_toolbar_on_left() ? collapse_toolbar_width : 0; @@ -11464,6 +11499,29 @@ void GLCanvas3D::_render_separator_toolbar_left() const m_separator_toolbar.render(*this,GLToolbarItem::SeparatorLine); } +// ORCA is mouse over the top toolbar area +bool GLCanvas3D::_is_mouse_over_top_toolbar(const Vec2d& mouse_pos) const +{ + float left, width, height; + if (m_canvas_type == ECanvasType::CanvasAssembleView) { + if (!m_gizmos.is_enabled() || m_gizmos.get_selectable_icons_cnt() == 0) + return false; + // same as GLGizmosManager::do_render_overlay() + left = 0.5f * (float)get_canvas_size().get_width() + 0.5f * m_paint_toolbar_width; + width = m_gizmos.get_scaled_total_width(); + height = m_gizmos.get_scaled_total_height(); + } else { + if (!m_main_toolbar.is_enabled()) + return false; + left = (float)get_main_toolbar_offset(); + width = get_top_toolbar_width(); + height = get_top_toolbar_height(); + } + + return left <= (float)mouse_pos.x() && (float)mouse_pos.x() <= left + width && + 0.f <= (float)mouse_pos.y() && (float)mouse_pos.y() <= height; +} + void GLCanvas3D::_render_collapse_toolbar() const { if (!m_collapse_toolbar_enabled) diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index d041c31ae7..218c4c0795 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -380,6 +380,8 @@ class GLCanvas3D bool ignore_left_up{ false }; Drag drag; bool ignore_right_up; + // ORCA a button was pressed on toolbar empty areas, swallow events until it is released + bool down_on_toolbar{ false }; // Orca: The screen-space start and world-space anchor describe the same pan session. // Invalidating one must invalidate the other so a new drag cannot reuse stale depth. @@ -1142,6 +1144,9 @@ public: void select_plate(); //BBS: GUI refactor: GLToolbar&&gizmo int get_main_toolbar_offset() const; + // ORCA the top toolbar row: main toolbar, separator, gizmo bar and assemble view toolbar (not the collapse toolbar) + float get_top_toolbar_width() const; + float get_top_toolbar_height() const; int get_main_toolbar_height() const { return m_main_toolbar.get_height(); } int get_main_toolbar_width() const { return m_main_toolbar.get_width(); } float get_assemble_view_toolbar_width() const { return m_assemble_view_toolbar.get_width(); } @@ -1599,6 +1604,7 @@ private: void _render_section_view_panel(const ImVec2& bottom_left); void _render_separator_toolbar_right() const; void _render_separator_toolbar_left() const; + bool _is_mouse_over_top_toolbar(const Vec2d& mouse_pos) const; void _render_collapse_toolbar() const; // BBS //void _render_view_toolbar() const; diff --git a/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp b/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp index d08b50f61d..24a4278528 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp @@ -275,6 +275,8 @@ public: } bool is_enabled() const { return m_enabled; } + // ORCA + bool is_mouse_over_toolbar_icon(const Vec2d& mouse_pos) const { return get_gizmo_from_mouse(mouse_pos) != Undefined; } void set_enabled(bool enable) { m_enabled = enable; } void set_icon_dirty() { m_icons_texture_dirty = true; }