From 4f71398a0fc9719aeda72cc6a32997f304ca9da9 Mon Sep 17 00:00:00 2001 From: Kim Gunwoo <149047537+rlarjsdn-kgw@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:47:30 +0900 Subject: [PATCH 01/36] Fix korean translations for left and right extruder (#17612) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix korean translations for left and right extruder Updated translations for 'left extruder' and 'right extruder' to use '압출기' instead of '익스트루더'. I showed 'extruder' and 'Extruder' has different translation in Korean. So i firstly fixed it * Update Korean translations for extruder terms Thanks for the review and for pointing out the remaining inconsistencies! I've updated the eight additional strings in the same PR to use "압출기" consistently with the Korean localization. --- localization/i18n/ko/OrcaSlicer_ko.po | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/localization/i18n/ko/OrcaSlicer_ko.po b/localization/i18n/ko/OrcaSlicer_ko.po index 432de782a8..680c041950 100644 --- a/localization/i18n/ko/OrcaSlicer_ko.po +++ b/localization/i18n/ko/OrcaSlicer_ko.po @@ -49,7 +49,7 @@ msgid "Left extruder" msgstr "왼쪽 압출기" msgid "left extruder" -msgstr "왼쪽 익스트루더" +msgstr "왼쪽 압출기" msgid "Right Extruder" msgstr "오른쪽 압출기" @@ -58,7 +58,7 @@ msgid "Right extruder" msgstr "오른쪽 압출기" msgid "right extruder" -msgstr "오른쪽 익스트루더" +msgstr "오른쪽 압출기" # AI Translated msgid "Main Nozzle" @@ -180,7 +180,7 @@ msgid "Right" msgstr "오른쪽" msgid "extruder" -msgstr "익스트루더" +msgstr "압출기" msgid "TPU is not supported by AMS." msgstr "TPU는 AMS에서 지원되지 않습니다." @@ -219,7 +219,7 @@ msgid "Damp PVA will become flexible and get stuck inside AMS, please take care msgstr "습한 PVA는 유연해져서 AMS 내부에 달라붙게 됩니다. 사용하기 전에 건조시키십시오." msgid "Damp PVA is flexible and may get stuck in extruder. Dry it before use." -msgstr "습한 PVA는 유연하여 익스트루더에 끼일 수 있습니다. 사용 전에 건조시키세요." +msgstr "습한 PVA는 유연하여 압출기에 끼일 수 있습니다. 사용 전에 건조시키세요." msgid "The rough surface of PLA Glow can accelerate wear on the AMS system, particularly on the internal components of the AMS Lite." msgstr "PLA Glow의 거친 표면은 AMS 시스템, 특히 AMS Lite의 내부 부품의 마모를 가속화할 수 있습니다." @@ -263,7 +263,7 @@ msgstr "%s은(는) Filament Track Switch로 인해 로드 또는 언로드에 #, c-format, boost-format msgid "%s is not supported by %s extruder." -msgstr "%s은(는) %s 익스트루더에서 지원되지 않습니다." +msgstr "%s은(는) %s 압출기에서 지원되지 않습니다." # AI Translated #, c-format, boost-format @@ -6209,10 +6209,10 @@ msgid "AMS temperature is too high, which may cause the filament to soften. Plea msgstr "AMS 온도가 너무 높아 필라멘트가 연화될 수 있습니다. AMS 온도가 %d℃ 이하로 떨어질 때까지 기다리세요." msgid "The current chamber temperature or the target chamber temperature exceeds 45℃. In order to avoid extruder clogging, low temperature filament(PLA/PETG/TPU) is not allowed to be loaded." -msgstr "현재 챔버 온도 또는 목표 챔버 온도가 45℃를 초과합니다. 익스트루더 막힘을 방지하기 위해 저온 필라멘트(PLA/PETG/TPU) 로딩이 허용되지 않습니다." +msgstr "현재 챔버 온도 또는 목표 챔버 온도가 45℃를 초과합니다. 압출기 막힘을 방지하기 위해 저온 필라멘트(PLA/PETG/TPU) 로딩이 허용되지 않습니다." msgid "Low temperature filament(PLA/PETG/TPU) is loaded in the extruder. In order to avoid extruder clogging, it is not allowed to set the chamber temperature." -msgstr "저온 필라멘트(PLA/PETG/TPU)가 익스트루더에 로드되어 있습니다. 익스트루더 막힘을 방지하기 위해 챔버 온도 설정이 허용되지 않습니다." +msgstr "저온 필라멘트(PLA/PETG/TPU)가 압출기에 로드되어 있습니다. 압출기 막힘을 방지하기 위해 챔버 온도 설정이 허용되지 않습니다." msgid "When you set the chamber temperature below 40℃, the chamber temperature control will not be activated, and the target chamber temperature will automatically be set to 0℃." msgstr "챔버 온도를 40℃ 이하로 설정하면 챔버 온도 제어가 활성화되지 않습니다. 그리고 목표 챔버 온도는 자동으로 0℃ 로 설정됩니다." @@ -8466,7 +8466,7 @@ msgid "When printing is paused, filament loading and unloading are only supporte msgstr "인쇄가 일시 중지되면 필라멘트 로딩 및 언로딩은 외부 슬롯에서만 지원됩니다." msgid "Current extruder is busy changing filament." -msgstr "현재 익스트루더가 필라멘트 교체 중입니다." +msgstr "현재 압출기가 필라멘트 교체 중입니다." # AI Translated msgid "\"Load\" or \"Unload\" is not supported for external spool while using Filament Track Switch." @@ -13850,7 +13850,7 @@ msgid "Single extruder multi-material setup" msgstr "단일 압출기 다중 재료 설정" msgid "Number of extruders of the printer." -msgstr "프린터 익스트루더 수." +msgstr "프린터 압출기 수." msgid "" "Single Extruder Multi Material is selected, and all extruders must have the same diameter.\n" @@ -14420,7 +14420,7 @@ msgstr "" "수정한 사전 설정 값을 삭제하거나 수정된 ​​값을 새 프로젝트로 전송하도록 선택할 수 있습니다" msgid "Extruder count" -msgstr "익스트루더 수" +msgstr "압출기 수" # AI Translated msgid "Capabilities" From 882175b2ae7bae7192b06e480e71c46e47493842 Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Thu, 19 Nov 2026 08:21:53 -0300 Subject: [PATCH 02/36] Start the max flowrate test's spiral at full flow (#17699) --- src/slic3r/GUI/Plater.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index cece79df58..f41e867a3a 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -18145,6 +18145,7 @@ void Plater::calib_max_vol_speed(const Calib_Params& params) obj_cfg.set_key_value("precise_z_height", new ConfigOptionBool(false)); print_config->set_key_value("timelapse_type", new ConfigOptionEnum(tlTraditional)); print_config->set_key_value("spiral_mode", new ConfigOptionBool(true)); + print_config->set_key_value("spiral_starting_flow_ratio", new ConfigOptionFloat(1)); print_config->set_key_value("max_volumetric_extrusion_rate_slope", new ConfigOptionFloat(0)); print_config->set_key_value("enable_wrapping_detection", new ConfigOptionBool(false)); From fe0094a5a35ff4f52ed9b8a7892707905f98004b Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Wed, 18 Nov 2026 23:38:53 -0300 Subject: [PATCH 03/36] Open the preview on the view each calibration tests After slicing a calibration, the preview shows the value it varies: Pressure Advance for the PA line, pattern and tower, Temperature for the temperature tower, Flow for the max flowrate and flow rate tests, Speed for VFA and Jerk for the cornering test. Retraction and input shaping have no matching view and keep the normal default. It goes through apply_default_view_type, so it takes precedence over the default view type preference and a view picked by hand survives a reslice. The flow rate test sets no calibration mode on the print, because that would change its G-code, so the Plater remembers it until other files are loaded. --- src/slic3r/GUI/GCodeViewer.cpp | 29 ++++++++++++++++++++++++++--- src/slic3r/GUI/GCodeViewer.hpp | 4 ++-- src/slic3r/GUI/Plater.cpp | 6 ++++++ src/slic3r/GUI/Plater.hpp | 2 ++ 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index 0330bcb47e..15cb3230a8 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -3,6 +3,7 @@ #include "libslic3r/BuildVolume.hpp" #include "libslic3r/Print.hpp" +#include "libslic3r/calib.hpp" #include "libslic3r/Geometry.hpp" #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/Model.hpp" @@ -206,6 +207,22 @@ static const std::vector>& view_typ return map; } +// ORCA: the view type showing the value a calibration varies, when the preview has one. +static std::optional calibration_view_type(CalibMode mode) +{ + switch (mode) { + case CalibMode::Calib_PA_Line: + case CalibMode::Calib_PA_Pattern: + case CalibMode::Calib_PA_Tower: return libvgcode::EViewType::PressureAdvance; + case CalibMode::Calib_Temp_Tower: return libvgcode::EViewType::Temperature; + case CalibMode::Calib_Flow_Rate: + case CalibMode::Calib_Vol_speed_Tower: return libvgcode::EViewType::VolumetricFlowRate; + case CalibMode::Calib_VFA_Tower: return libvgcode::EViewType::Speed; + case CalibMode::Calib_Cornering: return libvgcode::EViewType::Jerk; + default: return std::nullopt; + } +} + // Find an index of a value in a sorted vector, which is in . // Returns -1 if there is no such member. static int find_close_layer_idx(const std::vector &zs, double &z, double eps) @@ -1286,14 +1303,19 @@ void GCodeViewer::select_view_type(libvgcode::EViewType type) // ORCA: Pick the view type the preview opens with, following the "preview_default_view_type" preference: // a fixed view type, the one the user picked last ("last"), or the automatic choice ("auto", the default) // which shows Filament for multi material prints and Line Type for single material ones. +// A calibration's view, when given, takes precedence over the preference. // The default is only (re)applied when it actually changes, so a view type picked by hand survives a reslice. -void GCodeViewer::apply_default_view_type() +void GCodeViewer::apply_default_view_type(std::optional calibration_view) { const std::string preference = wxGetApp().app_config->get("preview_default_view_type"); std::string key = preference; libvgcode::EViewType type = libvgcode::EViewType::FeatureType; - if (preference == "last") { + if (calibration_view) { + type = *calibration_view; + key = "calibration_" + view_type_to_config_name(type); + } + else if (preference == "last") { if (!view_type_from_config_name(wxGetApp().app_config->get("preview_last_view_type"), type)) type = libvgcode::EViewType::FeatureType; } @@ -1765,7 +1787,8 @@ void GCodeViewer::load_as_gcode(const GCodeProcessorResult& gcode_result, const // load_toolpaths(gcode_result, build_volume, exclude_bounding_box); // ORCA: Apply the default view type now that we know how many tools the G-code actually uses. - apply_default_view_type(); + const bool flowrate_calib = print.calib_mode() == CalibMode::Calib_None && wxGetApp().plater()->is_flowrate_calib(); + apply_default_view_type(calibration_view_type(flowrate_calib ? CalibMode::Calib_Flow_Rate : print.calib_mode())); // BBS: data for rendering color arrangement recommendation m_nozzle_nums = print.config().option("nozzle_diameter")->values.size(); diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index 6755fae341..1ecdb72e97 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -533,8 +533,8 @@ public: } // ORCA: select a view type in the preview combo box and apply it void select_view_type(libvgcode::EViewType type); - // ORCA: apply the "preview_default_view_type" preference, see the definition for the supported values - void apply_default_view_type(); + // ORCA: apply the "preview_default_view_type" preference, or the view of the calibration being previewed + void apply_default_view_type(std::optional calibration_view = std::nullopt); // ORCA: stable, locale independent name of a view type, as stored in the application config static std::string view_type_to_config_name(libvgcode::EViewType type); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index f41e867a3a..bc8334f7c4 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -7298,6 +7298,8 @@ struct Plater::priv int m_cur_slice_plate; //BBS: m_slice_all in .gcode.3mf file case, set true when slice all bool m_slice_all_only_has_gcode{ false }; + // Orca: the flow rate test sets no calibration mode on the print, as that would change its G-code + bool m_flowrate_calib{ false }; bool m_need_update{false}; //BBS: add popup object table logic @@ -9287,6 +9289,7 @@ std::vector Plater::priv::load_files(const std::vector& input_ q->m_3mf_path = input_files.front().string(); // Leave the previous calibration mode intact when preparation was cancelled. background_process.fff_print()->calib_mode() = CalibMode::Calib_None; + m_flowrate_calib = false; for (size_t i = 0; i < input_files.size(); ++i) { int project_filament_count = 1; @@ -17780,8 +17783,11 @@ void Plater::calib_flowrate(bool is_linear, int pass, InfillPattern pattern, int // Refresh object after scaling const std::vector object_idx(boost::counting_iterator(0), boost::counting_iterator(model().objects.size())); changed_objects(object_idx); + p->m_flowrate_calib = true; } +bool Plater::is_flowrate_calib() const { return p->m_flowrate_calib; } + // The belt provini tower (Calib_Params::test_model 1) is one embossed model per // temperature range. diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index 0eb65ad872..c5d5ddcc05 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -414,6 +414,8 @@ public: void calib_pa(const Calib_Params& params); //ORCA: Add pattern parameter to calib_flowrate void calib_flowrate(bool is_linear, int pass, InfillPattern pattern = ipArchimedeanChords, int filament_id = 0, int extruder_id = 0); + // True from calib_flowrate() until other files are loaded, like the print's calibration mode + bool is_flowrate_calib() const; void calib_temp(const Calib_Params& params); void calib_max_vol_speed(const Calib_Params& params); void calib_retraction(const Calib_Params& params); From 571386db5799c975215cfc2401c1c5470f97c2cb Mon Sep 17 00:00:00 2001 From: Arthur Porto <227830219+Art-Porto@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:33:10 -0300 Subject: [PATCH 04/36] Load the Device tab page only once the tab is opened (#17580) Load the Device tab page only once the tab is on screen The idle prebuild of the main window panels builds the Device tab's web view while the tab is hidden and loads the print host page into it at once, because a new panel counts as shown. The page, and the camera stream it opens, then run from startup until the app closes, whether the tab is ever opened or not. load_url() now defers the page unless the view is on screen, as it did before the prebuild. --- src/slic3r/GUI/PrinterWebView.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/PrinterWebView.cpp b/src/slic3r/GUI/PrinterWebView.cpp index a870c12e23..dc6afc0ce7 100644 --- a/src/slic3r/GUI/PrinterWebView.cpp +++ b/src/slic3r/GUI/PrinterWebView.cpp @@ -239,7 +239,10 @@ void PrinterWebView::load_url(wxString& url, wxString apikey) m_url_loaded = false; m_handler = create_printer_webview_handler(*this); - if (this->IsShown()) { + // Orca: IsShownOnScreen(), not IsShown(): the idle prebuild builds this view inside the hidden + // Device tab, and a new panel counts as shown, so the page and its camera stream would start + // before the tab is opened. Show() loads the deferred page. + if (this->IsShownOnScreen()) { //ORCA: m_url_deferred will be cleared on load success //m_url_deferred.clear(); m_browser->LoadURL(url); From c56506d68bd722ddb43dd6c7181a5cc45a56ac82 Mon Sep 17 00:00:00 2001 From: yw4z Date: Thu, 19 Nov 2026 16:41:43 +0300 Subject: [PATCH 05/36] Fix: Non positive volumes of selected or non selected object visible on Texture displacement gizmo (#17656) The Texture displacement gizmo made every volume visible again on each frame, so modifiers, negative volumes and support blockers/enforcers from other objects and instances showed through. It now restores only the selected instance, and hides the selected object's non-part volumes while the gizmo is open. --- src/slic3r/GUI/GLCanvas3D.cpp | 5 +++++ src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index ffacbd5449..06ff7ee5de 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -2708,6 +2708,11 @@ void GLCanvas3D::toggle_model_objects_visibility(bool visible, const ModelObject vol->force_neutral_color = false; else if (gizmo_type == GLGizmosManager::MmSegmentation) vol->is_active = false; + else if (gizmo_type == GLGizmosManager::TextureDisplacement) { + vol->force_native_color = true; + if (vol->is_modifier) // GLVolume::is_modifier == any non-model-part volume + vol->is_active = false; + } else vol->force_native_color = true; } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp index a81815663d..87a1653efa 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp @@ -732,7 +732,11 @@ void GLGizmoTextureDisplacement::render_painter_gizmo() if (const ModelVolume *part = preview_part(*preview); part != nullptr) previewed.push_back(part); } - m_parent.toggle_model_objects_visibility(true); + m_parent.toggle_model_objects_visibility( + true, + m_c->selection_info()->model_object(), + m_c->selection_info()->get_active_instance() + ); for (const ModelVolume *volume : previewed) m_parent.toggle_model_objects_visibility(false, m_c->selection_info()->model_object(), m_c->selection_info()->get_active_instance(), volume); From c51687243fe2cf3f88ce8f8d561ee6ba04b139aa Mon Sep 17 00:00:00 2001 From: yw4z Date: Thu, 19 Nov 2026 16:52:31 +0300 Subject: [PATCH 06/36] Fix plate skirt start point not saved to 3mf (#17457) Save and load the plate's skirt start angle in the project file. Before this, a skirt start point set in Plate Settings was lost on save. Adds a round-trip check to the plate test in test_3mf.cpp. --- src/libslic3r/Format/bbs_3mf.cpp | 13 +++++++++++++ tests/libslic3r/test_3mf.cpp | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/src/libslic3r/Format/bbs_3mf.cpp b/src/libslic3r/Format/bbs_3mf.cpp index d51543de65..9513a1e807 100644 --- a/src/libslic3r/Format/bbs_3mf.cpp +++ b/src/libslic3r/Format/bbs_3mf.cpp @@ -384,6 +384,7 @@ static constexpr const char* FIRST_LAYER_PRINT_SEQUENCE_ATTR = "first_layer_prin static constexpr const char* OTHER_LAYERS_PRINT_SEQUENCE_ATTR = "other_layers_print_sequence"; static constexpr const char* OTHER_LAYERS_PRINT_SEQUENCE_NUMS_ATTR = "other_layers_print_sequence_nums"; static constexpr const char* SPIRAL_VASE_MODE = "spiral_mode"; +static constexpr const char* SKIRT_START_ANGLE_ATTR = "skirt_start_angle"; static constexpr const char* IMEX_PARALLEL_MODE_ATTR = "imex_parallel_mode"; // The same attribute before the feature was renamed IMEX. Plate metadata is matched by exact // string and written with set_key_value, so it never passes through handle_legacy: without this @@ -4683,6 +4684,13 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) std::istringstream(value) >> std::boolalpha >> spiral_mode; m_curr_plater->config.set_key_value("spiral_mode", new ConfigOptionBool(spiral_mode)); } + else if (key == SKIRT_START_ANGLE_ATTR) { + // plate override of the skirt start point, ignored when it is not a valid angle + size_t parsed = 0; + const double skirt_start_angle = string_to_double_decimal_point(value, &parsed); + if (parsed > 0 && skirt_start_angle >= -180. && skirt_start_angle <= 180.) + m_curr_plater->config.set_key_value("skirt_start_angle", new ConfigOptionFloat(skirt_start_angle)); + } else if (key == IMEX_PARALLEL_MODE_ATTR || key == IXEX_PARALLEL_MODE_ATTR_LEGACY) { m_curr_plater->config.set_key_value("imex_parallel_mode", new ConfigOptionString(value)); } @@ -8558,6 +8566,11 @@ bool _BBS_3MF_Exporter::_add_model_config_file_to_archive(mz_zip_archive& archiv if (spiral_mode_opt) stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << SPIRAL_VASE_MODE << "\" " << VALUE_ATTR << "=\"" << spiral_mode_opt->getBool() << "\"/>\n"; + // plate override of the skirt start point, written with a decimal point in every locale + auto* skirt_start_angle_opt = plate_data->config.option("skirt_start_angle"); + if (skirt_start_angle_opt) + stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << SKIRT_START_ANGLE_ATTR << "\" " << VALUE_ATTR << "=\"" << float_to_string_decimal_point(skirt_start_angle_opt->value) << "\"/>\n"; + { // Mode names are user supplied free text, so the value has to be escaped for an // attribute. xml_escape_double_quotes_attribute_value() is used rather than diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index 06b9e8193c..8817534951 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -1553,6 +1553,7 @@ SCENARIO("BBS 3MF round-trips per-plate IMEX state (parallel mode + head filamen plate0->plate_index = 0; plate0->config.set_key_value("imex_parallel_mode", new ConfigOptionString(hostile_mode)); plate0->config.set_key_value("imex_head_filament_map", new ConfigOptionString(hostile_hfm)); + plate0->config.set_key_value("skirt_start_angle", new ConfigOptionFloat(12.5)); src_plates.push_back(plate0); WHEN("the model is saved to BBS 3MF and loaded back") { @@ -1595,6 +1596,12 @@ SCENARIO("BBS 3MF round-trips per-plate IMEX state (parallel mode + head filamen REQUIRE(hfm_opt != nullptr); REQUIRE(hfm_opt->value == hostile_hfm); } + THEN("skirt_start_angle round-trips with its fraction") { + REQUIRE(dst_plates.size() >= 1); + auto *angle_opt = dst_plates[0]->config.option("skirt_start_angle"); + REQUIRE(angle_opt != nullptr); + REQUIRE_THAT(angle_opt->value, Catch::Matchers::WithinAbs(12.5, 1e-6)); + } release_PlateData_list(dst_plates); } From 14f52a4a273b42da2627327092f60924489ba82b Mon Sep 17 00:00:00 2001 From: Arthur Porto <227830219+Art-Porto@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:56:22 -0300 Subject: [PATCH 07/36] Show the prime volume of each filament where the Type 1 prime tower takes it (#17424) The Type 1 prime tower purges the prime volume of each filament, and no tab showed it, so on Bambu Lab printers the process Prime volume looked like the setting but changed nothing. The filament's Multimaterial page now has a Prime volume group with Filament change, and Hotend change on a printer whose extruder holds more than one nozzle, such as the H2C. On a Type 1 tower the process Prime volume is greyed out. Slicing is unchanged. Fixes #16350 --- src/slic3r/GUI/ConfigManipulation.cpp | 2 ++ src/slic3r/GUI/Tab.cpp | 17 ++++++++++++ tests/fff_print/test_wipe_tower.cpp | 40 +++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/src/slic3r/GUI/ConfigManipulation.cpp b/src/slic3r/GUI/ConfigManipulation.cpp index 5ec0d31f7b..4d69214862 100644 --- a/src/slic3r/GUI/ConfigManipulation.cpp +++ b/src/slic3r/GUI/ConfigManipulation.cpp @@ -1238,6 +1238,8 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in toggle_line("toolchange_cyclic_first_layer", use_cyclic_ordering, -1, cyclic_order_reason); toggle_line("prime_volume",have_prime_tower && (!purge_in_primetower || !bSEMM), -1, _L("Enable the prime tower and either disable purging in the prime tower or disable single extruder multimaterial mode.")); + // Orca: the Type 1 tower takes the prime volume of each filament instead. + toggle_field("prime_volume", supports_wipe_tower_2, -1, _L("The Type 1 prime tower takes the prime volume from each filament, on its Multimaterial page.")); for (auto el : {"flush_into_infill", "flush_into_support", "flush_into_objects"}) toggle_field(el, have_prime_tower, -1, _L("Enable the prime tower to use this setting.")); diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 6453bf61a8..61b79c686d 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -5098,6 +5098,11 @@ void TabFilament::build() optgroup->append_single_option_line("filament_tower_interface_purge_volume", "material_multimaterial#multimaterial-wipe-tower-parameters"); optgroup->append_single_option_line("filament_tower_interface_print_temp", "material_multimaterial#multimaterial-wipe-tower-parameters"); + // Orca: the Type 1 prime tower takes its prime volume from each filament, not from the process. + optgroup = page->new_optgroup(L("Prime volume"), "param_tower"); + optgroup->append_single_option_line("filament_prime_volume", "material_multimaterial#multimaterial-wipe-tower-parameters"); + optgroup->append_single_option_line("filament_prime_volume_nc", "material_multimaterial#multimaterial-wipe-tower-parameters"); + optgroup = page->new_optgroup(L("Multi Filament")); // optgroup->append_single_option_line("filament_flush_temp", "", 0); // optgroup->append_single_option_line("filament_flush_volumetric_speed", "", 0); @@ -5334,6 +5339,18 @@ void TabFilament::toggle_options() // Orca: hide specific settings for BBL printers const wxString bambu_printer_reason = _L("This setting is unavailable for Bambu Lab printers."); toggle_option("filament_minimal_purge_on_wipe_tower", !is_BBL_printer, 256 + variant_index, bambu_printer_reason); + + // Orca: only the Type 1 prime tower reads these. Bambu Lab printers always use the Type 1 tower. The tower + // takes the hotend change volume only when two filaments share an extruder but not a nozzle, so only on a + // printer whose extruder holds several nozzles, as has_multiple_nozzle tells in TabPrinter::on_preset_loaded(). + const bool type1_tower = is_BBL_printer || printer_cfg.opt_enum("wipe_tower_type") == WipeTowerType::Type1; + const auto *max_nozzle_counts = printer_cfg.option("extruder_max_nozzle_count"); + const bool has_multiple_nozzle = max_nozzle_counts != nullptr && + std::any_of(max_nozzle_counts->values.begin(), max_nozzle_counts->values.end(), + [](int v) { return v > 1 && v != ConfigOptionIntsNullable::nil_value(); }); + toggle_line("filament_prime_volume", type1_tower, -1, _L("Select wipe tower Type 1 in the printer settings to use this setting.")); + toggle_line("filament_prime_volume_nc", type1_tower && has_multiple_nozzle, -1, + _L("Select wipe tower Type 1 on a printer whose extruder holds more than one nozzle to use this setting.")); for (auto el : {"filament_loading_speed_start", "filament_loading_speed", "filament_unloading_speed_start", "filament_unloading_speed", "filament_toolchange_delay", "filament_cooling_moves", "filament_cooling_initial_speed", "filament_cooling_final_speed"}) diff --git a/tests/fff_print/test_wipe_tower.cpp b/tests/fff_print/test_wipe_tower.cpp index ba404b1320..558091b867 100644 --- a/tests/fff_print/test_wipe_tower.cpp +++ b/tests/fff_print/test_wipe_tower.cpp @@ -432,6 +432,46 @@ static DynamicPrintConfig tower_estimate_config(const char *wall_type, unsigned { "raft_layers", "0" } }); } +// The filament a Type 1 tower extrudes for two 20 mm cubes on filaments 1 and 2, so every layer changes +// filament, given the process prime volume and the prime volume of each filament. +static double type1_tower_filament(const char *prime_volume, const char *filament_prime_volume) +{ + DynamicPrintConfig config = tower_estimate_config("rectangle"); + config.set_deserialize_strict({ { "wipe_tower_type", "type1" }, + { "prime_volume", prime_volume }, + { "filament_prime_volume", filament_prime_volume }, + { "wipe_tower_x", "120" }, + { "wipe_tower_y", "120" } }); + const std::vector> overrides = { {}, { { "extruder", "2" } } }; + Print print; + Model model; + init_print({ cube(20), cube(20) }, print, model, config, &overrides); + const std::string gcode = Slic3r::Test::gcode(print); + + // The filament extruded under the prime tower's role tag. + double extruded = 0.; + bool in_tower = false; + GCodeReader parser; + parser.apply_config(print.config()); + parser.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + const std::string_view raw = line.raw(); + if (raw.rfind(";TYPE:", 0) == 0 || raw.rfind("; FEATURE: ", 0) == 0) + in_tower = raw.find("Prime tower") != std::string_view::npos; + else if (in_tower && line.extruding(self)) + extruded += line.dist_E(self); + }); + return extruded; +} + +TEST_CASE("The Type 1 tower purges the prime volume of each filament, not the process one", "[WipeTower]") +{ + const double filament_45 = type1_tower_filament("45", "45,45"); + REQUIRE(filament_45 > 0.); + CHECK_THAT(type1_tower_filament("5", "45,45"), Catch::Matchers::WithinRel(filament_45, 1e-6)); + CHECK_THAT(type1_tower_filament("60", "45,45"), Catch::Matchers::WithinRel(filament_45, 1e-6)); + CHECK(type1_tower_filament("45", "15,15") < filament_45); +} + TEST_CASE("The tower is sized for the thinnest layer any object on the plate is sliced at", "[WipeTower]") { // The tower has to survive its thinnest layer, so an override finer than the preset drives From 1de01873ae15566ce4d407a98209bf442380a2cf Mon Sep 17 00:00:00 2001 From: Lam Wei Lun Date: Thu, 19 Nov 2026 22:01:51 +0800 Subject: [PATCH 08/36] Fix mouse ear brim missing at a rounded corner depending on object orientation (#17163) Mouse ear placement no longer depends on where the outline starts. The old code simplified the outline with Douglas-Peucker, which is anchored on its first vertex, so rotating a part changed which rounded corners got an ear. make_brim_ear_points() now measures the turn at each vertex over a window of arc length on both sides, and doubles the window while the outline keeps turning. Corners with large fillets now get an ear at the default settings. A candidate whose window already reached a placed ear is dropped, so a sharp corner next to a curve gets one ear. The Brim Ears tool's Auto-generate uses the same function. Behavior change: a smooth closed outline such as a disc gets no ears at the default 125 degree max angle. Raising the max angle to 135 or more still gives it ears. Fixes #17119 --- localization/i18n/OrcaSlicer.pot | 5 +- src/libslic3r/Brim.cpp | 186 +++++++- src/libslic3r/Brim.hpp | 8 + src/libslic3r/PrintConfig.cpp | 7 +- src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp | 19 +- src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp | 2 +- tests/fff_print/test_skirt_brim.cpp | 114 +++++ tests/libslic3r/CMakeLists.txt | 2 + tests/libslic3r/test_brim.cpp | 502 ++++++++++++++++++++++ 9 files changed, 807 insertions(+), 38 deletions(-) create mode 100644 tests/libslic3r/test_brim.cpp diff --git a/localization/i18n/OrcaSlicer.pot b/localization/i18n/OrcaSlicer.pot index e8ff50e250..960b645c84 100644 --- a/localization/i18n/OrcaSlicer.pot +++ b/localization/i18n/OrcaSlicer.pot @@ -14890,8 +14890,9 @@ msgid "Brim ear detection radius" msgstr "" msgid "" -"The geometry will be decimated before detecting sharp angles. This parameter indicates the minimum length of the deviation for the decimation.\n" -"0 to deactivate." +"The direction change at a corner is measured over a window of this length along the outline.\n" +"The window grows while the outline keeps curving, so a rounded corner counts as one corner once its whole turn is seen.\n" +"0 to measure the angle at every vertex without smoothing." msgstr "" msgid "Brim ears outer only" diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index 1ab8cecbce..db7946b914 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -346,6 +347,172 @@ double configBrimWidthByVolumeGroups(double adhesion, double maxSpeed, const std return brim_width; } +namespace { + +// ORCA: position at arc length a along the closed contour, interpolated inside one segment. +Vec2d point_at_arc(const Points &pts, const std::vector &cum, double perimeter, double a) +{ + const size_t n = pts.size(); + a = std::fmod(a, perimeter); + if (a < 0.) + a += perimeter; + // cum[k] <= a < cum[k + 1]. Segment lengths are positive, duplicates were dropped. + size_t k = size_t(std::upper_bound(cum.begin(), cum.end(), a) - cum.begin()) - 1; + if (k >= n) + k = n - 1; + const double t = (a - cum[k]) / (cum[k + 1] - cum[k]); + return pts[k].cast() * (1. - t) + pts[(k + 1) % n].cast() * t; +} + +} // namespace + +// ORCA: Detect mouse ear positions on one closed contour. Coordinates and ear_detection_length are scaled. +// The turn at a vertex is measured over a window of ear_detection_length of arc length per side, doubled +// while the outline keeps curving, so a corner is accepted once its turn saturates. Outer contours take +// convex corners, inner contours concave ones; candidates on the same corner collapse to the sharpest. +Points make_brim_ear_points(const Polygon &contour, coord_t ear_detection_length, + coordf_t brim_ears_max_angle, bool is_outer_brim) +{ + Points ears; + if (contour.points.size() < 3 || contour.length() <= 0 || brim_ears_max_angle <= 0) + return ears; + + const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0; + const double cos_threshold = cos(std::nextafter(angle_threshold, +INFINITY)); + const double L = double(ear_detection_length); + + // ORCA: drop points closer than 1 um to the previous kept one, so no segment has zero length. + const double min_dist2 = 1000. * 1000.; + Points pts; + std::vector index_map; + pts.reserve(contour.points.size()); + index_map.reserve(contour.points.size()); + for (size_t i = 0; i < contour.points.size(); ++i) { + if (!pts.empty() && (contour.points[i] - pts.back()).cast().squaredNorm() < min_dist2) + continue; + pts.push_back(contour.points[i]); + index_map.push_back(i); + } + const size_t n = pts.size(); + if (n < 3) + return ears; + + // Cumulative arc length of every vertex, used as the position of a candidate along the closed contour. + std::vector cum(n + 1, 0.0); + for (size_t i = 0; i < n; ++i) + cum[i + 1] = cum[i] + (pts[(i + 1) % n] - pts[i]).cast().norm(); + const double perimeter = cum[n]; + if (perimeter <= 0.) + return ears; + + struct Candidate { + size_t idx; + double dot; + double arc; + double scale; + }; + std::vector candidates; + + // ORCA: window ladder L, 2L, 4L..., capped at 16L and at perimeter/8 so a window cannot reach the far side. + std::vector scales; + if (L > 0.) { + const double s_max = std::min(16.0 * L, perimeter / 8.0); + for (double s = L;; s *= 2.) { + scales.push_back(std::min(s, s_max)); + if (s >= s_max) + break; + } + } + + for (size_t i = 0; i < n; ++i) { + const Vec2d pi = pts[i].cast(); + if (L == 0.) { + // ORCA: zero window, measure the turn at the vertex itself. + const Vec2d a = pi - pts[(i + n - 1) % n].cast(); + const Vec2d b = pts[(i + 1) % n].cast() - pi; + if (a.squaredNorm() == 0. || b.squaredNorm() == 0.) + continue; + if (is_outer_brim ? cross2(a, b) <= 0. : cross2(a, b) >= 0.) + continue; + const double dot = a.normalized().dot(b.normalized()); + if (dot < cos_threshold) + candidates.push_back({i, dot, cum[i], 0.}); + continue; + } + for (size_t m = 0; m < scales.size(); ++m) { + const double s = scales[m]; + const double s_next = std::min(2.0 * s, perimeter / 4.0); // lookahead window, kept off the far side + const Vec2d a = pi - point_at_arc(pts, cum, perimeter, cum[i] - s); + const Vec2d b = point_at_arc(pts, cum, perimeter, cum[i] + s) - pi; + if (a.squaredNorm() == 0. || b.squaredNorm() == 0.) + continue; + const Vec2d ua = a.normalized(); + const Vec2d ub = b.normalized(); + const double cross = cross2(ua, ub); + if (is_outer_brim ? cross <= 0. : cross >= 0.) + continue; + const double dot = ua.dot(ub); + if (dot >= cos_threshold) + continue; + const double turn = std::abs(std::atan2(cross, dot)); + if (turn == 0.) + continue; + // ORCA: a corner is saturated once twice the window sees no more turning; a straight leg or an + // arc keeps turning, so the 1.5 ratio rejects it. The last rung of the ladder cannot grow any + // further, so its turn is final: the lookahead from there reaches the neighbouring corner on a + // small part and would otherwise reject every corner on it. + if (m + 1 < scales.size()) { + double next_turn = turn; + const Vec2d a_next = pi - point_at_arc(pts, cum, perimeter, cum[i] - s_next); + const Vec2d b_next = point_at_arc(pts, cum, perimeter, cum[i] + s_next) - pi; + if (a_next.squaredNorm() > 0. && b_next.squaredNorm() > 0.) { + const Vec2d ua_next = a_next.normalized(); + const Vec2d ub_next = b_next.normalized(); + next_turn = std::abs(std::atan2(cross2(ua_next, ub_next), ua_next.dot(ub_next))); + } + if (next_turn > 1.5 * turn) + continue; + } + candidates.push_back({i, dot, cum[i], s}); + break; + } + } + + // ORCA: take the most local candidate first (smallest window, i.e. the corner centre), then the sharpest, + // drop everything on the same corner, repeat. Chaining neighbours would swallow a curved contour. + const double fallback_suppress = double(std::max(1, scale_(0.01))); // 0.01 mm when there is no window + while (!candidates.empty()) { + size_t best = 0; + for (size_t c = 1; c < candidates.size(); ++c) { + const Candidate &cc = candidates[c]; + const Candidate &cb = candidates[best]; + if (cc.scale < cb.scale || + (cc.scale == cb.scale && (cc.dot < cb.dot || + (cc.dot == cb.dot && cc.idx < cb.idx)))) + best = c; + } + const Candidate picked = candidates[best]; + ears.emplace_back(contour.points[index_map[picked.idx]]); + // ORCA: suppress within twice the window that detected the ear, taking the wider of the two windows: a + // candidate whose window already reaches the picked ear measured the same corner, which otherwise leaves + // a duplicate beside a corner that meets a curve. Capped at perimeter/8 so a small part keeps every ear. + std::vector remaining; + remaining.reserve(candidates.size() - 1); + for (size_t c = 0; c < candidates.size(); ++c) { + if (c == best) + continue; + const double ds = std::abs(candidates[c].arc - picked.arc); + const double suppress_distance = + L > 0. ? std::min(2.0 * std::max(picked.scale, candidates[c].scale), perimeter / 8.0) + : fallback_suppress; + if (std::min(ds, perimeter - ds) > suppress_distance) + remaining.push_back(candidates[c]); + } + candidates = std::move(remaining); + } + return ears; +} + // Generate ears // Ported from SuperSlicer: https://github.com/supermerill/SuperSlicer/blob/45d0532845b63cd5cefe7de7dc4ef0e0ed7e030a/src/libslic3r/Brim.cpp#L1116 static ExPolygons make_brim_ears_auto(const ExPolygons& obj_expoly, coord_t size_ear, coord_t ear_detection_length, @@ -355,24 +522,9 @@ static ExPolygons make_brim_ears_auto(const ExPolygons& obj_expoly, coord_t size return mouse_ears_ex; } // Detect places to put ears - const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0; Points pt_ears; - for (const ExPolygon &poly : obj_expoly) { - Polygon decimated_polygon = poly.contour; - if (ear_detection_length > 0) { - // decimate polygon - Points points = poly.contour.points; - points.push_back(points.front()); - points = MultiPoint::_douglas_peucker(points, ear_detection_length); - if (points.size() > 4) { // don't decimate if it's going to be below 4 points, as it's surely enough to fill everything anyway - points.erase(points.end() - 1); - decimated_polygon.points = points; - } - } - - append(pt_ears, is_outer_brim ? decimated_polygon.convex_points(angle_threshold) - : decimated_polygon.concave_points(angle_threshold)); - } + for (const ExPolygon &poly : obj_expoly) + append(pt_ears, make_brim_ear_points(poly.contour, ear_detection_length, brim_ears_max_angle, is_outer_brim)); // Then add ears // create ear pattern diff --git a/src/libslic3r/Brim.hpp b/src/libslic3r/Brim.hpp index 9279b1e023..ad9726a331 100644 --- a/src/libslic3r/Brim.hpp +++ b/src/libslic3r/Brim.hpp @@ -5,6 +5,7 @@ #include "ObjectID.hpp" #include "Point.hpp" #include "Polygon.hpp" +#include "libslic3r.h" #include #include @@ -31,6 +32,13 @@ ExtrusionEntityCollection makeBrimInfillFromPlateCoordinates(const ExPolygons& s // BBS: automatically make brim ExtrusionEntityCollection make_brim_auto(const Print &print, PrintTryCancel try_cancel, Polygons &islands_area); +// ORCA: Detect mouse ear positions on one closed contour. Coordinates and ear_detection_length are scaled. +// The window starts at ear_detection_length and doubles while the outline keeps curving; a corner is accepted +// once its turn saturates. Outer contours take convex corners, inner contours concave ones; candidates on the +// same corner collapse to the sharpest. +Points make_brim_ear_points(const Polygon &contour, coord_t ear_detection_length, + coordf_t brim_ears_max_angle, bool is_outer_brim); + } // Slic3r #endif // slic3r_Brim_hpp_ diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index b5514c4352..ba03678d1b 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -2211,9 +2211,10 @@ void PrintConfigDef::init_fff_params() def = this->add("brim_ears_detection_length", coFloat); def->label = L("Brim ear detection radius"); def->category = L("Support"); - def->tooltip = L("The geometry will be decimated before detecting sharp angles. " - "This parameter indicates the minimum length of the deviation for the decimation.\n" - "0 to deactivate."); + def->tooltip = L("The direction change at a corner is measured over a window of this length along the outline.\n" + "The window grows while the outline keeps curving, so a rounded corner counts as one corner " + "once its whole turn is seen.\n" + "0 to measure the angle at every vertex without smoothing."); def->sidetext = L("mm"); // millimeters, CIS languages need translation def->min = 0; def->mode = comAdvanced; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp index 34f49dfc53..790fa3af24 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp @@ -20,6 +20,7 @@ #include "slic3r/GUI/Event.hpp" #include "libslic3r/Utils.hpp" #include "libslic3r/Point.hpp" +#include "libslic3r/Brim.hpp" #include "libslic3r/BrimEarsPoint.hpp" #include "libslic3r/Geometry.hpp" #include @@ -958,22 +959,9 @@ void GLGizmoBrimEars::reload_cache() find_single(); } -Points GLGizmoBrimEars::generate_points(Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer) +Points GLGizmoBrimEars::generate_points(const Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer) { - const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0; - Points pt_ears; - if (ear_detection_length > 0) { - double detect_length = ear_detection_length / SCALING_FACTOR; - Points points = obj_polygon.points; - points.push_back(points.front()); - points = MultiPoint::_douglas_peucker(points, detect_length); - if (points.size() > 4) { - points.erase(points.end() - 1); - } - obj_polygon.points = points; - } - append(pt_ears, is_outer ? obj_polygon.convex_points(angle_threshold) : obj_polygon.concave_points(angle_threshold)); - return pt_ears; + return make_brim_ear_points(obj_polygon, scale_(ear_detection_length), brim_ears_max_angle, is_outer); } void GLGizmoBrimEars::first_layer_slicer() @@ -1053,6 +1041,7 @@ void GLGizmoBrimEars::get_detection_radius_max() min_points_num = MultiPoint::_douglas_peucker(out_points, 0).size(); int repeat = 0; int loop_protect = 0; + // ORCA: only a feature-size estimate for the slider's upper bound; the detector no longer decimates. for (;;) { loop_protect++; tolerance += 10; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp index 35177bfac6..7153b3e93b 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp @@ -159,7 +159,7 @@ private: void select_point(int i); void unselect_point(int i); void reload_cache(); - Points generate_points(Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer); + Points generate_points(const Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer); void auto_generate(); void first_layer_slicer(); void get_detection_radius_max(); diff --git a/tests/fff_print/test_skirt_brim.cpp b/tests/fff_print/test_skirt_brim.cpp index c03daa74d0..e3f091d59a 100644 --- a/tests/fff_print/test_skirt_brim.cpp +++ b/tests/fff_print/test_skirt_brim.cpp @@ -472,6 +472,120 @@ TEST_CASE("Outer-only painted brim ears stay out of model holes", "[SkirtBrim]") CHECK_FALSE(brim_enters_first_layer_hole(print)); } +// A 40 mm wide, 3 mm tall prism whose 70 degree apex is rounded by a 1.5 mm fillet in six chords: the +// outline test_brim.cpp builds, as a mesh the pipeline can slice. +// Same outline as filleted_triangle_outline(1.5, 6) in the libslic3r test_brim.cpp fixture. +static TriangleMesh triangle_with_rounded_apex() +{ + const std::vector outline{ + Vec2d(0., 0.), Vec2d(40., 0.), Vec2d(17.6811, 26.5986), Vec2d(17.3195, 26.9111), + Vec2d(16.8780, 27.0940), Vec2d(16.4013, 27.1287), Vec2d(15.9380, 27.0117), Vec2d(15.5349, 26.7549), + Vec2d(15.2330, 26.3844), + }; + const float height = 3.f; + std::vector vertices; + std::vector faces; + const size_t n = outline.size(); + for (const Vec2d &p : outline) { + vertices.emplace_back(float(p.x()), float(p.y()), 0.f); + vertices.emplace_back(float(p.x()), float(p.y()), height); + } + // Fan from rim vertex 0, so the first triangle is i = 1; starting at 0 would emit a face with a + // repeated vertex on both caps. + for (size_t i = 1; i + 1 < n; ++ i) { + faces.emplace_back(0, int(2 * (i + 1)), int(2 * i)); // bottom cap, facing down + faces.emplace_back(1, int(2 * i + 1), int(2 * (i + 1) + 1)); // top cap, facing up + } + for (size_t i = 0; i < n; ++ i) { + const size_t j = (i + 1) % n; + faces.emplace_back(int(2 * i), int(2 * j), int(2 * j + 1)); + faces.emplace_back(int(2 * i), int(2 * j + 1), int(2 * i + 1)); + } + return TriangleMesh(vertices, faces); +} + +// One entry per ear. The slicer clips each ear disc against the object, so an ear is a half disc, not a +// ring; its axis-aligned bounding box centre still identifies it, and that centre stays valid under the +// turns used below. Coordinates are scaled, hence scaled() tolerances. +static std::vector brim_ear_centres(Print &print) +{ + std::vector centres; + for (const auto &kv : print.get_brimMap()) { + Polylines paths; + kv.second.collect_polylines(paths); + for (const Polyline &path : paths) { + if (path.points.empty()) + continue; + const BoundingBox box = path.bounding_box(); + const Vec2d centre = (box.min.cast() + box.max.cast()) * 0.5; + if (std::none_of(centres.begin(), centres.end(), [¢re](const Vec2d &e) { return (e - centre).norm() < scaled(1.); })) + centres.push_back(centre); + } + } + return centres; +} + +// Sorted distances between every pair of ear centres: independent of where the part ends up on the plate. +static std::vector ear_centre_distances(const std::vector ¢res) +{ + std::vector distances; + for (size_t i = 0; i < centres.size(); ++ i) + for (size_t j = i + 1; j < centres.size(); ++ j) + distances.push_back((centres[i] - centres[j]).norm()); + std::sort(distances.begin(), distances.end()); + return distances; +} + +// A rounded corner must keep its ear whatever the part's orientation: the corner used to be measured after +// a decimation anchored on the contour's start vertex, which moves when the object is rotated. +TEST_CASE("Mouse ears stay on the same corners when the object rotates", "[SkirtBrim]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "skirt_loops", 0 }, + { "brim_type", "brim_ears" }, + { "brim_width", 3 }, + { "brim_ears_max_angle", 125 }, + { "brim_ears_detection_length", 1 }, + { "initial_layer_line_width", 0.5 }, + }); + + // Not auto-arranged, so the part is rotated about its own footprint centre and stays on the bed. + auto slice_rotated = [&config](double rotation) { + Print print; + Model model; + init_print({ triangle_with_rounded_apex() }, print, model, config, nullptr, false); + const Vec3d pivot = model.objects.front()->raw_mesh_bounding_box().center(); + const Transform3d about_pivot = Geometry::translation_transform(Vec3d(pivot.x(), pivot.y(), 0.)) * + Geometry::rotation_transform(Vec3d(0., 0., Geometry::deg2rad(rotation))) * + Geometry::translation_transform(Vec3d(-pivot.x(), -pivot.y(), 0.)); + model.objects.front()->instances.front()->set_transformation(Geometry::Transformation(about_pivot)); + print.apply(model, config); + print.process(); + return std::make_pair(brim_loop_count(print), brim_ear_centres(print)); + }; + + const std::pair> base = slice_rotated(0.); + REQUIRE(base.first > 0); + // Two sharp base corners plus the rounded apex, at every orientation. + REQUIRE(base.second.size() == 3); + const std::vector base_distances = ear_centre_distances(base.second); + + for (double rotation : { 37., 90., 180. }) { + DYNAMIC_SECTION("rotation " << rotation) { + const std::pair> rotated = slice_rotated(rotation); + REQUIRE(rotated.second.size() == base.second.size()); + CHECK(rotated.first == base.first); + // The ear positions are compared up to the rigid motion the rotation applies, so the plate + // placement the slicer chooses for the rotated footprint does not enter the comparison. + const std::vector distances = ear_centre_distances(rotated.second); + REQUIRE(distances.size() == base_distances.size()); + for (size_t i = 0; i < distances.size(); ++ i) + CHECK_THAT(distances[i], Catch::Matchers::WithinAbs(base_distances[i], scaled(0.5))); + } + } +} + SCENARIO("Skirt has the configured number of loops", "[SkirtBrim]") { GIVEN("20mm cube and default config") { WHEN("skirt_loops is set to 2") { diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 41c0fb05df..e2f39a622f 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -23,6 +23,8 @@ add_executable(${_TEST_NAME}_tests test_assemble_list.cpp test_bambu_networking.cpp test_belt_brim.cpp + # Mouse ear detection is pure contour geometry; the slicing pipeline stays in fff_print. + test_brim.cpp test_buildvolume.cpp test_calib.cpp test_clipper_offset.cpp diff --git a/tests/libslic3r/test_brim.cpp b/tests/libslic3r/test_brim.cpp new file mode 100644 index 0000000000..f3a652f8a9 --- /dev/null +++ b/tests/libslic3r/test_brim.cpp @@ -0,0 +1,502 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "catch2/catch_test_macros.hpp" +#include "catch2/matchers/catch_matchers.hpp" +#include "catch2/matchers/catch_matchers_floating_point.hpp" +#include "libslic3r/Brim.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/libslic3r.h" + +using namespace Slic3r; + +namespace { + +// Ear points come back in no particular order, so compare them as a set. +bool same_point_set(const Points &a, const Points &b, coord_t tolerance) +{ + if (a.size() != b.size()) + return false; + std::vector matched(b.size(), false); + for (const Point &p : a) { + bool found = false; + for (size_t i = 0; i < b.size() && ! found; ++ i) { + if (! matched[i] && std::abs(p.x() - b[i].x()) <= tolerance && std::abs(p.y() - b[i].y()) <= tolerance) { + matched[i] = true; + found = true; + } + } + if (! found) + return false; + } + return true; +} + +bool contains_point(const Points &points, const Point &expected, coord_t tolerance) +{ + return std::any_of(points.begin(), points.end(), [&expected, tolerance](const Point &p) { + return std::abs(p.x() - expected.x()) <= tolerance && std::abs(p.y() - expected.y()) <= tolerance; + }); +} + +bool is_finite(const Point &p) +{ + return std::isfinite(unscale(p.x())) && std::isfinite(unscale(p.y())); +} + +// Arc that replaces `corner` between `prev` and `next`, as `segments` chords of the given radius, in mm. +std::vector fillet_arc(const Vec2d &prev, const Vec2d &corner, const Vec2d &next, double radius, int segments) +{ + const Vec2d to_prev = (prev - corner).normalized(); + const Vec2d to_next = (next - corner).normalized(); + const double half = std::acos(std::clamp(to_prev.dot(to_next), -1., 1.)) / 2.; + const double tangent = radius / std::tan(half); + const Vec2d start = corner + to_prev * tangent; + const Vec2d end = corner + to_next * tangent; + const Vec2d centre = corner + (to_prev + to_next).normalized() * (radius / std::sin(half)); + const double from = std::atan2(start.y() - centre.y(), start.x() - centre.x()); + const double to = std::atan2(end.y() - centre.y(), end.x() - centre.x()); + double sweep = to - from; + while (sweep > PI) + sweep -= 2. * PI; + while (sweep < -PI) + sweep += 2. * PI; + std::vector arc; + for (int i = 0; i <= segments; ++ i) { + const double angle = from + sweep * i / segments; + arc.emplace_back(centre.x() + radius * std::cos(angle), centre.y() + radius * std::sin(angle)); + } + return arc; +} + +// The arc that fillet_arc puts at a corner: its middle point in mm, and the angle it sweeps in radians. +struct Fillet { + Vec2d midpoint; + double sweep; +}; + +Fillet fillet_geometry(const Vec2d &prev, const Vec2d &corner, const Vec2d &next, double radius) +{ + const Vec2d to_prev = (prev - corner).normalized(); + const Vec2d to_next = (next - corner).normalized(); + const double half = std::acos(std::clamp(to_prev.dot(to_next), -1., 1.)) / 2.; + const Vec2d midpoint = corner + (to_prev + to_next).normalized() * (radius / std::sin(half) - radius); + return Fillet{ midpoint, PI - 2. * half }; +} + +// A closed outline plus the geometry of the arc that replaced each of its corners. +struct FilletedOutline { + std::vector outline; + std::vector corners; +}; + +// Replace every corner of the closed `corners` polygon with an arc of `radius` in `chords` chords. +FilletedOutline filleted_outline(const std::vector &corners, double radius, int chords) +{ + FilletedOutline filleted; + filleted.outline.reserve(corners.size() * size_t(chords + 1)); + filleted.corners.reserve(corners.size()); + for (size_t i = 0; i < corners.size(); ++ i) { + const Vec2d &prev = corners[(i + corners.size() - 1) % corners.size()]; + const Vec2d &next = corners[(i + 1) % corners.size()]; + const std::vector arc = fillet_arc(prev, corners[i], next, radius, chords); + filleted.outline.insert(filleted.outline.end(), arc.begin(), arc.end()); + filleted.corners.push_back(fillet_geometry(prev, corners[i], next, radius)); + } + return filleted; +} + +// 40 mm wide triangle with a 70 degree apex rounded by a fillet of `radius` in `chords` chords, counter-clockwise. +// The 60 / 50 degree base corners are deliberately unequal: a mirror symmetric outline ties the fillet's +// two sharpest vertices exactly, and the tie is then broken by vertex index. +struct FilletedTriangle { + std::vector outline; + Fillet apex; +}; + +FilletedTriangle filleted_triangle(double radius, int chords) +{ + const Vec2d a(0., 0.); + const Vec2d b(40., 0.); + const double to_apex = 40. * std::sin(50. * PI / 180.) / std::sin(70. * PI / 180.); + const Vec2d apex = a + Vec2d(std::cos(60. * PI / 180.), std::sin(60. * PI / 180.)) * to_apex; + const std::vector arc = fillet_arc(a, apex, b, radius, chords); + std::vector outline{ a, b }; + outline.insert(outline.end(), arc.rbegin(), arc.rend()); + return { outline, fillet_geometry(a, apex, b, radius) }; +} + +std::vector filleted_triangle_outline(double radius, int chords) +{ + return filleted_triangle(radius, chords).outline; +} + +// Axis-aligned CCW square (0, 0)..(side, side) with every corner filleted. +FilletedOutline filleted_square_outline(double side, double radius, int chords) +{ + return filleted_outline({ Vec2d(0., 0.), Vec2d(side, 0.), Vec2d(side, side), Vec2d(0., side) }, radius, chords); +} + +// Regular polygon with `sides` vertices on a circle of the given radius, counter-clockwise. +std::vector regular_polygon_outline(int sides, double radius) +{ + std::vector outline; + outline.reserve(size_t(sides)); + for (int i = 0; i < sides; ++ i) { + const double angle = 2. * PI * i / sides; + outline.emplace_back(radius * std::cos(angle), radius * std::sin(angle)); + } + return outline; +} + +// Regular `chords`-gon approximating a circle of the given radius. +std::vector circle_outline(double radius, int chords) +{ + return regular_polygon_outline(chords, radius); +} + +// Half disc of `radius`: a flat side and a `chords`-chord semicircular wall meeting it at two right angles. +std::vector half_disc_outline(double radius, int chords) +{ + std::vector outline; + outline.reserve(size_t(chords) + 1); + outline.emplace_back(-radius, 0.); + for (int i = 1; i <= chords; ++ i) { + const double angle = PI + PI * i / chords; + outline.emplace_back(radius * std::cos(angle), radius * std::sin(angle)); + } + return outline; +} + +// Ellipse with semi-axes `a` and `b` in `chords` chords. +std::vector ellipse_outline(double a, double b, int chords) +{ + std::vector outline; + outline.reserve(size_t(chords)); + for (int i = 0; i < chords; ++ i) { + const double angle = 2. * PI * i / chords; + outline.emplace_back(a * std::cos(angle), b * std::sin(angle)); + } + return outline; +} + +// Mean of the outline's vertices, in mm. +Vec2d outline_centroid(const std::vector &points) +{ + Vec2d sum = Vec2d::Zero(); + for (const Vec2d &p : points) + sum += p; + return sum / double(points.size()); +} + +std::vector to_mm(const Points &points) +{ + std::vector out; + out.reserve(points.size()); + for (const Point &p : points) + out.emplace_back(unscale(p.x()), unscale(p.y())); + return out; +} + +// Sorted distances between every pair of points, in mm: unchanged by a rigid motion of the whole set. +std::vector pairwise_distances(const std::vector &points) +{ + std::vector distances; + distances.reserve(points.size() * (points.size() - 1) / 2); + for (size_t i = 0; i < points.size(); ++ i) + for (size_t j = i + 1; j < points.size(); ++ j) + distances.push_back((points[i] - points[j]).norm()); + std::sort(distances.begin(), distances.end()); + return distances; +} + +// Ears sitting on one rounded corner: within half a chord of the arc's midpoint, which is the closest any +// point of the fillet gets to an ear placed on it. +size_t ears_on_corner(const Points &ears, const Fillet &corner, double radius, int chords) +{ + const Point midpoint = Point::new_scale(corner.midpoint); + const coord_t tolerance = coord_t(scale_(radius + 0.5 * radius * corner.sweep / chords)); + return size_t(std::count_if(ears.begin(), ears.end(), [&midpoint, tolerance](const Point &ear) { + return (ear - midpoint).cast().norm() <= double(tolerance); + })); +} + +// A quarter turn about the origin is exact in scaled integer coordinates. +Point rotated_quarter_turns(const Point &p, int quarter) +{ + Point rotated = p; + for (int i = 0; i < quarter; ++ i) + rotated = Point(-rotated.y(), rotated.x()); + return rotated; +} + +} // namespace + +// The detection must read the corner, not the contour's start vertex: a decimation anchored on the first +// vertex used to place an ear on a rounded corner for some vertex orders and not for others. +TEST_CASE("Brim ear detection is independent of the contour start vertex", "[Brim][Regression]") +{ + struct Case { double radius; int chords; }; + + const coord_t detection = coord_t(scale_(1.0)); + for (const Case &c : { Case{ 1.5, 6 }, Case{ 2.0, 12 }, Case{ 5.0, 12 } }) { + DYNAMIC_SECTION("fillet " << c.radius << " mm in " << c.chords << " chords") { + const Points contour = Polygon::new_scale(filleted_triangle_outline(c.radius, c.chords)).points; + const Points found = make_brim_ear_points(Polygon(contour), detection, 125., true); + // Two sharp base corners plus the rounded apex. + REQUIRE(found.size() == 3); + + for (size_t shift = 1; shift < contour.size(); ++ shift) { + Points shifted; + shifted.reserve(contour.size()); + std::rotate_copy(contour.begin(), contour.begin() + shift, contour.end(), std::back_inserter(shifted)); + const Points ears = make_brim_ear_points(Polygon(shifted), detection, 125., true); + CHECK(ears.size() == found.size()); + CHECK(same_point_set(ears, found, 2)); + } + } + } +} + +TEST_CASE("Brim ear detection rotates with the contour", "[Brim]") +{ + const std::vector outline = filleted_triangle_outline(1.5, 6); + const Points contour = Polygon::new_scale(outline).points; + const coord_t detection = coord_t(scale_(1.0)); + const Points base = make_brim_ear_points(Polygon(contour), detection, 125., true); + REQUIRE(base.size() == 3); + + for (int quarter : { 1, 2, 3 }) { + DYNAMIC_SECTION("quarter turns " << quarter) { + Points rotated_contour; + rotated_contour.reserve(contour.size()); + for (const Point &p : contour) + rotated_contour.push_back(rotated_quarter_turns(p, quarter)); + Points expected; + expected.reserve(base.size()); + for (const Point &p : base) + expected.push_back(rotated_quarter_turns(p, quarter)); + + const Points ears = make_brim_ear_points(Polygon(rotated_contour), detection, 125., true); + CHECK(ears.size() == base.size()); + CHECK(same_point_set(ears, expected, 2)); + } + } + + SECTION("37 degrees") { + // 37 degrees is not exact in scaled integer coordinates, so compare ear distances instead of positions. + const Vec2d centre = outline_centroid(outline); + const double angle = 37. * PI / 180.; + const auto rotate = [¢re, angle](const Vec2d &p) -> Vec2d { + const Vec2d d(p.x() - centre.x(), p.y() - centre.y()); + return Vec2d(centre.x() + d.x() * std::cos(angle) - d.y() * std::sin(angle), + centre.y() + d.x() * std::sin(angle) + d.y() * std::cos(angle)); + }; + + Points rotated_contour; + rotated_contour.reserve(outline.size()); + for (const Vec2d &p : outline) + rotated_contour.push_back(Point::new_scale(rotate(p))); + + std::vector expected = to_mm(base); + for (Vec2d &p : expected) + p = rotate(p); + + const Points ears = make_brim_ear_points(Polygon(rotated_contour), detection, 125., true); + const std::vector found_distances = pairwise_distances(to_mm(ears)); + const std::vector expected_distances = pairwise_distances(expected); + REQUIRE(found_distances.size() == expected_distances.size()); + for (size_t i = 0; i < found_distances.size(); ++ i) + CHECK_THAT(found_distances[i], Catch::Matchers::WithinAbs(expected_distances[i], 0.01)); + } +} + +TEST_CASE("A rounded apex carries a single brim ear", "[Brim]") +{ + const coord_t detection = coord_t(scale_(1.0)); + + for (double radius : { 0.5, 1.5, 3.0, 5.0 }) { + for (int chords : { 3, 6, 12, 24 }) { + DYNAMIC_SECTION("fillet " << radius << " mm in " << chords << " chords") { + const FilletedTriangle triangle = filleted_triangle(radius, chords); + const Points ears = make_brim_ear_points(Polygon::new_scale(triangle.outline), detection, 125., true); + // Two sharp base corners plus the rounded apex. + REQUIRE(ears.size() == 3); + + // A fillet is one corner, so exactly one ear sits on it, never a row along its chords. + CHECK(ears_on_corner(ears, triangle.apex, radius, chords) == 1); + } + } + } +} + +TEST_CASE("A square keeps one brim ear per rounded corner", "[Brim][Regression]") +{ + const coord_t detection = coord_t(scale_(1.0)); + const double radius = 5.; + const int chords = 12; + const FilletedOutline square = filleted_square_outline(40., radius, chords); + const Points ears = make_brim_ear_points(Polygon::new_scale(square.outline), detection, 125., true); + + // Four 90 degree corners, each rounded by one fillet: four ears, not one per chord. + REQUIRE(ears.size() == 4); + + for (const Fillet &corner : square.corners) + CHECK(ears_on_corner(ears, corner, radius, chords) == 1); +} + +// A part whose fillets take up most of the perimeter: the ladder stops at its cap of perimeter/8, so the +// saturation lookahead already reaches the neighbouring corner, and twice the window reaches the +// neighbouring ear. Detection used to return two ears at some orientations and none at others. +TEST_CASE("A small part keeps one brim ear per rounded corner", "[Brim][Regression]") +{ + const coord_t detection = coord_t(scale_(1.0)); + + SECTION("12 mm square with 4 mm fillets") { + const double radius = 4.; + const int chords = 12; + const FilletedOutline square = filleted_square_outline(12., radius, chords); + const Points ears = make_brim_ear_points(Polygon::new_scale(square.outline), detection, 125., true); + + REQUIRE(ears.size() == 4); + for (const Fillet &corner : square.corners) + CHECK(ears_on_corner(ears, corner, radius, chords) == 1); + } + + SECTION("10 mm hexagon with 2 mm fillets") { + const double radius = 2.; + const int chords = 6; + const FilletedOutline hexagon = filleted_outline(regular_polygon_outline(6, 10.), radius, chords); + const Points ears = make_brim_ear_points(Polygon::new_scale(hexagon.outline), detection, 125., true); + + REQUIRE(ears.size() == 6); + for (const Fillet &corner : hexagon.corners) + CHECK(ears_on_corner(ears, corner, radius, chords) == 1); + } +} + +TEST_CASE("A smooth contour has no brim ears", "[Brim]") +{ + const coord_t detection = coord_t(scale_(1.0)); + + // A circle's turn is spread evenly, so no vertex turns past the threshold at any measurement scale. + CHECK(make_brim_ear_points(Polygon::new_scale(circle_outline(5., 48)), detection, 125., true).empty()); + // A 24-gon is as smooth as the detector can tell at the default 1 mm detection length. + CHECK(make_brim_ear_points(Polygon::new_scale(regular_polygon_outline(24, 10.)), detection, 125., true).empty()); +} + +// A corner that meets a curved wall is one corner. A point on the curve accepts only once its window reaches +// that corner, so its candidate is the same corner seen from further away; keeping it puts a second ear 2 to +// 7 mm from the first. +TEST_CASE("A corner next to a curve carries one brim ear", "[Brim][Regression]") +{ + const coord_t detection = coord_t(scale_(1.0)); + + for (double radius : { 5., 10. }) { + DYNAMIC_SECTION("half disc of " << radius << " mm") { + const Points ears = make_brim_ear_points(Polygon::new_scale(half_disc_outline(radius, 64)), + detection, 125., true); + // Two right angles, one at each end of the flat side, and nothing on the semicircle between them. + REQUIRE(ears.size() == 2); + for (const Point &ear : ears) { + CHECK_THAT(std::abs(unscale(ear.x())), Catch::Matchers::WithinAbs(radius, 1.)); + CHECK_THAT(unscale(ear.y()), Catch::Matchers::WithinAbs(0., 1.)); + } + } + } + + for (int chords : { 64, 128 }) { + DYNAMIC_SECTION("60 x 10 mm ellipse in " << chords << " chords") { + const Points ears = make_brim_ear_points(Polygon::new_scale(ellipse_outline(30., 5., chords)), + detection, 125., true); + // One ear at each end of the long axis, none on the flanks. + REQUIRE(ears.size() == 2); + for (const Point &ear : ears) + CHECK(std::abs(unscale(ear.x())) > 25.); + } + } +} + +TEST_CASE("A pentagon keeps one brim ear per rounded corner", "[Brim][Regression]") +{ + // Side 20 mm: circumradius 20 / (2 sin 36 degrees), every corner rounded by 1 mm in six chords. + const std::vector corners = regular_polygon_outline(5, 20. / (2. * std::sin(PI / 5.))); + const FilletedOutline filleted = filleted_outline(corners, 1., 6); + const Points ears = make_brim_ear_points(Polygon::new_scale(filleted.outline), + coord_t(scale_(1.0)), 125., true); + + // Five 72 degree corners: a decimation that collapsed the outline to a triangle would report three. + REQUIRE(ears.size() == 5); +} + +TEST_CASE("Zero detection length still finds the sharp corners", "[Brim]") +{ + const std::vector outline = filleted_triangle_outline(1.5, 6); + const Points contour = Polygon::new_scale(outline).points; + const Points ears = make_brim_ear_points(Polygon(contour), 0, 125., true); + + // With immediate neighbours only, the two base corners turn far past the threshold and the fillet does not. + REQUIRE(ears.size() == 2); + CHECK(contains_point(ears, contour[0], 2)); + CHECK(contains_point(ears, contour[1], 2)); + for (const Point &ear : ears) + CHECK(is_finite(ear)); +} + +TEST_CASE("A concave notch takes brim ears on an inner contour", "[Brim]") +{ + // 40 x 40 mm plate with a 10 x 10 mm notch in its top edge, given in the winding a hole is stored in. + const std::vector stored_outline{ + Vec2d(0., 40.), Vec2d(20., 40.), Vec2d(20., 30.), Vec2d(30., 30.), + Vec2d(30., 40.), Vec2d(40., 40.), Vec2d(40., 0.), Vec2d(0., 0.), + }; + Polygons holes{ Polygon::new_scale(stored_outline) }; + // outer_inner_brim_area reverses hole contours before its concave pass, so the test does the same. + polygons_reverse(holes); + const Polygon &contour = holes.front(); + const coord_t detection = coord_t(scale_(1.0)); + + const auto on_notch_floor = [](const Point &ear) { + const double x = unscale(ear.x()); + const double y = unscale(ear.y()); + return std::abs(y - 30.) < 1. && x > 19. && x < 31.; + }; + + const Points concave_ears = make_brim_ear_points(contour, detection, 125., false); + REQUIRE(! concave_ears.empty()); + CHECK(std::all_of(concave_ears.begin(), concave_ears.end(), on_notch_floor)); + + const Points convex_ears = make_brim_ear_points(contour, detection, 125., true); + CHECK(! convex_ears.empty()); + CHECK(std::none_of(convex_ears.begin(), convex_ears.end(), on_notch_floor)); +} + +TEST_CASE("A clockwise contour keeps brim ear detection well defined", "[Brim]") +{ + Points contour = Polygon::new_scale(filleted_triangle_outline(1.5, 6)).points; + std::reverse(contour.begin(), contour.end()); + + Points ears; + REQUIRE_NOTHROW(ears = make_brim_ear_points(Polygon(contour), coord_t(scale_(1.0)), 125., true)); + // The convexity predicate is winding sensitive, so a reversed outer contour has no convex corner left. + CHECK(ears.empty()); +} + +TEST_CASE("Brim ear max angle excludes a corner at exactly the bound", "[Brim]") +{ + // A rectangle's corners turn by exactly 90 degrees. + const std::vector rectangle{ Vec2d(0., 0.), Vec2d(40., 0.), Vec2d(40., 20.), Vec2d(0., 20.) }; + const Polygon contour = Polygon::new_scale(rectangle); + const coord_t detection = coord_t(scale_(1.0)); + + CHECK(make_brim_ear_points(contour, detection, 91., true).size() == 4); + CHECK(make_brim_ear_points(contour, detection, 90., true).empty()); + CHECK(make_brim_ear_points(contour, detection, 89., true).empty()); +} From 736d07ade9e21d88c5f754ec73b49067c98df68e Mon Sep 17 00:00:00 2001 From: Kris Austin Date: Thu, 19 Nov 2026 08:14:46 -0600 Subject: [PATCH 09/36] Let the stale bot handle feature requests and run more per day (#17708) Enhancement issues are no longer exempt. Many old feature requests may no longer apply, and the stale notice lets the author say whether they still want it. The stale and close messages now fit both bugs and feature requests. operations-per-run goes from 300 to 800. At 300, one pass over the open issues and PRs took 7 runs, so a reply could keep the stale label for up to a week. 800 still keeps each run under GitHub's limit of 500 comments an hour. --- .github/workflows/stale.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index b4e6ba27a7..e3a03bddc5 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -16,9 +16,10 @@ jobs: steps: - uses: actions/stale@v11 with: - # Each new stale label costs about 2 operations. Runs that stop early - # continue from the same place the next day. - operations-per-run: 300 + # Each stale label or close costs about 2 operations and posts one + # comment, so 800 stays under GitHub's limit of 500 comments an hour. + # Runs that stop early continue from the same place the next day. + operations-per-run: 800 ascending: true stale-issue-label: stale stale-pr-label: stale @@ -28,17 +29,16 @@ jobs: days-before-issue-stale: 90 days-before-issue-close: 14 close-issue-reason: not_planned - exempt-issue-labels: enhancement exempt-all-issue-assignees: true exempt-all-issue-milestones: true stale-issue-message: | This issue has had no activity for 90 days, so it will be closed in 14 days. - If it still happens on the latest OrcaSlicer release, please leave a comment with the version you tested and it will stay open. + If it's a bug that still happens on the latest OrcaSlicer release, please leave a comment with the version you tested. If it's a feature request you still want, please leave a comment saying so. Either one keeps it open. close-issue-message: | This issue was closed because there was no activity after the reminder. - If it still happens on the latest release, leave a comment here and a team member can reopen it, or open a new issue with the details. + If it still matters to you, leave a comment here and a team member can reopen it, or open a new issue with the details. # PRs: only PRs where we asked the author for something only-pr-labels: "wait for response" From 7932cd23f7d28837d12ad2825e51cc0a86e38b61 Mon Sep 17 00:00:00 2001 From: Kris Austin Date: Thu, 19 Nov 2026 08:43:40 -0600 Subject: [PATCH 10/36] Remove the stale label as soon as someone comments (#17709) stale.yml only removes the label when its daily run gets back to an issue or PR, which can take a few days. A new workflow removes it when a user comments on an open item that has the label. The stale bot also checks exemptions before activity, so a stale item that later gets an assignee or milestone, becomes a draft, or loses "wait for response" is never checked again and keeps its label. A new step in stale.yml removes the label from those. --- .github/workflows/stale.yml | 30 +++++++++++++++++++- .github/workflows/unstale-on-comment.yml | 36 ++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/unstale-on-comment.yml diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index e3a03bddc5..9d75d85845 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -10,6 +10,10 @@ permissions: issues: write pull-requests: write +# Overlapping runs would overwrite each other's saved progress. +concurrency: + group: stale + jobs: stale: runs-on: ubuntu-latest @@ -25,6 +29,9 @@ jobs: stale-pr-label: stale remove-stale-when-updated: true + # The last step mirrors the exempt and only-labels options below. + # Update its filters when they change. + # Issues days-before-issue-stale: 90 days-before-issue-close: 14 @@ -51,8 +58,29 @@ jobs: stale-pr-message: | We asked for changes or more information on this PR, and there has been no activity for 90 days. It will be closed in 14 days. - To keep it open, leave a comment. If you push new commits, please also leave a short comment, because a push alone does not reset this. If you no longer have time for it, that is fine, just let us know. + To keep it open, leave a comment. If you push new commits, please also leave a short comment so we know it's ready for another look. If you no longer have time for it, that is fine, just let us know. close-pr-message: | This PR was closed because we did not hear back after the reminder. Thank you for the work you put into it. If you want to continue, push your changes and reopen it, or open a new PR. + + # The stale bot checks exemptions before activity, so it never comes back + # to a stale item that became exempt. Remove the label from those here. + - name: Remove stale labels the stale bot will not revisit + if: ${{ !cancelled() }} + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + { + gh issue list -R "$GITHUB_REPOSITORY" --label stale --state open --limit 5000 \ + --json number,assignees,milestone \ + --jq '.[] | select((.assignees | length > 0) or .milestone != null) | .number' + gh pr list -R "$GITHUB_REPOSITORY" --label stale --state open --limit 1000 \ + --json number,isDraft,assignees,milestone,labels \ + --jq '.[] | select(.isDraft or (.assignees | length > 0) or .milestone != null + or ([.labels[].name] | index("wait for response") | not)) | .number' + } | while read -r n; do + gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$n/labels/stale" --silent < /dev/null || + echo "::warning::Could not remove the stale label from #$n" + done diff --git a/.github/workflows/unstale-on-comment.yml b/.github/workflows/unstale-on-comment.yml new file mode 100644 index 0000000000..3c64c3e7b2 --- /dev/null +++ b/.github/workflows/unstale-on-comment.yml @@ -0,0 +1,36 @@ +name: Remove stale label on comment + +# stale.yml only removes the label when its daily run gets back to an item, +# which can take a few days. This removes it as soon as someone comments. +on: + issue_comment: + types: [created] + +permissions: + issues: write + pull-requests: write + +jobs: + unstale: + if: >- + github.repository == 'OrcaSlicer/OrcaSlicer' && + github.event.issue.state == 'open' && + github.event.comment.user.type == 'User' && + contains(github.event.issue.labels.*.name, 'stale') + runs-on: ubuntu-latest + steps: + - name: Remove the stale label + env: + GH_TOKEN: ${{ github.token }} + NUMBER: ${{ github.event.issue.number }} + run: | + # "Close with comment" sends the event while the issue is still open. + state=$(gh api "repos/$GITHUB_REPOSITORY/issues/$NUMBER" --jq .state) + if [ "$state" != open ]; then + exit 0 + fi + # A 404 means another comment or the stale run already removed it. + if ! gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$NUMBER/labels/stale" --silent 2> err.txt; then + cat err.txt >&2 + grep -q "HTTP 404" err.txt + fi From 5cf5ef881e0f57138888257bf3298fce0fc4dc85 Mon Sep 17 00:00:00 2001 From: Ian Chua Date: Fri, 20 Nov 2026 05:24:22 +0800 Subject: [PATCH 11/36] fix: audit process by executable (#17671) * fix: audit process execution by name, ignore args * test: fix stale test expectations * fix: resolve Windows subprocess audit targets from command line * fix: preserve quoted Windows paths in process audit grants * fix: grant shell permissions for os.system commands * fix: require grants for all possible os.system shells * fix: clarify process permission scope in prompts * refactor: simplify audit target handling * fix: handle ambiguous Windows process commands * test: fix for ambigous calls on windows --- docs/HLSD/plugin-permissions.md | 51 ++- resources/web/dialog/PluginsDialog/index.js | 2 +- src/slic3r/GUI/PluginsDialog.cpp | 4 +- src/slic3r/plugin/PluginAuditManager.cpp | 372 +++++++++++++++--- src/slic3r/plugin/PluginFsUtils.hpp | 2 + src/slic3r/plugin/PythonPluginBridge.cpp | 4 +- tests/slic3rutils/test_plugin_audit.cpp | 410 +++++++++++++++++++- 7 files changed, 783 insertions(+), 62 deletions(-) diff --git a/docs/HLSD/plugin-permissions.md b/docs/HLSD/plugin-permissions.md index 8c14679fbf..89fff7e7bf 100644 --- a/docs/HLSD/plugin-permissions.md +++ b/docs/HLSD/plugin-permissions.md @@ -29,7 +29,7 @@ Permissions are stored per plugin key. A plugin can hold: | `fs_delete` | folder list | Filesystem delete events such as `os.remove` and `shutil.rmtree`. | | `network_http` | target list | Network targets, consulted together with `network_socket` for both HTTP and socket events. A canonical `scheme://host` entry is host-wide and covers both layers; a URL with a path, port, query or trailing slash is exact; a bare host or legacy address tuple covers raw sockets. | | `network_socket` | target list | The same network matching, kept as a separate list so a plugin can declare socket access without an HTTP URL. | -| `process` | target list | Process creation and process replacement: `os.system`, `subprocess.Popen`, `os.spawn*`, `os.exec*`, `pty.spawn`, `_winapi.CreateProcess`, and similar. Targets match the audited value verbatim. | +| `process` | target list | Process creation and process replacement: `subprocess.Popen`, `os.spawn*`, `os.exec*`, `pty.spawn`, `_winapi.CreateProcess`, and similar. Targets name the tool, not its arguments. The exception is a Windows command line with an unquoted executable followed by arguments: it is stored as an exact full command line, because `CreateProcess` may resolve a longer executable prefix than the first token shows. `os.system` names the shell it runs (see "Target matching"). | | `threading` | boolean | Permission to start a Python thread with `_thread.start_new_thread`. | | `events` | target list | Audited events that expose no target, keyed as `:`, for example `Socket:socket.__new__`. Matched verbatim. | | `full_access` | boolean | Turns off the permission decision for the plugin. See "Full access". | @@ -89,8 +89,36 @@ that requested it and the nested deletes it performs inside that subtree. A canonical entry is host-wide and applies to HTTP and raw socket events for that host. A URL with a path, port, query, fragment or trailing slash that was stored without normalization remains an exact match. -- Process entries are compared verbatim with the string the audit event reports, - including Python representations of a command. +- Process entries name the tool an event runs, compared verbatim. When the event exposes + the executable or path, that argument is the target. For a command string or argv, the + first token or element is the target. Arguments after the tool are ignored, so one grant + covers repeated runs of the tool with different arguments. The exception is a Windows + command line whose executable is unquoted and followed by non-whitespace text. + `CreateProcess` resolves such a name by trying successively longer prefixes, so the first + whitespace-delimited token need not be the executable it starts: a command line + `C:\Program Files\app.exe --x` can start `C:\Program Files\app.exe`, not `C:\Program`. + The audit therefore stores the exact full command line instead of the first token, in a + reserved `CommandLine:` namespace in the `process` list. An exact entry matches only the + same full command line, compared verbatim, and a later run with different arguments asks + again. A quoted first argument, an explicit executable or application name, and a command + line that has no arguments keep the executable-only, argument-insensitive grant. The + command line is not parsed further, and the resolved executable is not checked: the same + approved command line can start a different binary if the working directory, `PATH`, or + the files it resolves through change. `os.system` works differently: + Python hands its whole string to the platform shell, so the target is every shell that may + run it. On POSIX that is `/bin/sh`. On Windows the C runtime runs the interpreter named by + `COMSPEC`, or `cmd.exe` when `COMSPEC` is unset or empty, and also falls back to `cmd.exe` + when it cannot open the configured file (ENOENT or EACCES). The configured interpreter and + the fallback are both required targets: a grant for a narrow `COMSPEC` does not authorize + the fallback shell. A `COMSPEC` that is already the bare name `cmd.exe`, in any casing, + names the fallback itself and is listed once. The value is read from the CRT environment + that `_wsystem` consults, not the process environment block, which can differ. The audit + does not test whether the `COMSPEC` file exists; the runtime decides that when it runs the + command, so a file present at prompt time can be gone by the call. The command string is + not parsed, and approving the shells covers every command and argument the plugin passes + to `os.system`. The targets are read when the event is raised, so a grant saved under one + `COMSPEC` value does not cover a run under another. Direct process creation, such as + `subprocess.Popen`, still names its executable. - An event with no target is granted by the `events` entry for its category and name. A targetless network event, such as `http.client.send`, is covered by any recorded network grant instead. @@ -191,8 +219,12 @@ whose denial aborted the load and then retry with the saved grant. Runtime approvals store the target observed by the audit hook, except that create and delete approvals store its parent folder. A URL with a path, port or -query is therefore an exact grant; a bare host remains usable for raw sockets. The -declared form and the runtime form are not normalized by the same code path. +query is therefore an exact grant; a bare host remains usable for raw sockets. A Windows +command line that needs the exact fallback is saved in the reserved `CommandLine:` namespace +as its full text, so the approval is argument-sensitive; the prompt shows the command line +without the storage marker and states that the full line, including any sensitive values in +its arguments, is shown and saved. The declared form and the runtime form are not normalized +by the same code path. A recursive delete is different: a Yes grants consent for the canonical target subtree for that operation only. The prompt shows the subtree root and states that the consent is not @@ -361,6 +393,15 @@ never treated as an opt-out. context, so its events are not attributed or restricted. - **Subprocesses leave the policy.** A process created by a granted or full-access plugin runs with the user's rights and is not covered by the parent's audit scope. +- **An `os.system` grant is a shell grant.** It authorizes every command string the plugin + passes to `os.system`, not only the one that triggered the prompt, because the shell + parses and runs the whole string. Arguments are not inspected or restricted. +- **An exact command line grant is command-sensitive, not binary-sensitive.** It is stored + and shown in full, so it can expose credentials or tokens passed as arguments to anyone + who sees the prompt or the sidecar. Approval covers only the same full command line. + `CreateProcess` still resolves the executable from the working directory, `PATH`, and the + filesystem, so the same approved command line can start a different binary later; the + grant does not pin the resolved image or verify it. - **Host APIs are not audit events.** Calls into OrcaSlicer's Python host APIs, such as preset updates or UI actions, execute C++ host code and follow that API's contract. The audit hook judges the Python-level filesystem, network, process and thread events it is diff --git a/resources/web/dialog/PluginsDialog/index.js b/resources/web/dialog/PluginsDialog/index.js index 27adc0c8eb..2c3efdc0d1 100644 --- a/resources/web/dialog/PluginsDialog/index.js +++ b/resources/web/dialog/PluginsDialog/index.js @@ -1115,7 +1115,7 @@ function RenderPermissions(plugin) { fs_readwrite: [null, ""], network_http: [null, "https://example.com"], network_socket: [null, "https://example.com"], - process: [T("permissions_process_help", "Enter the exact value recorded by the audit. It may be a Python representation of the command."), T("permissions_process_placeholder", "Exact audited value")], + process: [T("permissions_process_help", "Executable grants cover all arguments. CommandLine: entries cover only the exact command line."), T("permissions_process_placeholder", "Executable or command name")], threading: [T("permissions_threading_help_short", "Allow this plugin to create threads."), ""], events: [T("permissions_events_help", "Enter a category and event separated by a colon, such as Socket:socket.__new__."), T("permissions_events_placeholder", "Socket:socket.__new__")] }; diff --git a/src/slic3r/GUI/PluginsDialog.cpp b/src/slic3r/GUI/PluginsDialog.cpp index 9f023df0b4..5c4d1e951b 100644 --- a/src/slic3r/GUI/PluginsDialog.cpp +++ b/src/slic3r/GUI/PluginsDialog.cpp @@ -762,8 +762,8 @@ nlohmann::json PluginsDialog::localized_strings() const {"permissions_filesystem_placeholder", _u8L("/path/to/directory/*")}, #endif {"permissions_network_access_guidance", _u8L("Enter a full http:// or https:// URL; only its scheme and host are saved, so the grant covers every port, path, and query on that host. A network socket grant also accepts a bare host name or IP address, with or without a port, and covers every port on that host. Other schemes are not accepted. Grants in either list are checked for HTTP and socket access.")}, - {"permissions_process_help", _u8L("Enter the exact value recorded by the audit. It may be a Python representation of the command.")}, - {"permissions_process_placeholder", _u8L("Exact audited value")}, + {"permissions_process_help", _u8L("Executable grants cover all arguments. CommandLine: entries cover only the exact command line.")}, + {"permissions_process_placeholder", _u8L("Executable or command name")}, {"permissions_threading_help_short", _u8L("Allow this plugin to create threads.")}, {"permissions_events_help", _u8L("Enter a category and event separated by a colon, such as Socket:socket.__new__.")}, {"permissions_events_placeholder", _u8L("Socket:socket.__new__")}, diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index d04c0f2aaa..cf247043cc 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -177,7 +177,7 @@ static const std::unordered_set operation_root_events{ }; // True for the categories whose targets are filesystem paths, as opposed to a network -// address or a process command line -- the deny-path and allowed-root checks only make sense +// address or a process executable -- the deny-path and allowed-root checks only make sense // against a path. static bool is_fs_category(AuditEventCategory category) { @@ -1635,31 +1635,137 @@ static std::vector create_permission_targets(const std::string& eve return targets; } -static const std::unordered_map> audit_target_arg_indices{ - {"http.client.connect", {1}}, - {"urllib.Request", {0}}, +// Network events name their target directly: a host, an address tuple or a URL. +static const std::unordered_map network_target_arg_indices{ + {"http.client.connect", 1}, + {"urllib.Request", 0}, - {"socket.connect", {1}}, - {"socket.bind", {1}}, - {"socket.getaddrinfo", {0}}, - {"socket.gethostbyname", {0}}, - {"socket.gethostbyaddr", {0}}, - {"socket.getnameinfo", {0}}, - {"socket.getservbyname", {0}}, - {"socket.getservbyport", {0}}, - {"socket.sendto", {1}}, - {"socket.sendmsg", {1}}, + {"socket.connect", 1}, + {"socket.bind", 1}, + {"socket.getaddrinfo", 0}, + {"socket.gethostbyname", 0}, + {"socket.gethostbyaddr", 0}, + {"socket.getnameinfo", 0}, + {"socket.getservbyname", 0}, + {"socket.getservbyport", 0}, + {"socket.sendto", 1}, + {"socket.sendmsg", 1}, +}; - {"os.system", {0}}, - {"subprocess.Popen", {1, 0}}, - {"os.posix_spawn", {1, 0}}, - {"os.spawn", {2, 1}}, - {"os.startfile", {0}}, - {"os.startfile/2", {0}}, - {"pty.spawn", {0}}, - {"_winapi.CreateProcess", {1, 0}}, - {"_posixsubprocess.fork_exec", {0}}, - {"os.exec", {0}}, +// Process events each expose the executable in a different argument, and some pass the whole +// command line or argv. A grant normally names the tool only, so the arguments are dropped; the +// exception is a Windows command line whose executable is unquoted and followed by arguments +// (see windows_command_line_target). +enum class ProcessTargetFormat { + Path, // the argument is the executable path or name + FirstToken, // a command string or argv sequence: its first token or element + WindowsCommandLine, // a Windows command line: its first argument, possibly a quoted path +}; + +struct ProcessTargetSource { + Py_ssize_t index; + ProcessTargetFormat format; +}; + +// An exact-command entry shares the process list with executable entries. This reserved prefix +// keeps the two namespaces apart: an exact command line can never be mistaken for an executable +// name, and an existing executable grant (which does not carry the prefix) keeps its +// argument-insensitive meaning. It is stored in the sidecar and listed by the Plugins dialog; the +// permission prompt shows the command line without it. +static const std::string kWindowsCommandLineGrantPrefix = "CommandLine:"; + +static bool is_exact_command_grant(const std::string& target) +{ + return boost::algorithm::starts_with(target, kWindowsCommandLineGrantPrefix); +} + +static std::string exact_command_grant(const std::string& command_line) +{ + return kWindowsCommandLineGrantPrefix + command_line; +} + +// The prompt shows the command line the user is asked about, not the storage marker. +static std::string process_target_for_display(const std::string& target) +{ + return is_exact_command_grant(target) ? target.substr(kWindowsCommandLineGrantPrefix.size()) : target; +} + +// A process prompt can list executable grants and exact command lines together (a declaration may +// do so; a runtime event has one target). The wording must not claim argument-insensitive scope +// for an exact command line. +struct ProcessPromptScope { + bool exact_command = false; + bool executable = false; +}; + +static ProcessPromptScope process_prompt_scope(const std::vector& targets) +{ + ProcessPromptScope scope; + for (const std::string& target : targets) { + if (is_exact_command_grant(target)) + scope.exact_command = true; + else + scope.executable = true; + } + return scope; +} + +// os.system does not run a program named by its first token: it hands the whole string to the +// platform shell. POSIX passes it to /bin/sh. The Windows C runtime runs the command interpreter +// named by COMSPEC, or cmd.exe when COMSPEC is unset or empty, and also falls back to cmd.exe +// when it cannot open the configured file (ENOENT or EACCES). Either interpreter may therefore +// run the command, so every one of them is a required target: a narrow grant for a harmless +// COMSPEC target must not admit the fallback shell. Approving the shells covers every command +// string the plugin passes to os.system, because a shell parses and executes all of the string, +// arguments included. +// +// The runtime chooses the interpreter when it runs the command, so the audit names the possible +// interpreters instead of checking whether the COMSPEC file exists: a file that is present while +// the prompt is answered can be removed before the call. A COMSPEC that already is the bare name +// cmd.exe, in any casing, names the fallback itself and is listed once. +#ifdef _WIN32 +static std::vector system_shell_targets() +{ + constexpr const char* kFallbackShell = "cmd.exe"; + + // _wsystem reads COMSPEC through the CRT environment, which is the copy it consults; the + // process environment block can differ. Read the same value and copy it at once, because a + // concurrent _wputenv may replace the buffer the pointer names. + const wchar_t* const comspec_value = ::_wgetenv(L"COMSPEC"); + // An unset or empty COMSPEC leaves only the runtime's default interpreter. + if (comspec_value == nullptr || *comspec_value == L'\0') + return {kFallbackShell}; + + std::string comspec = wxString(comspec_value).utf8_string(); + // A bare cmd.exe is the fallback interpreter itself, whatever the casing, so one target stays. + if (comspec.find_first_of("/\\") == std::string::npos && + wxString::FromUTF8(comspec).CmpNoCase(wxString::FromUTF8(kFallbackShell)) == 0) + return {kFallbackShell}; + + return {std::move(comspec), kFallbackShell}; +} +#else +static std::vector system_shell_targets() +{ + return {"/bin/sh"}; +} +#endif + +static const std::unordered_map> process_target_sources{ + {"os.exec", {{0, ProcessTargetFormat::Path}}}, + {"os.posix_spawn", {{0, ProcessTargetFormat::Path}}}, + {"os.spawn", {{1, ProcessTargetFormat::Path}}}, + {"os.startfile", {{0, ProcessTargetFormat::Path}}}, + {"os.startfile/2", {{0, ProcessTargetFormat::Path}}}, + // executable is unresolved when the caller did not pass one, as on Windows, where args is + // then a single command line; on POSIX args is an argv sequence and executable is always set. + {"subprocess.Popen", {{0, ProcessTargetFormat::Path}, {1, ProcessTargetFormat::WindowsCommandLine}}}, + // application_name wins when it is given, so its source comes first; when it is omitted + // command_line is a Windows command line whose first argument names the executable. + {"_winapi.CreateProcess", {{0, ProcessTargetFormat::Path}, {1, ProcessTargetFormat::WindowsCommandLine}}}, + {"pty.spawn", {{0, ProcessTargetFormat::FirstToken}}}, + // The first argument is argv; its first element names the program. + {"_posixsubprocess.fork_exec", {{0, ProcessTargetFormat::FirstToken}}}, }; AuditEventCategory open_category(PyObject* args) @@ -1670,6 +1776,115 @@ AuditEventCategory open_category(PyObject* args) return AuditEventCategory::FsReadWrite; } +// The first token of a command string, or the first element of an argv sequence. A sequence +// element is kept whole, so an executable path may contain spaces. +std::string first_process_token(PyObject* object) +{ + if (!object) + return {}; + + std::string text; + if (python_text(object, text)) { + const size_t start = text.find_first_not_of(" \t\r\n"); + if (start == std::string::npos) + return {}; + const size_t end = text.find_first_of(" \t\r\n", start); + return text.substr(start, end == std::string::npos ? std::string::npos : end - start); + } + + if (!PySequence_Check(object)) + return python_path(object); + + PyObject* first = PySequence_GetItem(object, 0); // new reference + if (!first) { + PyErr_Clear(); + return {}; + } + std::string value = python_path(first); + Py_DECREF(first); + return value; +} + +// The grant target for a Windows command line. Windows does not split it like a POSIX shell: a +// path that contains spaces is enclosed in double quotes, and backslashes before a quote follow +// the CommandLineToArgvW rules (2n backslashes and a quote give n backslashes and end the +// argument, 2n+1 give n backslashes and a literal quote). +// +// A quoted first argument names the executable unambiguously and is returned alone, as is a +// command line that is only the executable: both keep the argument-insensitive executable grant. +// An unquoted first argument followed by more text is different. CreateProcess resolves it by +// trying successively longer prefixes of the name, so the first whitespace-delimited token need +// not be the executable it starts (the command line "C:\Program Files\app.exe --x" can start +// "C:\Program Files\app.exe", not "C:\Program"). Such a command line is returned as one exact +// grant instead, because granting the first token would describe a different program and would +// cover every later command line with that token. +std::string windows_command_line_target(const std::string& command_line) +{ + size_t index = command_line.find_first_not_of(" \t"); + if (index == std::string::npos) + return {}; + + if (command_line[index] != '"') { + const size_t end = command_line.find_first_of(" \t", index); + const size_t token_end = end == std::string::npos ? command_line.size() : end; + if (command_line.find_first_not_of(" \t", token_end) != std::string::npos) + return exact_command_grant(command_line.substr(index)); + return command_line.substr(index, token_end - index); + } + + std::string token; + ++index; // the opening quote is not part of the argument + while (index < command_line.size()) { + if (command_line[index] == '\\') { + size_t backslashes = 0; + while (index < command_line.size() && command_line[index] == '\\') { + ++backslashes; + ++index; + } + if (index < command_line.size() && command_line[index] == '"') { + token.append(backslashes / 2, '\\'); + if (backslashes % 2) { + token.push_back('"'); + ++index; + } else { + ++index; // the closing quote + break; + } + } else { + token.append(backslashes, '\\'); + } + continue; + } + if (command_line[index] == '"') { + ++index; // the closing quote + break; + } + token.push_back(command_line[index]); + ++index; + } + return token; +} + +std::string process_target(const ProcessTargetSource& source, PyObject* args) +{ + PyObject* const item = tuple_item(args, source.index); + if (!item || item == Py_None) + return {}; + switch (source.format) { + case ProcessTargetFormat::Path: + return python_path(item); + case ProcessTargetFormat::FirstToken: + return first_process_token(item); + case ProcessTargetFormat::WindowsCommandLine: { + std::string command_line; + if (python_text(item, command_line)) + return windows_command_line_target(command_line); + return first_process_token(item); + } + } + return {}; +} + std::vector audit_targets(const std::string& event_name, AuditEventCategory category, PyObject* args) { std::vector targets; @@ -1687,6 +1902,24 @@ std::vector audit_targets(const std::string& event_name, AuditEvent } return targets; } + case AuditEventCategory::ProcessCreate: + case AuditEventCategory::ProcessReplace: { + // The shells a command string may run in, not the command itself. Every possible + // interpreter has to be granted before the event is allowed. + if (event_name == "os.system") + return system_shell_targets(); + const auto it = process_target_sources.find(event_name); + if (it == process_target_sources.end()) + return targets; + for (const ProcessTargetSource& source : it->second) { + std::string value = process_target(source, args); + if (!value.empty()) { + targets.push_back(std::move(value)); + break; + } + } + return targets; + } case AuditEventCategory::Threading: // Thread creation exposes no user-supplied target. Use a fixed sentinel so the grant // persists per plugin: the permission list matches targets by exact string, and the @@ -1697,18 +1930,14 @@ std::vector audit_targets(const std::string& event_name, AuditEvent break; } - const auto it = audit_target_arg_indices.find(event_name); - if (it != audit_target_arg_indices.end()) { - for (const Py_ssize_t index : it->second) { - // None is an argument left out (sendmsg without an address), not a target named "None". - PyObject* const item = tuple_item(args, index); - if (item == Py_None) - continue; + const auto it = network_target_arg_indices.find(event_name); + if (it != network_target_arg_indices.end()) { + // None is an argument left out (sendmsg without an address), not a target named "None". + PyObject* const item = tuple_item(args, it->second); + if (item != Py_None) { std::string value = python_str(item); - if (!value.empty()) { + if (!value.empty()) targets.push_back(std::move(value)); - break; - } } } @@ -2369,7 +2598,8 @@ int report_denied(PluginAuditManager& mgr, wxString audit_message(AuditEventCategory category, const wxString& plugin_name, const wxString& event_name, const wxString& target_list, size_t target_count, bool full_fs_scope = false, - bool tree_scope = false, bool root_tree_scope = false) + bool tree_scope = false, bool root_tree_scope = false, bool exact_process_command = false, + bool executable_process_target = false) { // Create and delete grants name folders, and a declaration may ask for the whole filesystem // with a sole "*". Describe that scope instead of printing the marker as a folder. @@ -2509,13 +2739,43 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name, "Approval covers raw network connections to the listed hosts. It does not restrict ports."), plugin_name, target_list); case AuditEventCategory::ProcessCreate: - return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following command:\n%s", - "Plugin \"%s\" is requesting to run the following commands:\n%s", target_count), + // An exact command line is saved with its arguments rather than as a tool name, so the + // prompt must not promise that approval covers any arguments. The full line is stored, + // which can include credentials or tokens in its arguments. + if (exact_process_command && !executable_process_target) + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following exact command line:\n%s\n\n" + "Approval is saved for this exact command line, including its arguments, and covers " + "only it. A different command line, including different arguments, asks again. The " + "full command line is shown and saved, so it may contain sensitive values.", + "Plugin \"%s\" is requesting to run the following exact command lines:\n%s\n\n" + "Approval is saved for each exact command line, including its arguments, and covers " + "only that line. A different command line, including different arguments, asks again. " + "The full command lines are shown and saved, so they may contain sensitive values.", + target_count), + plugin_name, target_list); + if (exact_process_command) + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following commands:\n%s\n\n" + "Approval covers the listed executables with any arguments. A listed exact command " + "line is saved with its arguments and covers only that command line. Exact command " + "lines are shown and saved in full, so they may contain sensitive values. Approving a " + "shell allows it to run any command.", + "Plugin \"%s\" is requesting to run the following commands:\n%s\n\n" + "Approval covers the listed executables with any arguments. Each listed exact command " + "line is saved with its arguments and covers only that command line. Exact command " + "lines are shown and saved in full, so they may contain sensitive values. Approving a " + "shell allows it to run any command.", + target_count), + plugin_name, target_list); + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following command:\n%s\n\n" + "Approval covers any arguments. Approving a shell allows it to run any command.", + "Plugin \"%s\" is requesting to run the following commands:\n%s\n\n" + "Approval covers any arguments. Approving a shell allows it to run any command.", target_count), plugin_name, target_list); case AuditEventCategory::Threading: return wxString::Format(_L("Plugin \"%s\" is requesting permission to create a thread."), plugin_name); case AuditEventCategory::ProcessReplace: - return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s"), plugin_name, target_list); + return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s\n\n" + "Approval covers any arguments. Approving a shell allows it to run any command."), plugin_name, target_list); default: return wxString::Format(_L("Plugin \"%s\" is requesting permission for the Python audit event \"%s\"."), plugin_name, event_name); } @@ -2525,17 +2785,19 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name, PermissionMessage formatted_audit_message(AuditEventCategory category, const wxString& plugin_name, const wxString& event_name, const wxString& targets, size_t count, bool full_fs_scope = false, bool tree_scope = false, - bool root_tree_scope = false) + bool root_tree_scope = false, bool exact_process_command = false, + bool executable_process_target = false) { if (targets.empty()) return {audit_message(category, plugin_name, event_name, targets, count, full_fs_scope, tree_scope, - root_tree_scope), {}}; + root_tree_scope, exact_process_command, executable_process_target), {}}; wxString marker = "__ORCA_PERMISSION_TARGETS__"; while (plugin_name.Contains(marker) || event_name.Contains(marker) || targets.Contains(marker)) marker += "_"; PermissionMessage message{ - audit_message(category, plugin_name, event_name, marker, count, full_fs_scope, tree_scope, root_tree_scope), {}}; + audit_message(category, plugin_name, event_name, marker, count, full_fs_scope, tree_scope, root_tree_scope, + exact_process_command, executable_process_target), {}}; const size_t pos = message.text.find(marker); if (pos != wxString::npos) { message.text.replace(pos, marker.length(), targets); @@ -2620,9 +2882,16 @@ bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_n return show_permission_dialog(message, _L("Plugin permission request")); } + const bool process_category = + category == AuditEventCategory::ProcessCreate || category == AuditEventCategory::ProcessReplace; + const ProcessPromptScope process_scope = + process_category ? process_prompt_scope(unresolved) : ProcessPromptScope{}; + wxString target_list; - for (const auto& target : unresolved) - target_list += wxString::FromUTF8(target.c_str()) + "\n"; + for (const auto& target : unresolved) { + const std::string shown = process_category ? process_target_for_display(target) : target; + target_list += wxString::FromUTF8(shown.c_str()) + "\n"; + } const bool tree_scope = std::any_of(unresolved.begin(), unresolved.end(), [](const std::string& target) { boost::filesystem::path root; @@ -2632,7 +2901,8 @@ bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_n PermissionMessage message = formatted_audit_message(category, wxString::FromUTF8(plugin_name.c_str()), wxString::FromUTF8(event_name.c_str()), target_list, unresolved.size(), /*full_fs_scope=*/false, tree_scope, - /*root_tree_scope=*/false); + /*root_tree_scope=*/false, process_scope.exact_command, + process_scope.executable); return show_permission_dialog(message, _L("Plugin permission request")); } @@ -2664,16 +2934,24 @@ PermissionMessage build_permission_message(const std::string& plugin_name, const return tree_grant_root(target, root) && is_filesystem_root(root); }); + const bool process_category = + bucket.category == AuditEventCategory::ProcessCreate || bucket.category == AuditEventCategory::ProcessReplace; + const ProcessPromptScope process_scope = + process_category ? process_prompt_scope(bucket.targets) : ProcessPromptScope{}; + wxString targets; if (!full_fs_scope) - for (const std::string& target : bucket.targets) - targets += wxString::FromUTF8(target.c_str()) + "\n"; + for (const std::string& target : bucket.targets) { + const std::string shown = process_category ? process_target_for_display(target) : target; + targets += wxString::FromUTF8(shown.c_str()) + "\n"; + } if (!message.text.IsEmpty()) message.text += "\n\n"; PermissionMessage part = formatted_audit_message(bucket.category, wxString::FromUTF8(plugin_name.c_str()), wxEmptyString, targets, bucket.targets.size(), - full_fs_scope, tree_scope, root_tree_scope); + full_fs_scope, tree_scope, root_tree_scope, + process_scope.exact_command, process_scope.executable); for (const auto& range : part.targets) message.targets.emplace_back(message.text.length() + range.first, range.second); message.text += part.text; diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index 5845aa3acf..add3887a2a 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -39,6 +39,8 @@ struct PluginPermissions std::vector fs_delete; std::vector network_http; std::vector network_socket; + // Executables or command names. Arguments are ignored, so one entry covers every call of + // the tool. std::vector process; // Thread creation is a yes/no grant. Newer sidecars store a boolean; older ones stored an // array (empty when denied, nonempty when granted), and nonempty strings are accepted by the diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index 050a60a285..86ab02b0d6 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -663,8 +663,8 @@ void bind_python_api(pybind11::module_& m) Each bucket takes the target strings the plugin expects the corresponding audit event to report: filesystem paths for fs_read and fs_readwrite, URLs for network_http, socket addresses -for network_socket, and commands for process. threading=True requests permission to start -threads. Targets already granted to the plugin are not asked for again. +for network_socket, and executables or command names for process. threading=True requests +permission to start threads. Targets already granted to the plugin are not asked for again. fs_create and fs_delete take folders rather than files. A literal folder entry grants creating or deleting entries directly inside that folder, not inside its subfolders. An entry ending in diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index 98b3c2e05a..a295230db3 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -1432,6 +1432,17 @@ PRIVATE = os.path.join(OUTSIDE, "private.txt") MISSING = os.path.join(OUTSIDE, "missing") TREE = os.path.join(OUTSIDE, "tree") TRUE_COMMAND = ["cmd", "/c", "exit 0"] if os.name == "nt" else ["true"] + +# The shells os.system may run a command in. On Windows the runtime uses COMSPEC or cmd.exe, +# and falls back to cmd.exe when COMSPEC names a file it cannot open, so both are targets. A +# bare cmd.exe COMSPEC is the fallback itself. +if os.name != "nt": + SYSTEM_SHELLS = ["/bin/sh"] +else: + COMSPEC = os.environ.get("COMSPEC") or "" + SYSTEM_SHELLS = (["cmd.exe"] if not COMSPEC or + ("/" not in COMSPEC and "\\" not in COMSPEC and COMSPEC.lower() == "cmd.exe") + else [COMSPEC, "cmd.exe"]) for path in (APPROVED, PRIVATE): with open(path, "w") as f: f.write("x") @@ -1525,6 +1536,23 @@ std::string describe(const std::vector& prompts) return text; } +// The line describe() prints for an os.system prompt, whose target is every possible shell. +std::string describe_system_prompt(const std::vector& shells) +{ + std::string text = "os.system:"; + for (const std::string& shell : shells) + text += " " + shell; + return text + "\n"; +} + +// The process grants a successful os.system approval adds to the ones already saved. +std::vector with_shell_grants(std::vector grants, + const std::vector& shells) +{ + grants.insert(grants.end(), shells.begin(), shells.end()); + return grants; +} + // The plugin system with the audit hook installed, and the permission dialog replaced by a // recorder that answers with `approve`. Declare it first in a test, so it is destroyed last. // @@ -1863,10 +1891,11 @@ TEST_CASE("A freshly approved operation covers its nested events", "[audit][Pyth const char* prompts; const char* code; }; - // Each case starts with no saved grants, so its root event is asked once. A freshly approved - // create or delete saves the parent folder, so the stored grants are reset between cases. - // Only the expected prompts are approved, so a nested event left uncovered fails the - // operation. + // Each case starts with no saved grants, so its root event is asked once; a freshly approved + // create or delete saves the parent folder, so the stored grants are reset between cases. A + // process grant names the executable, so pty.spawn's own approval covers the exec in the + // forked child. Only the expected prompts are approved, so a nested event left uncovered + // fails the operation. std::vector cases = { {"shutil.copytree", "shutil.copytree(TREE, os.path.join(OUTSIDE, 'copy'))"}, {"shutil.copyfile", "shutil.copyfile(APPROVED, os.path.join(OUTSIDE, 'copied.txt'))"}, @@ -2027,7 +2056,7 @@ fd_outcomes = [attempt(lambda: open(READ_FD, "r", closefd=False).close()), CHECK(describe(harness.prompts) == "open:\nopen:\n"); CHECK(harness.saved_permissions(PLUGIN).events == std::vector{"FsRead:open"}); - // A saved os.fork event grant is not an os.system command named "os.fork". + // A saved os.fork event grant is not the shell os.system runs. PluginPermissions permissions; permissions.events = {"FsRead:open", "ProcessCreate:os.fork"}; harness.save_permissions(PLUGIN, permissions); @@ -2045,6 +2074,377 @@ os.close(WRITE_FD) CHECK(harness.saved_permissions(PLUGIN).process.empty()); } +TEST_CASE("A process grant names the executable, or the exact Windows command line", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + const std::vector shells = python.strings("SYSTEM_SHELLS"); +#ifdef _WIN32 + // subprocess.run() joins argv into one command line before the audit event. Its executable + // "cmd" is unquoted and followed by arguments, so the documented grant keeps the whole exact + // line instead of the first token. + const std::string popen_target = R"(CommandLine:cmd /c "exit 0")"; +#else + // POSIX keeps the executable in its own argv element, so only the executable is granted. + const std::string popen_target = python.eval("TRUE_COMMAND[0]"); +#endif + + // Refused, so nothing runs: the prompts show the target each event reports. A direct process + // event names the executable, except a Windows command line whose unquoted executable is + // followed by arguments, which is the exact command line. os.system names every shell that may + // parse its command string. + python.run_as(PLUGIN, R"PY( +popen_outcome = attempt(lambda: subprocess.run(TRUE_COMMAND, check=True)) +system_outcome = attempt(lambda: os.system(" ".join(TRUE_COMMAND) + " ignored")) +)PY"); + CHECK(python.str("popen_outcome") == "denied"); + CHECK(python.str("system_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: " + popen_target + "\n" + describe_system_prompt(shells)); + +#ifndef _WIN32 + harness.prompts.clear(); + python.run_as(PLUGIN, "spawn_outcome = attempt(lambda: spawn_checked(TRUE_COMMAND + ['spawned']))"); + CHECK(python.str("spawn_outcome") == "denied"); + CHECK(describe(harness.prompts) == "pty.spawn: " + popen_target + "\n"); +#endif + + // Approving the direct process event grants its target alone: on Windows the exact command + // line, elsewhere the executable. The approval also opens an operation frame that covers the + // runtime's nested CreateProcess event, so the run asks once. Neither target is a shell grant, + // so a later os.system is asked for on its own. + harness.approve = [](const Prompt&) { return true; }; + harness.prompts.clear(); + python.run_as(PLUGIN, "popen_outcome = attempt(lambda: subprocess.run(TRUE_COMMAND, check=True))"); + CHECK(python.str("popen_outcome") == "ok"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == std::vector{popen_target}); + CHECK(harness.saved_permissions(PLUGIN).process == std::vector{popen_target}); + + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +system_outcome = attempt(lambda: os.system(" ".join(TRUE_COMMAND) + " ignored")) +)PY"); + CHECK(python.str("system_outcome") == "ok"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == shells); + CHECK(harness.saved_permissions(PLUGIN).process == + with_shell_grants({popen_target}, shells)); + + // The shell grant covers a different command string, arguments included. + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +repeat_outcome = attempt(lambda: os.system(" ".join(TRUE_COMMAND) + " another argument")) +)PY"); + CHECK(python.str("repeat_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A subprocess grant names the executable from a Windows command line", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // The event Windows subprocess.Popen raises: the executable is unresolved unless the caller + // passed one, and the arguments are a single command line. Raising it directly checks the + // target the hook reads without creating a process. + python.run_as(PLUGIN, R"PY( +def raise_popen(executable, command_line): + try: + sys.audit("subprocess.Popen", executable, command_line, None, None) + return "ok" + except PermissionError: + return "denied" + +quoted_outcome = raise_popen(None, r'"C:\Program Files\Tool\tool.exe" --flag') +explicit_outcome = raise_popen(r"D:\other\tool.exe", r'"C:\Program Files\Tool\tool.exe" --flag') +unquoted_outcome = raise_popen(None, r"plain-tool.exe --flag") +)PY"); + CHECK(python.str("quoted_outcome") == "denied"); + CHECK(python.str("explicit_outcome") == "denied"); + CHECK(python.str("unquoted_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: C:\\Program Files\\Tool\\tool.exe\n" + "subprocess.Popen: D:\\other\\tool.exe\n" + "subprocess.Popen: CommandLine:plain-tool.exe --flag\n"); +} + +TEST_CASE("An unquoted Windows command line is granted as one exact command", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // An existing executable grant for the first token must not authorize the longer executable + // that CreateProcess may resolve from an unquoted command line. + PluginPermissions legacy; + legacy.process = {R"(C:\Program)"}; + harness.save_permissions(PLUGIN, legacy); + + python.run_as(PLUGIN, R"PY( +def raise_popen(executable, command_line): + try: + sys.audit("subprocess.Popen", executable, command_line, None, None) + return "ok" + except PermissionError: + return "denied" + +tool_a_one = r"C:\Program Files\ToolA\a.exe --one" +)PY"); + + // The legacy C:\Program grant is the first token of ToolA, but the command line is asked for + // as one exact command instead. + python.run_as(PLUGIN, R"PY( +denied_outcome = raise_popen(None, tool_a_one) +)PY"); + CHECK(python.str("denied_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: CommandLine:C:\\Program Files\\ToolA\\a.exe --one\n"); + CHECK(harness.saved_permissions(PLUGIN).process == std::vector{R"(C:\Program)"}); + + // Approving saves that exact command line beside the unrelated legacy grant. + harness.approve = [](const Prompt& prompt) { + return prompt.targets == + std::vector{R"(CommandLine:C:\Program Files\ToolA\a.exe --one)"}; + }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +approved_outcome = raise_popen(None, tool_a_one) +)PY"); + CHECK(python.str("approved_outcome") == "ok"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: CommandLine:C:\\Program Files\\ToolA\\a.exe --one\n"); + CHECK(harness.saved_permissions(PLUGIN).process == + std::vector{R"(C:\Program)", R"(CommandLine:C:\Program Files\ToolA\a.exe --one)"}); + + // The same exact command line reuses the saved exact grant. + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +repeat_outcome = raise_popen(None, tool_a_one) +)PY"); + CHECK(python.str("repeat_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + + // The saved exact grant covers neither changed arguments nor the same arguments on another + // executable, and the legacy C:\Program grant does not cover either exact command line. + harness.approve = [](const Prompt&) { return false; }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +changed_arguments_outcome = raise_popen(None, r"C:\Program Files\ToolA\a.exe --two") +other_executable_outcome = raise_popen(None, r"C:\Program Files\ToolB\b.exe --one") +)PY"); + CHECK(python.str("changed_arguments_outcome") == "denied"); + CHECK(python.str("other_executable_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "subprocess.Popen: CommandLine:C:\\Program Files\\ToolA\\a.exe --two\n" + "subprocess.Popen: CommandLine:C:\\Program Files\\ToolB\\b.exe --one\n"); + + // A quoted executable and an explicit executable remain argument-insensitive grants. + PluginPermissions permissions; + permissions.process = {R"(C:\Program Files\Tool\tool.exe)", R"(D:\other\tool.exe)"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +quoted_outcome = raise_popen(None, r'"C:\Program Files\Tool\tool.exe" --changed') +explicit_outcome = raise_popen(r"D:\other\tool.exe", r'"C:\Program Files\Tool\tool.exe" --changed') +)PY"); + CHECK(python.str("quoted_outcome") == "ok"); + CHECK(python.str("explicit_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A Windows command line grant names one quoted executable, not another path", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // The event _winapi.CreateProcess raises, with application_name left out as it may be, so no + // process is created. The quoted paths contain spaces, which a whitespace split would cut. + python.run_as(PLUGIN, R"PY( +def raise_create_process(application_name, command_line): + try: + sys.audit("_winapi.CreateProcess", application_name, command_line, None) + return "ok" + except PermissionError: + return "denied" + +first_outcome = raise_create_process(None, r'"C:\Program Files\ToolA\a.exe" --one') +other_outcome = raise_create_process(None, r'"C:\Program Files\ToolB\b.exe" --one') +explicit_outcome = raise_create_process(r"D:\tools\other.exe", r'"C:\Program Files\ToolA\a.exe" --one') +)PY"); + CHECK(python.str("first_outcome") == "denied"); + CHECK(python.str("other_outcome") == "denied"); + CHECK(python.str("explicit_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "_winapi.CreateProcess: C:\\Program Files\\ToolA\\a.exe\n" + "_winapi.CreateProcess: C:\\Program Files\\ToolB\\b.exe\n" + "_winapi.CreateProcess: D:\\tools\\other.exe\n"); + + // A grant for one quoted path covers that executable with other arguments, never another path. + harness.approve = [](const Prompt& prompt) { + return prompt.targets == std::vector{R"(C:\Program Files\ToolA\a.exe)"}; + }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +repeat_outcome = raise_create_process(None, r'"C:\Program Files\ToolA\a.exe" --two') +distinct_outcome = raise_create_process(None, r'"C:\Program Files\ToolB\b.exe" --one') +)PY"); + CHECK(python.str("repeat_outcome") == "ok"); + CHECK(python.str("distinct_outcome") == "denied"); + CHECK(describe(harness.prompts) == + "_winapi.CreateProcess: C:\\Program Files\\ToolA\\a.exe\n" + "_winapi.CreateProcess: C:\\Program Files\\ToolB\\b.exe\n"); + CHECK(harness.saved_permissions(PLUGIN).process == + std::vector{R"(C:\Program Files\ToolA\a.exe)"}); + + // The saved grant covers the same executable again, still without spanning to ToolB. + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +saved_outcome = raise_create_process(None, r'"C:\Program Files\ToolA\a.exe" --three') +other_saved_outcome = raise_create_process(None, r'"C:\Program Files\ToolB\b.exe" --two') +)PY"); + CHECK(python.str("saved_outcome") == "ok"); + CHECK(python.str("other_saved_outcome") == "denied"); + CHECK(describe(harness.prompts) == "_winapi.CreateProcess: C:\\Program Files\\ToolB\\b.exe\n"); +} + +TEST_CASE("An os.system grant names the shell and covers every command", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + const std::vector shells = python.strings("SYSTEM_SHELLS"); + + // Raising the event directly exercises the targets the hook reads without running the command. + // The grants name the shells, not the command string's first token, on every platform. + python.run_as(PLUGIN, R"PY( +def raise_system(command): + try: + sys.audit("os.system", command) + return "ok" + except PermissionError: + return "denied" + +plain_outcome = raise_system("plain-tool --one") +quoted_outcome = raise_system(r'"C:\Program Files\ToolA\a.exe" --one') +other_outcome = raise_system("other-tool") +)PY"); + CHECK(python.str("plain_outcome") == "denied"); + CHECK(python.str("quoted_outcome") == "denied"); + CHECK(python.str("other_outcome") == "denied"); + CHECK(describe(harness.prompts) == + describe_system_prompt(shells) + describe_system_prompt(shells) + describe_system_prompt(shells)); + + // Approving the shells covers every command string, arguments included. + harness.approve = [](const Prompt&) { return true; }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +repeat_outcome = raise_system("plain-tool --two") +)PY"); + CHECK(python.str("repeat_outcome") == "ok"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == shells); + CHECK(harness.saved_permissions(PLUGIN).process == shells); + + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +quoted_repeat_outcome = raise_system(r'"C:\Program Files\ToolB\b.exe" --flag') +other_repeat_outcome = raise_system("third-tool --three") +)PY"); + CHECK(python.str("quoted_repeat_outcome") == "ok"); + CHECK(python.str("other_repeat_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +} + +#ifdef _WIN32 +TEST_CASE("An os.system grant for COMSPEC alone does not authorize the fallback shell", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // Pin the configured interpreter, so the case does not depend on the machine's COMSPEC. + python.run_as(PLUGIN, R"PY( +saved_comspec = os.environ.get("COMSPEC") +NARROW_SHELL = r"C:\narrow\narrow-shell.exe" +os.environ["COMSPEC"] = NARROW_SHELL + +def raise_system(command): + try: + sys.audit("os.system", command) + return "ok" + except PermissionError: + return "denied" +)PY"); + const std::string narrow_shell = python.str("NARROW_SHELL"); + const std::vector both_shells{narrow_shell, "cmd.exe"}; + + // The runtime falls back to cmd.exe when it cannot open COMSPEC, so the configured + // interpreter's grant alone leaves the event unresolved by the fallback shell. + PluginPermissions permissions; + permissions.process = {narrow_shell}; + harness.save_permissions(PLUGIN, permissions); + python.run_as(PLUGIN, "narrow_outcome = raise_system('anything')"); + CHECK(python.str("narrow_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.system: cmd.exe\n"); + CHECK(harness.saved_permissions(PLUGIN).process == std::vector{narrow_shell}); + + // One approval saves the missing fallback interpreter, so the next run does not ask again. + harness.approve = [](const Prompt&) { return true; }; + harness.prompts.clear(); + python.run_as(PLUGIN, "approved_outcome = raise_system('anything')"); + CHECK(python.str("approved_outcome") == "ok"); + CHECK(harness.prompts.size() == 1); + if (harness.prompts.size() == 1) + CHECK(harness.prompts.front().targets == std::vector{"cmd.exe"}); + CHECK(harness.saved_permissions(PLUGIN).process == both_shells); + + harness.prompts.clear(); + python.run_as(PLUGIN, "repeat_outcome = raise_system('anything else')"); + CHECK(python.str("repeat_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + + // A COMSPEC that is the bare fallback name names one interpreter, whatever its casing. + harness.save_permissions(PLUGIN, {}); + harness.approve = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, R"PY( +os.environ["COMSPEC"] = "CmD.eXe" +bare_outcome = raise_system("anything") +)PY"); + CHECK(python.str("bare_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.system: cmd.exe\n"); + CHECK(harness.saved_permissions(PLUGIN).process.empty()); + + python.run_as(PLUGIN, R"PY( +if saved_comspec is None: + os.environ.pop("COMSPEC", None) +else: + os.environ["COMSPEC"] = saved_comspec +)PY"); +} +#endif + TEST_CASE("A finalizer run when a root frame is let go is judged as the plugin without a prompt", "[audit][Python]") { AuditHarness harness; From a53663cddf31bd2041f04cd06a810c2b99bc33ad Mon Sep 17 00:00:00 2001 From: Rodrigo Faselli <162915171+RF47@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:21:25 -0300 Subject: [PATCH 12/36] Patch Boost.Locale to configure with CMake 4.5 (#17725) --- deps/Boost/Boost.cmake | 2 ++ deps/Boost/fix_locale_source_group.cmake | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 deps/Boost/fix_locale_source_group.cmake diff --git a/deps/Boost/Boost.cmake b/deps/Boost/Boost.cmake index 1526928094..80d0620a41 100644 --- a/deps/Boost/Boost.cmake +++ b/deps/Boost/Boost.cmake @@ -43,6 +43,8 @@ orcaslicer_add_cmake_project(Boost URL "https://github.com/boostorg/boost/releases/download/boost-1.84.0/boost-1.84.0.tar.gz" URL_HASH SHA256=4d27e9efed0f6f152dc28db6430b9d3dfb40c0345da7342eaa5a987dde57bd95 LIST_SEPARATOR | + # Lets Boost.Locale configure with CMake 4.5; see the script. + PATCH_COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR= -P ${CMAKE_CURRENT_LIST_DIR}/fix_locale_source_group.cmake CMAKE_ARGS -DBOOST_EXCLUDE_LIBRARIES:STRING=contract|fiber|numpy|stacktrace|wave|test -DBOOST_LOCALE_ENABLE_ICU:BOOL=OFF # do not link to libicu, breaks compatibility between distros diff --git a/deps/Boost/fix_locale_source_group.cmake b/deps/Boost/fix_locale_source_group.cmake new file mode 100644 index 0000000000..56f9b401e8 --- /dev/null +++ b/deps/Boost/fix_locale_source_group.cmake @@ -0,0 +1,21 @@ +# Boost.Locale lists include/boost/locale.hpp in a source_group(TREE) rooted at include/boost/locale. +# Before 4.5, CMake compared the two as strings and accepted it. CMake 4.5 reworked source_group() and +# compares path components, so it stops the configure with "is not a prefix of file". locale.hpp gets its own group on the +# following line of that file, so only the headers under include/boost/locale/ go into the tree. +# +# Run as the PATCH_COMMAND with -DSOURCE_DIR=. A second run leaves the file as it is. +set(_file "${SOURCE_DIR}/libs/locale/CMakeLists.txt") +set(_old [[list(FILTER sources_inc EXCLUDE REGEX "^src/")]]) +set(_new [[list(FILTER sources_inc INCLUDE REGEX "^include/boost/locale/")]]) + +file(READ "${_file}" _content) +string(FIND "${_content}" "${_new}" _patched) +if (_patched EQUAL -1) + string(FIND "${_content}" "${_old}" _found) + if (_found EQUAL -1) + message(FATAL_ERROR "${_file} no longer has the line this script replaces. Check whether this Boost " + "version still needs deps/Boost/fix_locale_source_group.cmake.") + endif () + string(REPLACE "${_old}" "${_new}" _content "${_content}") + file(WRITE "${_file}" "${_content}") +endif () From 8db30fdb30098d441803adeb37f3feb4039f4207 Mon Sep 17 00:00:00 2001 From: Noisyfox Date: Fri, 20 Nov 2026 10:53:54 +0800 Subject: [PATCH 13/36] Fix Expat MSVC builds with UTF-8 source encoding (#17596) Expat 2.10.0 has UTF-8 quotes in a comment in random_rand_s.c. cl.exe reads source files in the system code page, so on code page 936 it reads the line break as part of a double-byte character. The next line becomes part of the comment and the build fails with C1020. Pass /utf-8 to Expat's C compiler when building with MSVC, keeping the existing C flags. --- deps/EXPAT/EXPAT.cmake | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/deps/EXPAT/EXPAT.cmake b/deps/EXPAT/EXPAT.cmake index 004318a51b..08a3c6668b 100644 --- a/deps/EXPAT/EXPAT.cmake +++ b/deps/EXPAT/EXPAT.cmake @@ -2,10 +2,18 @@ # the parser must not come from a distro or SDK copy that may predate it. # XML_DTD and XML_GE are passed explicitly: 2.4.0 gated the guard behind XML_DTD # and 2.6.0 behind XML_GE, so neither may be left to the default. +set(_expat_c_flags_line "") +if (MSVC) + # UTF-8 quotes in random_rand_s.c comments can swallow a preprocessor line + # when MSVC reads the source using the system's legacy code page. + set(_expat_c_flags_line "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} /utf-8") +endif () + orcaslicer_add_cmake_project(EXPAT URL https://github.com/libexpat/libexpat/releases/download/R_2_10_0/expat-2.10.0.tar.gz URL_HASH SHA256=5466a341f9c692ef7a958a6881311be597f8e1ce345984cf78414f54793dea4c CMAKE_ARGS + "${_expat_c_flags_line}" -DBUILD_SHARED_LIBS=OFF -DEXPAT_SHARED_LIBS=OFF -DEXPAT_DTD=ON From 3efe401d8e14b409490170d1021fa3db1bd26cc1 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:50:36 +0800 Subject: [PATCH 14/36] Give the Section View's Cut Face the Infill Colour in the Solid Model (#17701) The solid model capped the section view's cut with the body's wall colour, while the two layer caps already took the infill's. The section cap now takes the infill colour sampled over every layer the solid stands for, as the body takes the wall colour, falling back to the body's colour where a body has no infill. Views that colour by filament are unchanged. --- docs/HLSD/gcode-preview-dragging.md | 6 ++++-- src/slic3r/GUI/GCodeViewer.cpp | 31 ++++++++++++++++++----------- src/slic3r/GUI/GCodeViewer.hpp | 8 ++++---- 3 files changed, 27 insertions(+), 18 deletions(-) diff --git a/docs/HLSD/gcode-preview-dragging.md b/docs/HLSD/gcode-preview-dragging.md index b3ee633f36..17fe9106c8 100644 --- a/docs/HLSD/gcode-preview-dragging.md +++ b/docs/HLSD/gcode-preview-dragging.md @@ -101,7 +101,7 @@ The solid stands in for the toolpaths, so it wears their colours. In the views t filament (Summary, Filament, Tool) each body keeps the filament colour its shell was loaded with. In every other view `GCodeViewer::update_solid_model_colors()` samples the toolpaths through `Viewer::get_vertex_color()`: the body takes the outer wall's colour over the layers the solid -stands for, each cap the infill's in the layer it is cut under, sparse infill before solid, and +stands for, each layer cap the infill's in the layer it is cut under, sparse infill before solid, and the prime tower its own role's. One vertex stands for the role, chosen by `Viewer::find_extrusion_vertex()`: in a view that grades the toolpaths by a value, the length-weighted median of that value over the role's extrusions in up to eight layers spread over @@ -116,7 +116,9 @@ the ends of the layer range then do not bound. And so does a belt printer's: its tilted at the belt angle, with heights in the G-code's frame, which no horizontal cut follows. A section view cuts the solid by its plane as it cuts the toolpaths, and the section face is one -more cap, counted on the body cut by that plane alone and drawn between the two heights. +more cap, counted on the body cut by that plane alone and drawn between the two heights. It may +cross any of the layers the solid stands for, so its colour is the infill's sampled over all of +them, as the body's is, or the body's own where the body has no infill. The solid is drawn opaque whatever the filaments' alpha: a translucent filament shows its toolpaths inside through the walls at rest, and the solid has no inside to show. diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index 15cb3230a8..e72c7f1720 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -3824,6 +3824,7 @@ void GCodeViewer::init_solid_model_caps(const std::array& z_range, std init_quad(cap, on_plane, reach * u, reach * v); cap.count_plane = m_clipping_plane; cap.quad_z_range = { z_bottom, z_top }; + cap.color_index = 2; } } @@ -3968,17 +3969,18 @@ void GCodeViewer::render_solid_model(int canvas_width, int canvas_height) } } -// The solid stands in for the toolpaths, so it takes their colours in the view that colours them -// by something other than the filament: each body the outer wall's, each cap the infill's of the -// layer it is cut under, sparse if the layer has any, else solid, and the tower its own role's, -// each from the toolpaths within the body's own footprint, so that objects printed at different -// grades keep their own. The views that colour by filament leave every body its own colour. The -// bodies are sampled over the layers the solid stands for and each cap in its own layer, each -// colour that of the vertex the viewer picks to represent the role there, so a view that grades -// the toolpaths, by speed or fan, shows the solid in the grade most of that role was printed at. -// The bodies are sampled once, as the drag begins, and held while a slider drag moves the span: -// sampled again at every step, the grade would flip with the layers the sample happens to fall -// on. Each cap follows its own layer. +// The solid stands in for the toolpaths, so it takes their colours in the view that colours them by +// something other than the filament: each body the outer wall's, each layer cap the infill's of the +// layer it is cut under, sparse if the layer has any, else solid, the section view's cap the +// infill's over all the layers, and the tower its own role's, each from the toolpaths within the +// body's own footprint, so that objects printed at different grades keep their own. The views that +// colour by filament leave every body its own colour. The bodies and the section view's cap are +// sampled over the layers the solid stands for and each layer cap in its own layer, each colour +// that of the vertex the viewer picks to represent the role there, so a view that grades the +// toolpaths, by speed or fan, shows the solid in the grade most of that role was printed at. The +// bodies are sampled once, as the drag begins, and held while a slider drag moves the span: sampled +// again at every step, the grade would flip with the layers the sample happens to fall on. The +// section view's cap is held with them; each layer cap follows its own layer. void GCodeViewer::update_solid_model_colors(const libvgcode::Interval& whole_layers) { SolidModelColors& colors = m_solid_model_colors; @@ -4019,8 +4021,13 @@ void GCodeViewer::update_solid_model_colors(const libvgcode::Interval& whole_lay const libvgcode::XYBox box{ { static_cast(footprint.min.x()) - margin, static_cast(footprint.min.y()) - margin }, { static_cast(footprint.max.x()) + margin, static_cast(footprint.max.y()) + margin } }; SolidModelColors::Body& body = colors.bodies[n]; - if (!held) + if (!held) { body.body = sample(whole_layers, tower ? tower_role : walls, box); + // the section view's cut may cross any of the layers, so it is sampled over all of them, as the body is + body.caps[2] = tower ? std::nullopt : sample(whole_layers, infill, box); + if (!body.caps[2].has_value()) + body.caps[2] = body.body; + } for (size_t k = 0; k < 2; ++k) { body.caps[k] = tower ? std::nullopt : sample({ whole_layers[k], whole_layers[k] }, infill, box); if (!body.caps[k].has_value()) diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index 1ecdb72e97..284c984c44 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -354,10 +354,10 @@ private: // the quad, cut by the other caps std::array quad_z_range{ -FLT_MAX, FLT_MAX }; std::array quad_plane{ 0.0f, 0.0f, 0.0f, 1.0f }; - // which of the sampled cap colours it takes, none for the body's own + // which of the sampled cap colours it takes std::optional color_index; }; - // the bottom cap, then the top one, as the colours are indexed, then the section view's; a cap + // the bottom cap, then the top one, then the section view's, as the colours are indexed; a cap // the solid is not cut at is left without a quad void init_solid_model_caps(const std::array& z_range, std::array& caps) const; void release_caster_depth(); @@ -392,8 +392,8 @@ private: { // unset where the view colours by filament, or no vertex of the role was found there std::optional body; - // the bottom and top caps - std::array, 2> caps; + // the bottom and top caps, then the section view's, sampled over every layer of the solid + std::array, 3> caps; }; std::vector bodies; }; From 9d6ba7eae28c5266fc7a2615ae582c8d82eed380 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:52:04 +0800 Subject: [PATCH 15/36] Keep Tree Hybrid's Expanded First Layer on the Bed (#17700) --- src/libslic3r/Support/TreeSupport.cpp | 2 +- tests/fff_print/test_tree_support.cpp | 46 +++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/libslic3r/Support/TreeSupport.cpp b/src/libslic3r/Support/TreeSupport.cpp index d51539b717..9bd6fca9bc 100644 --- a/src/libslic3r/Support/TreeSupport.cpp +++ b/src/libslic3r/Support/TreeSupport.cpp @@ -2582,7 +2582,7 @@ void TreeSupport::draw_circles() } else expanded_base_areas.emplace_back(expoly); } - ts_layer->base_areas = std::move(expanded_base_areas); + ts_layer->base_areas = intersection_ex(expanded_base_areas, m_machine_border); } // Orca: Final tree base polygons may be too close above model surfaces. diff --git a/tests/fff_print/test_tree_support.cpp b/tests/fff_print/test_tree_support.cpp index 8823baf184..a2b324720d 100644 --- a/tests/fff_print/test_tree_support.cpp +++ b/tests/fff_print/test_tree_support.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include "libslic3r/Config.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Point.hpp" @@ -20,6 +22,7 @@ #include "test_helpers.hpp" #include "libslic3r/ExtrusionEntity.hpp" #include "libslic3r/ExtrusionEntityCollection.hpp" +#include "libslic3r/Model.hpp" #include "libslic3r/Print.hpp" using namespace Slic3r::Test; @@ -339,3 +342,46 @@ TEST_CASE("Tree support reaches every overhang that joins a cluster on the same REQUIRE(2 * under_front > under_back); REQUIRE(2 * under_back > under_front); } + +// Hybrid tree support grows its first layer by raft_first_layer_expansion after the support was clipped to +// the bed, so the grown footprint must be clipped again. +TEST_CASE("Hybrid tree support first layer expansion stays on the bed", "[TreeSupport][Regression]") +{ + const double bed_max_x = 56.; + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "printable_area", "0x0,56x0,56x100,0x100" }, + { "enable_support", 1 }, + { "support_type", "tree(auto)" }, + { "support_style", "tree_hybrid" }, + { "raft_layers", 0 }, + { "raft_first_layer_expansion", 5 }, + { "layer_height", 0.2 }, + { "initial_layer_print_height", 0.2 }, + }); + // A block with a ledge that overhangs to 2 mm from the bed's right edge, closer than the expansion. + TriangleMesh block = make_cube(20, 40, 8); + TriangleMesh ledge = make_cube(9.1, 40, 1.9); + block.translate(25.f, 30.f, 0.f); + // The ledge overlaps the block rather than touching it; a coplanar join slices ambiguously. + ledge.translate(44.9f, 30.f, 6.f); + block.merge(ledge); + + Slic3r::Print print; + Slic3r::Model model; + Slic3r::Test::init_print(std::vector{ std::move(block) }, print, model, config, nullptr, false); + print.process(); + + const PrintObject *object = print.objects().front(); + REQUIRE(!object->support_layers().empty()); + Points first_layer; + object->support_layers().front()->support_fills.collect_points(first_layer); + REQUIRE(!first_layer.empty()); + const Point shift = object->instances().front().shift; + double max_x = 0.; + for (const Point &pt : first_layer) + max_x = std::max(max_x, unscale(pt.x() + shift.x())); + // Without the expansion the support stops near the ledge's edge at 54 mm, so this shows the expansion ran. + REQUIRE(max_x > 55.); + CHECK(max_x <= bed_max_x); +} From 0c62aa085ea908f4077f7a5c3ea46ce37917880a Mon Sep 17 00:00:00 2001 From: Ian Chua Date: Fri, 20 Nov 2026 14:51:42 +0800 Subject: [PATCH 16/36] feat: Install Python plugin wheels with uv (#17281) * feat: initial migration to let UV install plugins for .whls * fix: clang-tidy * Simplify plugin wheel loading through uv * fix: use legacy loader for plugins loaded with legacy method * fix: use same unzip name as old one * fix: keep legacy plugins on the same path * fix: unit tests * fix: allow epoch versions in wheel filenames * fix: clang-tidy * fix: pass Unicode paths to uv on Windows * fix: cleanup * fix: support Windows long paths when installing wheel plugins * fix: recognize uppercase .whl extensions in plugin discovery and dependencies * fix: keep plain import paths for short namespace and compiled packages * refactor: fold duplicate wheel import and cache migration branches * fix: treat an absent package directory as a single-module import * fix: windows long path deletion (#17703) * fix: handle long Windows plugin cleanup paths * fix: warn when plugin deletion removes no files --- docs/HLSD/python-plugin-wheel-installation.md | 57 + src/slic3r/GUI/PluginsDialog.cpp | 17 +- src/slic3r/plugin/PluginAuditManager.cpp | 71 +- src/slic3r/plugin/PluginFsUtils.cpp | 1284 +++++++++++++++-- src/slic3r/plugin/PluginFsUtils.hpp | 93 ++ src/slic3r/plugin/PluginLoader.cpp | 209 ++- src/slic3r/plugin/PythonInterpreter.cpp | 236 ++- src/slic3r/plugin/PythonInterpreter.hpp | 13 +- tests/slic3rutils/CMakeLists.txt | 1 + tests/slic3rutils/test_plugin_audit.cpp | 70 + tests/slic3rutils/test_plugin_install.cpp | 174 +++ tests/slic3rutils/test_plugin_lifecycle.cpp | 260 ++++ .../slic3rutils/test_plugin_wheel_install.cpp | 810 +++++++++++ 13 files changed, 2995 insertions(+), 300 deletions(-) create mode 100644 docs/HLSD/python-plugin-wheel-installation.md create mode 100644 tests/slic3rutils/test_plugin_wheel_install.cpp diff --git a/docs/HLSD/python-plugin-wheel-installation.md b/docs/HLSD/python-plugin-wheel-installation.md new file mode 100644 index 0000000000..6076af5bb7 --- /dev/null +++ b/docs/HLSD/python-plugin-wheel-installation.md @@ -0,0 +1,57 @@ +# Python plugin wheel installation + +## Purpose and identity + +OrcaSlicer runs Python plugins in its embedded interpreter. A plugin's entry is a `.py` file or a wheel stored in its plugin directory. Discovery and metadata reading use that entry file; the wheel remains available after installation. Local plugin keys derive from the entry filename, while cloud plugins use their UUID. Those identities connect plugins to their settings, permissions, capabilities and other references and must not change because of how a wheel is installed. + +Writable plugin data is stored separately from the plugin package. Package removal or replacement must not inadvertently remove that data. + +## Installing wheels + +A wheel entry is installed with bundled `uv` and bundled Python when the plugin is loaded, unless a usable installation is already present. The target is the plugin's legacy extraction path, `/__whl_extracted__//`, which is also where the pre-uv loader extracted the entry wheel. That gives one cache location and one loading flow: the entry package is always imported from that directory, whether it was extracted before or installed by uv. The stored wheel, plugin key and `.install_state.json` sidecar remain where they are, preserving their settings, permissions and capability choices. A `.py` entry is still imported directly. + +`__whl_extracted__/` is shared with dependency wheels. A dependency wheel `.whl` is extracted to `__whl_extracted__//`, so only the entry package's own subdirectory is the installation target; dependency extractions alongside it are left alone. If a dependency wheel's filename stem equals the entry package, both would need the same directory and import name. Installation fails with a collision error instead of replacing the dependency extraction. + +An existing `__whl_extracted__//` without an installation marker is a pre-uv entry extraction. When it already contains the entry package it is used directly: the same directory import runs, and uv is not started, so its files are not rewritten. Only the entry package's own directory counts. The shared `__whl_extracted__/` parent, which holds dependency extractions, is never treated as an entry installation. A markerless target that does not contain the entry package is replaced. A target with a marker that is stale or invalid is a uv-managed installation and is also replaced, through the normal reinstall path. Plugin-owned data belongs in the separate plugin data directory. If uv fails before promotion, the previous directory is left untouched; if promotion fails, it is restored. Either way a markerless extraction remains usable until a replacement succeeds. + +The entry package is metadata-derived and becomes a path component and an import name. It must be a non-empty dotted name whose components are non-empty and contain no path separators, control characters, or characters Windows forbids in filenames. Non-ASCII Unicode names are allowed. This is path-component safety rather than full Python identifier validation: a name that cannot be imported fails when the module is imported. + +uv runs without contacting a package index and without installing dependencies: + +``` +uv --no-config pip install --python --no-python-downloads + --no-deps --no-index --no-cache --link-mode copy + --target +``` + +Declared dependencies continue to use the existing shared installation policy: they are installed separately by uv into the shared packages directory and added to the interpreter's import path. Wheel files next to the entry that are not the entry itself are extracted under `__whl_extracted__/` as before, alongside the entry target. + +The installed directory provides real filesystem paths for package resources. Wheel installation can relocate files compared with literal extraction, especially files in a wheel's `.data` directory. Plugins that derive resource paths from their package location should be checked against the installed layout. + +## Path spelling on Windows + +The plugin root, its `__whl_extracted__/` caches and the files below them can pass the legacy 260-character `MAX_PATH`. Filesystem probes and operations use the extended-length (`\\?\`) spelling where the plain spelling cannot reach a path; uv receives plain paths and qualifies them itself, and a `sys.path` entry keeps the plain spelling it was given whenever the import can be served through it. For an imported package or module that is decided from the entry files the finder probes: the plain spelling is kept while `/__init__.py`, a compiled `__init__` initializer, or the single-module `.py`/compiled extension also fit below the limit. A package with no `.py` entry, such as a namespace or compiled-only package, therefore keeps the plain spelling instead of being prefixed for lack of a file to probe, while any entry file past the limit selects the extended-length form. Dependency extraction roots follow the same rule, decided by whether the extraction root itself is reachable through the plain spelling. + +One limit remains: files nested below the entry are not probed individually. They are reached through the recorded `sys.path` entry, so a submodule that itself lies past the limit is only reached when the entry above it already selected the extended-length form. + +## Wheel filename reconstruction + +uv requires a valid PEP 427 wheel filename. A stored cloud download or a locally renamed wheel may not have one, so installation stages a copy under a name built from the wheel's own `METADATA` name and version and its declared `WHEEL` tags. The stored entry filename is not changed. The tag is selected from the tags the wheel declares; it is never invented, and uv performs the final interpreter/platform compatibility check. + +## Cache and reuse + +Installation happens in a staging directory, `__wheel_staging__-*`, and is promoted to `__whl_extracted__//` only after uv succeeds and the entry package is present. The previous target is moved to `__wheel_prev__-*` during promotion and restored if promotion fails; it is removed after a successful promotion. All of these names start with `__`, so discovery ignores them. + +A marker inside the installed target records the installation format, interpreter ABI, entry package, wheel size and a fingerprint of the wheel bytes. A later load reuses the target when all of them match, so unchanged wheels do not run uv again. A markerless target that contains the entry package is a pre-uv extraction and is reused directly. Any marker that does not match the current wheel, format or ABI causes reinstallation, so a stale uv installation is never reused. The marker is a cache hint, not evidence that a plugin is trustworthy. The entry package must still be identified independently of the distribution name. + +Legacy acceptance and uv installation take the same lock, so a load never accepts a markerless target while another load is rebuilding it. + +The local plugin cache-clear action removes `__whl_extracted__/`, including the entry installation and all dependency extractions. It does not remove the stored wheel, the sidecar or the separate plugin data directory. + +## Failure and lifecycle + +If uv fails or the promoted target is incomplete, the load fails with an error naming the installation problem. There is no silent fallback to extraction. The previous target is restored if promotion fails, and the stored wheel, sidecar, settings and permissions are left in place, so a later load can retry once the problem is resolved. + +Native extensions may remain loaded after a plugin is stopped, particularly on Windows, so replacing or removing their files may require an application restart. + +Each plugin's installation directory is private, but plugins share one interpreter, `sys.path`, `sys.modules` and the dependency directory. Separate directories do not isolate conflicting imports. Installation and execution of plugin code are not security sandboxes. diff --git a/src/slic3r/GUI/PluginsDialog.cpp b/src/slic3r/GUI/PluginsDialog.cpp index 5c4d1e951b..a1ef07005a 100644 --- a/src/slic3r/GUI/PluginsDialog.cpp +++ b/src/slic3r/GUI/PluginsDialog.cpp @@ -1735,29 +1735,28 @@ void PluginsDialog::reload_local_plugin(const std::string& plugin_key, bool clea [plugin_key, was_loaded, clear_cache]() -> std::pair { PluginManager& manager = PluginManager::instance(); - boost::filesystem::path cache_dir; + boost::filesystem::path plugin_root; if (clear_cache) { PluginDescriptor descriptor; if (!manager.try_get_plugin_descriptor(plugin_key, descriptor)) return {false, _u8L("Plugin not found.")}; - boost::filesystem::path resolved_root; - std::string resolve_error; + std::string resolve_error; if (!resolve_allowed_plugin_root(descriptor, {get_orca_plugins_dir()}, _u8L("Refusing to clear a plugin cache outside the local plugin directory."), - resolved_root, resolve_error)) + plugin_root, resolve_error)) return {false, resolve_error}; - cache_dir = resolved_root / "__whl_extracted__"; } if (!manager.unload_plugin(plugin_key)) return {false, _u8L("Failed to unload plugin.")}; if (clear_cache) { - boost::system::error_code ec; - boost::filesystem::remove_all(cache_dir, ec); - if (ec) - return {false, GUI::format(_u8L("Failed to clear plugin cache: %1%"), ec.message())}; + // __whl_extracted__ holds both dependency extractions and the uv-installed + // entry wheel. The stored wheel and plugin data are left untouched. + std::string cache_error; + if (!plugin_wheel_install::delete_install_cache(plugin_root, cache_error)) + return {false, cache_error}; } manager.load_plugin(plugin_key, false); diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index cf247043cc..233fcb1b3d 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -641,13 +641,56 @@ bool same_path_component(const boost::filesystem::path& lhs, const boost::filesy #endif } +#ifdef _WIN32 +// Windows spells some locations two ways: the plain form ("C:\dir", "\\server\share\dir") and the +// documented extended-length form ("\\?\C:\dir", "\\?\UNC\server\share\dir"). A plugin's __file__ +// carries whichever spelling its sys.path entry used, and a path canonicalized past MAX_PATH is +// necessarily extended, while allowed roots and grants are registered in the plain form. The +// prefix adds a root-name component ("\\?\C:" sees "C:", "\\?\UNC" sees "\\server"), so a +// component-wise comparison would never match. Rewrite the two documented aliases to the plain +// spelling here; the result is only compared, never used for I/O. Every other device-namespace +// path ("\\?\Volume{...}", "\\?\PIPE\...", "\\.\pipe\...", "\\.\PhysicalDrive0", "\??\C:\...") +// names something this normalization cannot reinterpret, so it is left exactly as written and +// keeps failing closed against a plain root. +boost::filesystem::path plain_spelling(const boost::filesystem::path& path) +{ + const std::wstring native = path.native(); + + // "\\?\UNC\server\share\..." -> "\\server\share\..." (the Win32 UNC alias). + constexpr std::size_t unc_prefix_length = 8; // "\\?\UNC\" + if (native.rfind(L"\\\\?\\UNC\\", 0) == 0) + return boost::filesystem::path(L"\\\\" + native.substr(unc_prefix_length)); + + // "\\?\C:\..." -> "C:\..." for a drive-letter root only. "\\?\UNC\..." is handled above, and + // anything else after the prefix is a different namespace, not a longer name for a drive path. + constexpr std::size_t prefix_length = 4; // "\\?\" + if (native.rfind(L"\\\\?\\", 0) == 0 && native.size() > prefix_length + 1) { + const wchar_t drive = native[prefix_length]; + const bool letter = (drive >= L'A' && drive <= L'Z') || (drive >= L'a' && drive <= L'z'); + if (letter && native[prefix_length + 1] == L':') + return boost::filesystem::path(native.substr(prefix_length)); + } + + return path; +} +#else +boost::filesystem::path plain_spelling(const boost::filesystem::path& path) +{ + return path; +} +#endif + // True when two canonical paths name the same location: every component must match, using the // platform's case rule. Unlike suffix_inside_root() this is full equality, so a lookalike that // merely shares a prefix -- or a file beside the granted one -- can never match. bool same_canonical_path(const boost::filesystem::path& lhs, const boost::filesystem::path& rhs) { - auto lhs_it = lhs.begin(), lhs_end = lhs.end(); - auto rhs_it = rhs.begin(), rhs_end = rhs.end(); + // Compare in the plain spelling; see plain_spelling(). + const boost::filesystem::path plain_lhs = plain_spelling(lhs); + const boost::filesystem::path plain_rhs = plain_spelling(rhs); + + auto lhs_it = plain_lhs.begin(), lhs_end = plain_lhs.end(); + auto rhs_it = plain_rhs.begin(), rhs_end = plain_rhs.end(); for (; lhs_it != lhs_end && rhs_it != rhs_end; ++lhs_it, ++rhs_it) { if (!same_path_component(*lhs_it, *rhs_it)) return false; @@ -658,18 +701,24 @@ bool same_canonical_path(const boost::filesystem::path& lhs, const boost::filesy // Component-wise containment: the whole of canonical_root must be a prefix of // canonical_candidate, and the remaining components must not traverse upward. Both arguments are // expected to come from canonicalize_for_comparison()/canonical_folder(), i.e. expanded to long -// names where the platform has 8.3 aliases. On a match, suffix receives the candidate's -// components below the root (empty when the two paths are equal). +// names where the platform has 8.3 aliases and possibly carrying the extended-length prefix. On a +// match, suffix receives the candidate's components below the root (empty when the two paths are +// equal). bool suffix_inside_root(const boost::filesystem::path& canonical_candidate, const boost::filesystem::path& canonical_root, boost::filesystem::path& suffix) { suffix.clear(); - auto cand_it = canonical_candidate.begin(); - auto cand_end = canonical_candidate.end(); - auto root_it = canonical_root.begin(); - auto root_end = canonical_root.end(); + // Compare in the plain spelling; see plain_spelling(). The components below the root never + // carry the prefix, so the suffix is unaffected. + const boost::filesystem::path candidate = plain_spelling(canonical_candidate); + const boost::filesystem::path root = plain_spelling(canonical_root); + + auto cand_it = candidate.begin(); + auto cand_end = candidate.end(); + auto root_it = root.begin(); + auto root_end = root.end(); // Consume matching components while (root_it != root_end && cand_it != cand_end && same_path_component(*root_it, *cand_it)) { @@ -697,9 +746,9 @@ bool suffix_inside_root(const boost::filesystem::path& canonical_candidate, bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boost::filesystem::path& allowed_root) { // Both sides are canonicalized identically, including the expansion of Windows 8.3 short - // names, so a root registered under one spelling still contains a target reported under the - // other. A side that cannot be normalized fails closed: comparing differently spelled paths - // could otherwise report containment that does not hold. + // names and the extended-length prefix, so a root registered under one spelling still contains + // a target reported under the other. A side that cannot be normalized fails closed: comparing + // differently spelled paths could otherwise report containment that does not hold. boost::filesystem::path canonical_candidate; if (!canonicalize_for_comparison(candidate, canonical_candidate)) return false; diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index 480fc3f2e7..a1215949a3 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -9,12 +9,13 @@ #include #include #include +#include #include #include #include +#include #include #include -#include #ifdef _WIN32 #ifndef NOMINMAX @@ -43,8 +44,11 @@ #include #include #include +#include #include +#include #include +#include #include #include #include @@ -53,6 +57,29 @@ namespace Slic3r { const char* const INSTALL_STATE_FILE = ".install_state.json"; +namespace { + +// Narrow path for boost::nowide streams and C stdio. On Windows the extended-length ("\\?\") form +// reaches past MAX_PATH even with LongPathsEnabled off; elsewhere the path is unchanged. Keep this +// out of boost::filesystem::path::generic_string(), which rewrites the separators the prefix needs. +std::string io_path_string(const boost::filesystem::path& path) +{ +#ifdef _WIN32 + return boost::nowide::narrow(extended_path(path).wstring()); +#else + return path.string(); +#endif +} + +} // namespace + +bool has_wheel_extension(const boost::filesystem::path& path) +{ + std::string ext = path.extension().string(); + boost::algorithm::to_lower(ext); + return ext == ".whl"; +} + std::mutex& install_state_mutex() { // Function-local static: safe to use from any writer regardless of static initialization order. @@ -199,7 +226,7 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: for (;;) { ++attempts; ec.clear(); - removed_count = fs::remove_all(resolved_root, ec); + removed_count = fs::remove_all(extended_path(resolved_root), ec); if (!ec) break; @@ -226,6 +253,12 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: return false; } + if (removed_count == 0) { + BOOST_LOG_TRIVIAL(warning) << "Plugin deletion removed 0 files from " << resolved_root.string() + << "; the folder may already be absent or may not have been accessible."; + return true; + } + if (attempts > 1) { // Recovered after one or more transient failures: keep the last failure for diagnosis. BOOST_LOG_TRIVIAL(info) << "Deleted plugin: " << plugin_id << " from " << resolved_root.string() @@ -235,16 +268,12 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: return true; } - if (removed_count == 0) { - return true; - } - BOOST_LOG_TRIVIAL(info) << "Deleted plugin: " << plugin_id << " from " << resolved_root.string(); return true; #else // Non-Windows behavior is unchanged: one remove_all() call, no retries. boost::system::error_code ec; - const auto removed_count = fs::remove_all(resolved_root, ec); + const auto removed_count = fs::remove_all(extended_path(resolved_root), ec); if (ec) { // TRN %1% is a folder path, %2% the system error message. error = GUI::format(_u8L("Failed to delete plugin folder %1%: %2%"), resolved_root.string(), ec.message()); @@ -252,6 +281,8 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: } if (removed_count == 0) { + BOOST_LOG_TRIVIAL(warning) << "Plugin deletion removed 0 files from " << resolved_root.string() + << "; the folder may already be absent or may not have been accessible."; return true; } @@ -280,17 +311,21 @@ void scan_plugin_directory(const std::string& dir_path, std::vectorstatus())) continue; - const fs::path plugin_dir = it->path(); + const fs::path plugin_dir = fs::path(dir_path) / it->path().filename(); if (is_ignored_plugin_directory(plugin_dir)) continue; @@ -315,7 +350,7 @@ void scan_plugin_directory(const std::string& dir_path, std::vector get_plugin_directories(const std::string& cloud_user_id // Creates the directory when missing — callers (notably the install path) rely on it existing. auto add_or_create_dir = [&dirs](const fs::path& path) { - if (fs::exists(path) && fs::is_directory(path)) { + const fs::path io_path = extended_path(path); + if (fs::exists(io_path) && fs::is_directory(io_path)) { dirs.push_back(path.string()); return; } try { - fs::create_directories(path); + fs::create_directories(io_path); dirs.push_back(path.string()); BOOST_LOG_TRIVIAL(info) << "Created plugin directory: " << path.string(); } catch (const std::exception& ex) { @@ -461,6 +497,84 @@ std::string normalize_zip_entry_name(std::string entry_name) return entry_name; } +// Locate the single ".dist-info/" directory in a wheel. Returns false when there is none or +// when the archive holds more than one. +bool find_wheel_dist_info_dir(mz_zip_archive& archive, std::string& dist_info_dir, std::string& error) +{ + dist_info_dir.clear(); + + // Scan ALL entries, not just directory entries — some zip writers omit + // explicit directory entries. normalize_zip_entry_name strips trailing + // slashes, so we match ".dist-info" as the last path component of a + // directory entry, and ".dist-info/" embedded in a file path. + const mz_uint num_entries = mz_zip_reader_get_num_files(&archive); + mz_zip_archive_file_stat stat; + + for (mz_uint i = 0; i < num_entries; ++i) { + if (!mz_zip_reader_file_stat(&archive, i, &stat)) + continue; + + std::string entry_name = normalize_zip_entry_name(zip_entry_name(archive, stat)); + if (entry_name.empty()) + continue; + + // Find .dist-info as a path component. + size_t pos = entry_name.find(".dist-info"); + if (pos == std::string::npos) + continue; + + std::string candidate; + if (pos + 10 == entry_name.size()) { + // Directory entry itself (trailing / stripped by normalize). + candidate = entry_name + "/"; + } else if (pos + 10 < entry_name.size() && entry_name[pos + 10] == '/') { + // File inside .dist-info/: name.dist-info/METADATA + candidate = entry_name.substr(0, pos + 11); // include trailing / + } else { + continue; // .dist-info mid-name, not a path component. + } + + if (!dist_info_dir.empty() && candidate != dist_info_dir) { + error = "Wheel contains multiple .dist-info directories: " + dist_info_dir + " and " + candidate; + return false; + } + dist_info_dir = candidate; + } + + if (dist_info_dir.empty()) { + error = "Wheel does not contain a .dist-info directory"; + return false; + } + + return true; +} + +// All Tag: values declared by a WHEEL file, in file order. +std::vector parse_wheel_tags(const std::string& wheel_content) +{ + std::vector tags; + + std::istringstream stream(wheel_content); + std::string line; + while (std::getline(stream, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) + line.pop_back(); + if (line.rfind("Tag:", 0) != 0) + continue; + + std::string tag = line.substr(4); + size_t start = 0; + size_t end = tag.size(); + while (start < end && (tag[start] == ' ' || tag[start] == '\t')) + ++start; + while (end > start && (tag[end - 1] == ' ' || tag[end - 1] == '\t')) + --end; + tags.push_back(tag.substr(start, end - start)); + } + + return tags; +} + struct ZipReaderGuard { mz_zip_archive archive; @@ -913,8 +1027,9 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& // unreadable parent be told apart from a genuinely missing sidecar. Only "no entry" means a // new plugin whose metadata may be seeded; anything else that cannot be read must be // preserved. + const fs::path io_sidecar_path = extended_path(sidecar_path); boost::system::error_code ec; - const fs::file_status link_status = fs::symlink_status(sidecar_path, ec); + const fs::file_status link_status = fs::symlink_status(io_sidecar_path, ec); if (ec) { if (ec == boost::system::errc::no_such_file_or_directory) return InstallStateReadStatus::Absent; @@ -923,11 +1038,11 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& if (!fs::exists(link_status)) return InstallStateReadStatus::Absent; - const fs::file_status status = fs::status(sidecar_path, ec); + const fs::file_status status = fs::status(io_sidecar_path, ec); if (ec || !fs::is_regular_file(status)) return InstallStateReadStatus::Unreadable; - boost::nowide::ifstream f(sidecar_path.string()); + boost::nowide::ifstream f(io_path_string(io_sidecar_path)); if (!f) return InstallStateReadStatus::Unreadable; @@ -938,7 +1053,13 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& // would look malformed too. They count as malformed only when the entry itself is a // regular file, not a link that a move could follow on Windows, and a second read gets // every byte on disk (load_string_file throws otherwise, caught below) that still - // does not parse. + // does not parse. That second read stays on load_string_file() because only it proves a + // full read: copying the streambuf into a stream reports a short or failed read as + // end-of-stream, and a truncated prefix that fails to parse would be misclassified as + // malformed and set aside. It is called with the plain path: load_string_file() goes + // through path::generic_string(), whose forward slashes the "\\?\" prefix does not + // accept, so a sidecar past MAX_PATH fails that read and stays Unreadable, never + // malformed. if (malformed != nullptr && fs::is_regular_file(link_status)) { std::string contents; load_string_file(sidecar_path, contents); @@ -1050,14 +1171,19 @@ bool replace_install_state_file(const boost::filesystem::path& target, const std (target.filename().string() + "." + std::to_string(get_current_pid()) + "." + std::to_string(counter.fetch_add(1, std::memory_order_relaxed)) + ".tmp"); - const auto fail = [&tmp_path, &error](const std::string& reason) { + // Every file operation below uses the extended-length form, so a sidecar past MAX_PATH is still + // replaced atomically; the plain paths stay for the error messages. + const fs::path io_tmp_path = extended_path(tmp_path); + const fs::path io_target_path = extended_path(target); + + const auto fail = [&io_tmp_path, &error](const std::string& reason) { boost::system::error_code remove_ec; - fs::remove(tmp_path, remove_ec); + fs::remove(io_tmp_path, remove_ec); error = reason; return false; }; - boost::nowide::ofstream out(tmp_path.string(), std::ios::out | std::ios::trunc); + boost::nowide::ofstream out(io_path_string(io_tmp_path), std::ios::out | std::ios::trunc); if (!out) return fail("cannot open temporary for writing"); @@ -1076,14 +1202,14 @@ bool replace_install_state_file(const boost::filesystem::path& target, const std // Keep the replaced file's mode where the platform has one. Best effort, matching the previous // writer; a failure here does not turn a successful replace into a failed one. boost::system::error_code perm_ec; - const fs::file_status target_status = fs::status(target, perm_ec); + const fs::file_status target_status = fs::status(io_target_path, perm_ec); if (!perm_ec && fs::exists(target_status)) - fs::permissions(tmp_path, target_status.permissions(), perm_ec); + fs::permissions(io_tmp_path, target_status.permissions(), perm_ec); #endif #ifdef _WIN32 - const std::wstring wide_tmp = tmp_path.wstring(); - const std::wstring wide_target = target.wstring(); + const std::wstring wide_tmp = io_tmp_path.wstring(); + const std::wstring wide_target = io_target_path.wstring(); // A scanner or a reader holding the target open makes MoveFileExW fail transiently with a // sharing or access error. Retry the same replace primitive a bounded number of times; any // other error, or the last attempt, reports the last error and removes the temporary. @@ -1100,7 +1226,7 @@ bool replace_install_state_file(const boost::filesystem::path& target, const std ::Sleep(10); } #else - if (boost::nowide::rename(tmp_path.string().c_str(), target.string().c_str()) != 0) + if (boost::nowide::rename(io_tmp_path.string().c_str(), io_target_path.string().c_str()) != 0) return fail(std::error_code(errno, std::generic_category()).message()); #endif @@ -1200,12 +1326,13 @@ bool read_python_plugin_metadata(const boost::filesystem::path& py_path, PluginD { namespace fs = boost::filesystem; - if (!fs::exists(py_path) || !fs::is_regular_file(py_path)) { + const fs::path io_py_path = extended_path(py_path); + if (!fs::exists(io_py_path) || !fs::is_regular_file(io_py_path)) { error = "Python plugin file does not exist: " + py_path.string(); return false; } - boost::nowide::ifstream f(py_path.string()); + boost::nowide::ifstream f(io_path_string(py_path)); if (!f) { error = "Failed to open Python plugin file: " + py_path.string(); return false; @@ -1281,116 +1408,84 @@ bool read_python_plugin_metadata(const boost::filesystem::path& py_path, PluginD return true; } -bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginDescriptor& descriptor, std::string& error) +namespace { + +// The archive, METADATA and WHEEL contents shared by the two wheel metadata readers. The reader is +// kept open so a caller can read further .dist-info files (RECORD, top_level.txt). +struct WheelPrologue +{ + ZipReaderGuard reader; + std::string dist_info_dir; + std::string wheel; + std::string name; + std::string version; + std::string summary; + std::string author; + std::string import_name; + std::vector requires_dist; +}; + +// Open the wheel, locate its single .dist-info directory, and read METADATA and WHEEL. +bool read_wheel_prologue(const boost::filesystem::path& whl_path, WheelPrologue& out, std::string& error) { namespace fs = boost::filesystem; - if (!fs::exists(whl_path) || !fs::is_regular_file(whl_path)) { + const fs::path io_whl_path = extended_path(whl_path); + if (!fs::exists(io_whl_path) || !fs::is_regular_file(io_whl_path)) { error = "Wheel plugin file does not exist: " + whl_path.string(); return false; } - ZipReaderGuard reader; - if (!open_zip_reader(&reader.archive, whl_path.string())) { - error = "Failed to open wheel as zip: " + MZ_Archive::get_errorstr(mz_zip_get_last_error(&reader.archive)); + if (!open_zip_reader(&out.reader.archive, whl_path.string())) { + error = "Failed to open wheel as zip: " + MZ_Archive::get_errorstr(mz_zip_get_last_error(&out.reader.archive)); return false; } - reader.opened = true; + out.reader.opened = true; - // Find the single .dist-info directory. - // Scan ALL entries, not just directory entries — some zip writers omit - // explicit directory entries. normalize_zip_entry_name strips trailing - // slashes, so we match ".dist-info" as the last path component of a - // directory entry, and ".dist-info/" embedded in a file path. - const mz_uint num_entries = mz_zip_reader_get_num_files(&reader.archive); - std::string dist_info_dir; - mz_zip_archive_file_stat stat; - - for (mz_uint i = 0; i < num_entries; ++i) { - if (!mz_zip_reader_file_stat(&reader.archive, i, &stat)) - continue; - - std::string entry_name = normalize_zip_entry_name(zip_entry_name(reader.archive, stat)); - if (entry_name.empty()) - continue; - - // Find .dist-info as a path component. - size_t pos = entry_name.find(".dist-info"); - if (pos == std::string::npos) - continue; - - std::string candidate; - if (pos + 10 == entry_name.size()) { - // Directory entry itself (trailing / stripped by normalize). - candidate = entry_name + "/"; - } else if (pos + 10 < entry_name.size() && entry_name[pos + 10] == '/') { - // File inside .dist-info/: name.dist-info/METADATA - candidate = entry_name.substr(0, pos + 11); // include trailing / - } else { - continue; // .dist-info mid-name, not a path component. - } - - if (!dist_info_dir.empty() && candidate != dist_info_dir) { - error = "Wheel contains multiple .dist-info directories: " + dist_info_dir + " and " + candidate; - return false; - } - dist_info_dir = candidate; - } - - if (dist_info_dir.empty()) { - error = "Wheel does not contain a .dist-info directory"; - return false; - } - - // Read METADATA. - const std::string metadata_path = dist_info_dir + "METADATA"; - std::string meta_content; - if (!read_zip_text_file(reader.archive, metadata_path.c_str(), meta_content, error)) + if (!find_wheel_dist_info_dir(out.reader.archive, out.dist_info_dir, error)) return false; - std::string meta_name, meta_version, meta_summary, meta_author, meta_requires_python, meta_import_name; - std::vector requires_dist; + std::string metadata_content; + if (!read_zip_text_file(out.reader.archive, (out.dist_info_dir + "METADATA").c_str(), metadata_content, error)) + return false; + + std::string requires_python; std::string meta_error; - parse_metadata_rfc822(meta_content, meta_name, meta_version, meta_summary, meta_author, - meta_requires_python, meta_import_name, requires_dist, meta_error); + parse_metadata_rfc822(metadata_content, out.name, out.version, out.summary, out.author, requires_python, + out.import_name, out.requires_dist, meta_error); - if (meta_name.empty()) { + if (out.name.empty()) { error = "Wheel METADATA missing required Name field"; return false; } - if (meta_version.empty()) { + if (out.version.empty()) { error = "Wheel METADATA missing required Version field"; return false; } - // Read WHEEL (verify existence and Wheel-Version). - const std::string wheel_path = dist_info_dir + "WHEEL"; - std::string wheel_content; - if (!read_zip_text_file(reader.archive, wheel_path.c_str(), wheel_content, error)) + if (!read_zip_text_file(out.reader.archive, (out.dist_info_dir + "WHEEL").c_str(), out.wheel, error)) return false; + + return true; +} + +} // namespace + +bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginDescriptor& descriptor, std::string& error) +{ + WheelPrologue wheel; + if (!read_wheel_prologue(whl_path, wheel, error)) + return false; + // Verify there's at least a Wheel-Version header line. - if (wheel_content.find("Wheel-Version:") == std::string::npos) { + if (wheel.wheel.find("Wheel-Version:") == std::string::npos) { error = "Wheel WHEEL file missing Wheel-Version header"; return false; } // Parse and validate wheel platform tags. { - std::vector wheel_tags; - std::istringstream wstream(wheel_content); - std::string wline; - while (std::getline(wstream, wline)) { - while (!wline.empty() && (wline.back() == '\r' || wline.back() == '\n')) - wline.pop_back(); - if (wline.rfind("Tag:", 0) == 0) { - std::string tag = wline.substr(4); - size_t s = 0, e = tag.size(); - while (s < e && (tag[s] == ' ' || tag[s] == '\t')) ++s; - while (e > s && (tag[e - 1] == ' ' || tag[e - 1] == '\t')) --e; - wheel_tags.push_back(tag.substr(s, e - s)); - } - } - + const std::vector wheel_tags = parse_wheel_tags(wheel.wheel); if (!wheel_tags.empty()) { bool compatible = false; const std::string abi_tag = PythonInterpreter::python_abi_tag(); @@ -1428,9 +1523,9 @@ bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginD } // Read RECORD (verify existence). - const std::string record_path = dist_info_dir + "RECORD"; + const std::string record_path = wheel.dist_info_dir + "RECORD"; std::string record_content; - if (!read_zip_text_file(reader.archive, record_path.c_str(), record_content, error)) + if (!read_zip_text_file(wheel.reader.archive, record_path.c_str(), record_content, error)) return false; if (record_content.empty()) { error = "Wheel RECORD file is empty"; @@ -1439,9 +1534,9 @@ bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginD // Parse top_level.txt if present. std::string top_level; - const std::string top_level_path = dist_info_dir + "top_level.txt"; + const std::string top_level_path = wheel.dist_info_dir + "top_level.txt"; std::string top_level_content; - if (read_zip_text_file(reader.archive, top_level_path.c_str(), top_level_content, error)) { + if (read_zip_text_file(wheel.reader.archive, top_level_path.c_str(), top_level_content, error)) { // top_level.txt contains one package name per line. std::istringstream tl_stream(top_level_content); std::string tl_line; @@ -1466,31 +1561,51 @@ bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginD // 2. Core Metadata Import-Name. // 3. top_level.txt if unambiguous. // 4. Normalized Name as fallback. - if (!meta_import_name.empty()) { - descriptor.entry_package = meta_import_name; + if (!wheel.import_name.empty()) { + descriptor.entry_package = wheel.import_name; } else if (!top_level.empty()) { descriptor.entry_package = top_level; } else { - descriptor.entry_package = normalize_package_name(meta_name); + descriptor.entry_package = normalize_package_name(wheel.name); } - descriptor.dependencies = std::move(requires_dist); + descriptor.dependencies = std::move(wheel.requires_dist); // Populate local identity fallbacks from wheel metadata. // Cloud metadata will override these when available. - descriptor.name = sanitize_plugin_name(meta_name); - descriptor.version = meta_version; - descriptor.description = meta_summary; - descriptor.author = meta_author; + descriptor.name = sanitize_plugin_name(wheel.name); + descriptor.version = wheel.version; + descriptor.description = wheel.summary; + descriptor.author = wheel.author; return true; } +bool read_wheel_install_metadata(const boost::filesystem::path& whl_path, WheelInstallMetadata& out, std::string& error) +{ + out = {}; + error.clear(); + + WheelPrologue wheel; + if (!read_wheel_prologue(whl_path, wheel, error)) + return false; + + out.name = std::move(wheel.name); + out.version = std::move(wheel.version); + out.tags = parse_wheel_tags(wheel.wheel); + return true; +} + boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::path& plugin_dir, std::string& error) { namespace fs = boost::filesystem; - if (!fs::exists(plugin_dir) || !fs::is_directory(plugin_dir)) { + // The entry file is a direct child, so it can pass MAX_PATH while the plugin folder itself still + // resolves. Probe the folder and its children in extended form, then return children joined to + // the caller's `plugin_dir`: that path is stored in the descriptor, passed to uv, and shown in + // the UI, and must keep its normal spelling. + const fs::path io_plugin_dir = extended_path(plugin_dir); + if (!fs::exists(io_plugin_dir) || !fs::is_directory(io_plugin_dir)) { error = GUI::format(_u8L("Plugin directory does not exist: %1%"), plugin_dir.string()); return {}; } @@ -1498,29 +1613,30 @@ boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::pat fs::path py_entry; fs::path whl_entry; - for (fs::directory_iterator it(plugin_dir); it != fs::directory_iterator(); ++it) { - if (is_ignored_plugin_directory(it->path())) + for (fs::directory_iterator it(io_plugin_dir); it != fs::directory_iterator(); ++it) { + const fs::path entry = plugin_dir / it->path().filename(); + if (is_ignored_plugin_directory(entry)) continue; if (!fs::is_regular_file(it->status())) continue; - const fs::path ext = it->path().extension(); + const fs::path ext = entry.extension(); if (ext == ".py") { if (!py_entry.empty()) { // TRN %1% and %2% are file names. error = GUI::format(_u8L("Plugin directory contains multiple .py files: %1% and %2%"), - py_entry.filename().string(), it->path().filename().string()); + py_entry.filename().string(), entry.filename().string()); return {}; } - py_entry = it->path(); - } else if (ext == ".whl") { + py_entry = entry; + } else if (has_wheel_extension(entry)) { if (!whl_entry.empty()) { // TRN %1% and %2% are file names. error = GUI::format(_u8L("Plugin directory contains multiple .whl files: %1% and %2%"), - whl_entry.filename().string(), it->path().filename().string()); + whl_entry.filename().string(), entry.filename().string()); return {}; } - whl_entry = it->path(); + whl_entry = entry; } } @@ -1612,3 +1728,913 @@ std::vector collect_resource_texture_files(const std::string& dir, } } // namespace Slic3r + +// ── uv wheel installation ───────────────────────────────────────────── + +namespace Slic3r::plugin_wheel_install { +namespace { + +namespace fs = boost::filesystem; + +bool is_tag_char(char ch) +{ + const unsigned char uch = static_cast(ch); + return std::isalnum(uch) || ch == '.' || ch == '_' || ch == '+'; +} + +// PEP 427: runs of characters outside the allowed set become a single '_' in the escaped +// component. Both keep [A-Za-z0-9.] plus `extra_chars`: a name '_', a version the characters a +// PEP 440 version may contain, including the '!' epoch separator. +std::string escape_wheel_component(const std::string& value, const std::string& extra_chars) +{ + std::string escaped; + escaped.reserve(value.size()); + bool pending_separator = false; + for (unsigned char ch : value) { + const char c = static_cast(ch); + if (std::isalnum(ch) || ch == '.' || extra_chars.find(c) != std::string::npos) { + if (pending_separator && !escaped.empty()) + escaped += '_'; + pending_separator = false; + escaped += c; + } else { + pending_separator = true; + } + } + return escaped; +} + +std::vector split_tag(const std::string& tag) +{ + std::vector parts; + std::string part; + for (char ch : tag) { + if (ch == '-') { + parts.push_back(part); + part.clear(); + } else { + part += ch; + } + } + parts.push_back(part); + return parts; +} + +bool starts_with_digits_after(const std::string& value, const char* prefix) +{ + const std::string prefix_string(prefix); + if (value.compare(0, prefix_string.size(), prefix_string) != 0) + return false; + return value.size() > prefix_string.size() && std::isdigit(static_cast(value[prefix_string.size()])) != 0; +} + +bool looks_like_python_tag(const std::string& tag) +{ + return starts_with_digits_after(tag, "py") || starts_with_digits_after(tag, "cp") || starts_with_digits_after(tag, "pp") || + tag.compare(0, 7, "graalpy") == 0; +} + +bool looks_like_abi_tag(const std::string& tag) +{ + return tag == "none" || tag == "abi3" || starts_with_digits_after(tag, "cp") || starts_with_digits_after(tag, "pp") || + tag.compare(0, 6, "pypy") == 0; +} + +bool looks_like_platform_tag(const std::string& tag) +{ + if (tag == "any") + return true; + + static constexpr const char* const tokens[] = {"manylinux", "musllinux", "linux", "win", "macosx", "freebsd", + "android", "ios", "openbsd", "netbsd", "solaris", "aix"}; + for (const char* token : tokens) { + if (tag.find(token) != std::string::npos) + return true; + } + return false; +} + +// True when the three tag components name a real Python/ABI/platform combination shape, not just +// three dash-separated words. This is what separates a wheel filename from a generated download +// name (cloud_plugin-.whl also splits into five components). +bool looks_like_wheel_tags(const std::string& python_tag, const std::string& abi, const std::string& platform) +{ + return looks_like_python_tag(python_tag) && looks_like_abi_tag(abi) && looks_like_platform_tag(platform); +} + +bool names_equal_case_insensitive(const std::string& lhs, const std::string& rhs) +{ + return lhs.size() == rhs.size() && + std::equal(lhs.begin(), lhs.end(), rhs.begin(), [](unsigned char a, unsigned char b) { + return std::tolower(a) == std::tolower(b); + }); +} + +// Path-component safety for a metadata-derived package name. Bytes >= 0x80 are left alone so +// non-ASCII (Unicode) import names are not rejected. ASCII path separators, control characters and +// characters Windows forbids in filenames are refused. This is deliberately not a Python +// identifier check: the import step reports a name that cannot be imported. +bool is_safe_package_path_char(unsigned char ch) +{ + if (ch >= 0x80) + return true; + if (ch < 0x20 || ch == 0x7F) + return false; + + switch (ch) { + case '/': + case '\\': + case ':': + case '<': + case '>': + case '"': + case '|': + case '?': + case '*': + return false; + default: + return true; + } +} + +// A dependency wheel .whl is extracted to __whl_extracted__//. If that stem equals the +// entry package, the entry target and the dependency extraction are the same directory. Compare +// case-insensitively so a case-insensitive filesystem cannot hide the collision. +bool dependency_extraction_collides(const fs::path& entry_path, const std::string& entry_package) +{ + if (!is_valid_entry_package(entry_package)) + return false; + + // Mirror add_wheel_dependencies_to_sys_path(): it scans the entry's parent directory (or the + // entry path itself when it has no extension) and recognizes wheel files by extension in any + // case. Keep the same rules here so this guard protects exactly the directories that loader + // uses. + const fs::path plugin_dir = entry_path.has_extension() ? entry_path.parent_path() : entry_path; + const fs::path io_plugin_dir = extended_path(plugin_dir); + const fs::path io_entry_path = extended_path(entry_path); + boost::system::error_code ec; + if (!fs::is_directory(io_plugin_dir, ec)) + return false; + + for (fs::directory_iterator it(io_plugin_dir, ec); !ec && it != fs::directory_iterator(); ++it) { + if (!fs::is_regular_file(it->status())) + continue; + + const fs::path candidate = it->path(); + if (candidate == io_entry_path) + continue; + if (!has_wheel_extension(candidate)) + continue; + + if (names_equal_case_insensitive(candidate.stem().string(), entry_package)) + return true; + } + return false; +} + +bool entry_package_present(const fs::path& target, const std::string& entry_package) +{ + if (!is_valid_entry_package(entry_package)) + return false; + + // The target is the wheel cache directory, which sits below the plugin folder and is the path + // most likely to pass MAX_PATH, so every probe here uses its extended-length form. + const fs::path io_target = extended_path(target); + + // Dotted import names ("pkg.sub") map onto nested components; the wheel installs + // top-level distributions, so this is only a sanity check that the root exists. + fs::path relative; + std::string component; + for (char ch : entry_package) { + if (ch == '.') { + relative /= component; + component.clear(); + } else { + component += ch; + } + } + relative /= component; + + if (fs::is_directory(io_target / relative)) + return true; + if (fs::is_regular_file(io_target / relative.parent_path() / (relative.filename().string() + ".py"))) + return true; + + // A compiled top-level module (.cpython-312-x86_64-linux-gnu.so / .pyd). + const fs::path parent = io_target / relative.parent_path(); + if (fs::is_directory(parent)) { + const std::string leaf = relative.filename().string() + "."; + for (fs::directory_iterator it(parent); it != fs::directory_iterator(); ++it) { + if (!fs::is_regular_file(it->status())) + continue; + const std::string filename = it->path().filename().string(); + if (filename.rfind(leaf, 0) != 0) + continue; + const std::string ext = it->path().extension().string(); + if (ext == ".so" || ext == ".pyd" || ext == ".dll") + return true; + } + } + + return false; +} + +// True when /__whl_extracted__/ is a markerless pre-uv extraction that +// already contains the entry package. Such a target is importable through the ordinary directory +// import, so it is used directly instead of being reinstalled. A marker, even an invalid one, makes +// the directory a uv-managed target whose reuse/reinstall decision belongs to is_installed(). +// Only the entry package's own directory is inspected; the shared __whl_extracted__/ parent also +// holds dependency extractions. +bool has_legacy_entry_extraction(const PluginDescriptor& descriptor) +{ + if (!is_valid_entry_package(descriptor.entry_package)) + return false; + + const std::string target_path = install_dir(descriptor.plugin_root, descriptor.entry_package); + if (target_path.empty()) + return false; + + // The cache target is the path MAX_PATH is reached first, so probe it in extended form. + const fs::path target = extended_path(fs::path(target_path)); + boost::system::error_code ec; + if (!fs::is_directory(target, ec)) + return false; + + ec.clear(); + const bool marker_present = fs::exists(target / MARKER_FILE_NAME, ec); + // Boost's exists() reports an absent path through ec as not-found; that is marker absence. + // Only a different error means the marker's presence could not be determined. + if (ec && ec != boost::system::errc::no_such_file_or_directory) + return false; + if (marker_present) + return false; + + return entry_package_present(target, descriptor.entry_package); +} + +// 64-bit FNV-1a over the wheel bytes. The marker only needs to detect a changed file; this is a +// cache hint, not a trust decision. +bool fingerprint_file(const fs::path& path, std::string& fingerprint, std::uint64_t& size, std::string& error) +{ + boost::nowide::ifstream file(io_path_string(path), std::ios::binary); + if (!file) { + error = "Failed to read plugin wheel: " + path.string(); + return false; + } + + std::uint64_t hash = 1469598103934665603ULL; + std::uint64_t total = 0; + char buffer[64 * 1024]; + while (file) { + file.read(buffer, sizeof(buffer)); + const std::streamsize read = file.gcount(); + for (std::streamsize i = 0; i < read; ++i) { + hash ^= static_cast(buffer[i]); + hash *= 1099511628211ULL; + } + total += static_cast(read); + } + if (file.bad()) { + error = "Failed to read plugin wheel: " + path.string(); + return false; + } + + char hex[17]; + std::snprintf(hex, sizeof(hex), "%016llx", static_cast(hash)); + fingerprint = hex; + size = total; + return true; +} + +void remove_tree_quietly(const fs::path& path) +{ + boost::system::error_code ec; + fs::remove_all(extended_path(path), ec); + if (ec) + BOOST_LOG_TRIVIAL(warning) << "Failed to remove plugin wheel installation directory " << path.string() << ": " << ec.message(); +} + +// Only staging directories are disposable. A `__wheel_prev__-*` directory can be the last usable +// target when a promotion failed and the restore failed; it is removed after a successful +// promotion, never guessed at by a later scan. +bool is_install_scratch_dir(const fs::path& path) +{ + return path.filename().string().rfind(STAGING_DIR_PREFIX, 0) == 0; +} + +// Drop staging leftovers from an interrupted install. Discovery ignores them; they are only disk +// noise. Best effort: a failure to remove one is logged, not fatal. +void remove_stale_scratch_dirs(const fs::path& plugin_root) +{ + const fs::path io_plugin_root = extended_path(plugin_root); + boost::system::error_code ec; + if (!fs::is_directory(io_plugin_root, ec)) + return; + + std::vector stale; + for (fs::directory_iterator it(io_plugin_root, ec); !ec && it != fs::directory_iterator(); ++it) { + // Rebuild the entry from the plain plugin root so the paths handed to cleanup, and the + // paths it logs, keep their normal form. + if (is_install_scratch_dir(it->path())) + stale.push_back(plugin_root / it->path().filename()); + } + for (const fs::path& path : stale) + remove_tree_quietly(path); +} + +bool default_uv_runner(const std::vector& args, std::chrono::seconds timeout, std::string& error) +{ + return PythonInterpreter::run_uv(args, timeout, error); +} + +} // namespace + +bool is_valid_wheel_filename(const std::string& filename) +{ + constexpr const char* extension = ".whl"; + constexpr std::size_t extension_length = 4; + + if (filename.size() <= extension_length) + return false; + if (filename.compare(filename.size() - extension_length, extension_length, extension) != 0) + return false; + + const std::string stem = filename.substr(0, filename.size() - extension_length); + const std::vector parts = split_tag(stem); + if (parts.size() != 5 && parts.size() != 6) + return false; + + for (std::size_t i = 0; i < parts.size(); ++i) { + const std::string& part = parts[i]; + if (part.empty()) + return false; + if (std::any_of(part.begin(), part.end(), [i](char ch) { return !is_tag_char(ch) && !(i == 1 && ch == '!'); })) + return false; + } + + // A PEP 440 version starts with a digit; the three trailing components are python, ABI and + // platform tags. + if (!std::isdigit(static_cast(parts[1][0]))) + return false; + + const std::size_t tag_offset = parts.size() == 6 ? 3 : 2; + return looks_like_wheel_tags(parts[tag_offset], parts[tag_offset + 1], parts[tag_offset + 2]); +} + +std::string make_wheel_filename(const std::string& name, const std::string& version, const std::string& tag) +{ + const std::string escaped_name = escape_wheel_component(name, "_"); + const std::string escaped_version = escape_wheel_component(version, "+!"); + if (escaped_name.empty() || escaped_version.empty() || tag.empty()) + return {}; + + // `tag` is the triple "python-abi-platform" from the WHEEL file, so it legitimately contains + // the two '-' separators that join the filename components. Validate it as a triple here; + // is_valid_wheel_filename() below applies the per-component character and tag-plausibility + // rules to the assembled name. + const std::vector tag_parts = split_tag(tag); + if (tag_parts.size() != 3) + return {}; + + const std::string filename = escaped_name + "-" + escaped_version + "-" + tag + ".whl"; + return is_valid_wheel_filename(filename) ? filename : std::string{}; +} + +namespace { + +// Parse a CPython-style tag ("cp312", "cp38") into major/minor. A tag with only a major digit +// ("cp3") reports minor == -1, meaning "any minor of that major". +bool parse_cpython_tag(const std::string& tag, int& major, int& minor) +{ + if (tag.size() < 3 || tag.compare(0, 2, "cp") != 0) + return false; + + std::size_t end = 2; + while (end < tag.size() && std::isdigit(static_cast(tag[end])) != 0) + ++end; + if (end == 2) + return false; + + major = tag[2] - '0'; + minor = -1; + if (end > 3) { + int value = 0; + for (std::size_t i = 3; i < end; ++i) { + if (value > 100000) + return false; + value = value * 10 + (tag[i] - '0'); + } + minor = value; + } + return true; +} + +// True when a declared python tag (py3, py3.12, py2.py3, cp312, ...) can run on the bundled +// interpreter. PyPy tags (pp*) cannot. +bool python_tag_compatible(const std::string& python_tag, int major, int minor) +{ + std::size_t start = 0; + while (start <= python_tag.size()) { + const std::size_t dot = python_tag.find('.', start); + const std::string component = python_tag.substr(start, dot == std::string::npos ? std::string::npos : dot - start); + + if (component.compare(0, 2, "py") == 0 && component.size() > 2) { + bool only_digits = true; + for (std::size_t i = 2; i < component.size(); ++i) { + if (std::isdigit(static_cast(component[i])) == 0) { + only_digits = false; + break; + } + } + if (only_digits) { + const int component_major = component[2] - '0'; + int component_minor = 0; + for (std::size_t i = 3; i < component.size(); ++i) + component_minor = component_minor * 10 + (component[i] - '0'); + if (component_major == major && (component.size() == 3 || component_minor <= minor)) + return true; + } + } else if (component.compare(0, 2, "cp") == 0) { + int tag_major = 0, tag_minor = -1; + if (parse_cpython_tag(component, tag_major, tag_minor) && tag_major == major && + (tag_minor < 0 || tag_minor <= minor)) + return true; + } + + if (dot == std::string::npos) + break; + start = dot + 1; + } + return false; +} + +// True when the declared ABI can be loaded by the bundled CPython. Pure wheels ("none") follow the +// python tag; "abi3" is the stable ABI up to the running minor; a concrete cpXY ABI must match. +// This is interpreter compatibility only: platform/architecture remains uv's decision. +bool abi_compatible(const std::string& python_tag, + const std::string& abi, + int major, + int minor, + const std::string& current_abi) +{ + if (abi == "none") + return python_tag_compatible(python_tag, major, minor); + + if (abi == "abi3") { + int tag_major = 0, tag_minor = -1; + return parse_cpython_tag(python_tag, tag_major, tag_minor) && tag_major == major && tag_minor <= minor; + } + + if (abi.compare(0, 2, "cp") == 0) + return abi == current_abi && python_tag_compatible(python_tag, major, minor); + + return false; +} + +} // namespace + +std::string wheel_filename_tag(const std::vector& tags) +{ + struct TagParts + { + std::string python; + std::string abi; + std::string platform; + }; + + std::vector valid; + for (const std::string& tag : tags) { + const std::vector parts = split_tag(tag); + if (parts.size() != 3 || parts[0].empty() || parts[1].empty() || parts[2].empty()) + continue; + if (!looks_like_wheel_tags(parts[0], parts[1], parts[2])) + continue; + valid.push_back({parts[0], parts[1], parts[2]}); + } + + if (valid.empty()) + return {}; + + // Prefer a tag the bundled interpreter can actually run. This is only a selection among the + // tags the wheel declares; it never changes one. If no declared tag is interpreter-compatible, + // keep the declared tags so uv can report the incompatibility clearly. + std::vector compatible; + { + const std::string current_abi = PythonInterpreter::python_abi_tag(); + int major = 0, minor = 0; + if (parse_cpython_tag(current_abi, major, minor)) { + for (const TagParts& tag : valid) { + if (abi_compatible(tag.python, tag.abi, major, minor, current_abi)) + compatible.push_back(tag); + } + } + } + const std::vector& candidates = compatible.empty() ? valid : compatible; + + // A declared universal tag covers every platform; prefer it over a platform-specific one. + for (const TagParts& tag : candidates) { + if (tag.platform == "any") + return tag.python + "-" + tag.abi + "-any"; + } + + const TagParts& first = candidates.front(); + + // Only combine tags that differ in nothing but a simple platform. Anything else (a different + // interpreter or ABI tag, or an already-compressed platform) is left exactly as the wheel + // declared it; uv decides whether the resulting filename is usable. + for (const TagParts& tag : candidates) { + if (tag.python != first.python || tag.abi != first.abi) + return first.python + "-" + first.abi + "-" + first.platform; + if (tag.platform.find('.') != std::string::npos) + return first.python + "-" + first.abi + "-" + first.platform; + } + + std::vector platforms; + for (const TagParts& tag : candidates) { + if (std::find(platforms.begin(), platforms.end(), tag.platform) == platforms.end()) + platforms.push_back(tag.platform); + } + + // A single tag, or a set that cannot be expressed as platform alternatives: keep the first tag. + if (platforms.size() <= 1) + return first.python + "-" + first.abi + "-" + first.platform; + + // PEP 425 compressed tag set: one python/abi with alternative platforms. + std::string platform = platforms.front(); + for (std::size_t i = 1; i < platforms.size(); ++i) + platform += "." + platforms[i]; + return first.python + "-" + first.abi + "-" + platform; +} + +bool is_valid_entry_package(const std::string& entry_package) +{ + if (entry_package.empty()) + return false; + + bool component_has_char = false; + for (unsigned char ch : entry_package) { + if (ch == '.') { + // Dotted names need non-empty components; this also rejects "." and "..". + if (!component_has_char) + return false; + component_has_char = false; + } else { + if (!is_safe_package_path_char(ch)) + return false; + component_has_char = true; + } + } + return component_has_char; +} + +std::string install_dir(const std::string& plugin_root, const std::string& entry_package) +{ + if (!is_valid_entry_package(entry_package)) + return {}; + return (fs::path(plugin_root) / EXTRACTED_DIR_NAME / entry_package).string(); +} + +bool delete_install_cache(const boost::filesystem::path& plugin_root, std::string& error) +{ + boost::system::error_code ec; + fs::remove_all(extended_path(plugin_root / EXTRACTED_DIR_NAME), ec); + if (ec) { + // TRN %1% is the system error message. + error = GUI::format(_u8L("Failed to clear plugin cache: %1%"), ec.message()); + return false; + } + return true; +} + +bool is_installed(const PluginDescriptor& descriptor) +{ + if (descriptor.plugin_root.empty()) + return false; + if (descriptor.entry_path.empty()) + return false; + if (descriptor.entry_package.empty()) + return false; + if (!is_valid_entry_package(descriptor.entry_package)) + return false; + + // The installed target is the path most likely to pass MAX_PATH, so it is probed and read in + // extended-length form. Only local path objects carry the prefix; marker fields and the + // descriptor's paths stay unprefixed. + const fs::path target = extended_path(fs::path(install_dir(descriptor.plugin_root, descriptor.entry_package))); + if (!fs::is_directory(target)) + return false; + + const fs::path marker_path = target / MARKER_FILE_NAME; + if (!fs::is_regular_file(marker_path)) + return false; + + nlohmann::json marker; + { + boost::nowide::ifstream file(io_path_string(marker_path)); + if (!file) + return false; + marker = nlohmann::json::parse(file, nullptr, false, true); + } + if (marker.is_discarded() || !marker.is_object()) + return false; + + const auto int_field = [&marker](const char* key) -> long long { + return marker.contains(key) && marker[key].is_number_integer() ? marker[key].get() : -1; + }; + const auto size_field = [&marker](const char* key, std::uint64_t& out) -> bool { + if (!marker.contains(key) || !marker[key].is_number_integer()) + return false; + if (marker[key].is_number_unsigned()) { + out = marker[key].get(); + return true; + } + const auto value = marker[key].get(); + if (value < 0) + return false; + out = static_cast(value); + return true; + }; + const auto string_field = [&marker](const char* key) -> std::string { + return marker.contains(key) && marker[key].is_string() ? marker[key].get() : std::string{}; + }; + + if (int_field("format") != INSTALL_FORMAT) + return false; + if (string_field("abi") != PythonInterpreter::python_abi_tag()) + return false; + if (string_field("entry_package") != descriptor.entry_package) + return false; + + std::string fingerprint; + std::uint64_t size = 0; + std::string fingerprint_error; + if (!fingerprint_file(descriptor.entry_path, fingerprint, size, fingerprint_error)) + return false; + + std::uint64_t recorded_size = 0; + if (!size_field("size", recorded_size)) + return false; + if (string_field("fingerprint") != fingerprint || recorded_size != size) + return false; + + if (!entry_package_present(target, descriptor.entry_package)) + return false; + + return true; +} + +bool ensure_installed(const PluginDescriptor& descriptor, std::string& error, const UvRunner& runner) +{ + error.clear(); + + if (descriptor.plugin_root.empty()) { + error = "Plugin has no installation directory."; + return false; + } + if (descriptor.entry_path.empty()) { + error = "Plugin has no entry file."; + return false; + } + if (!has_wheel_extension(descriptor.entry_path)) { + error = "uv wheel installation is only available for .whl plugins."; + return false; + } + if (!descriptor.is_metadata_valid()) { + error = "Plugin metadata is invalid; its wheel cannot be installed."; + return false; + } + if (descriptor.entry_package.empty()) { + error = "Wheel does not identify an importable entry package."; + return false; + } + if (!is_valid_entry_package(descriptor.entry_package)) { + error = "Wheel entry package '" + descriptor.entry_package + "' is not a safe package path."; + return false; + } + + const fs::path plugin_root = fs::path(descriptor.plugin_root); + const fs::path entry = fs::path(descriptor.entry_path); + const std::string target_path = install_dir(descriptor.plugin_root, descriptor.entry_package); + const fs::path target(target_path); + + // Every filesystem step below runs on the extended-length form: the staging root and the + // installed cache sit below the plugin folder and are where MAX_PATH is reached first. The + // plain paths stay for messages and for the uv arguments (see below). + const fs::path io_entry = extended_path(entry); + const fs::path io_target = extended_path(target); + + // __whl_extracted__/ is shared with dependency extractions. Never take over a directory that + // belongs to a dependency wheel: the two would fight over the same directory and import name. + // Checked before reuse so a marker in a coincidentally named dependency directory cannot make + // the entry look installed. + if (dependency_extraction_collides(entry, descriptor.entry_package)) { + error = "Wheel entry package '" + descriptor.entry_package + + "' collides with the extraction directory of a dependency wheel next to the entry; " + "rename the dependency wheel so its extraction uses a different directory."; + return false; + } + + if (is_installed(descriptor)) { + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] reusing installation for " << descriptor.plugin_key << " (" + << target_path << ")"; + return true; + } + + // Wheel installs mutate a per-plugin directory; serialize them so two plugin loads cannot + // interleave staging/promotion (load already serializes, this also covers direct callers). + static std::mutex install_mutex; + std::lock_guard install_lock(install_mutex); + + // Another caller may have completed the same install while this one waited. + if (is_installed(descriptor)) { + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] reusing installation for " << descriptor.plugin_key << " (" + << target_path << ")"; + return true; + } + + // A markerless entry-specific directory that already contains the entry package is the pre-uv + // loader's extraction. It is imported through the same directory path, so accept it without + // running uv. Checked under the same lock as installation: a concurrent load cannot observe a + // target that another caller is replacing. A marker-present target is uv-managed and keeps the + // reinstall path above, so a stale or invalid uv installation is still rebuilt. + if (has_legacy_entry_extraction(descriptor)) { + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] reusing legacy extraction for " << descriptor.plugin_key << " (" + << target_path << ")"; + return true; + } + + std::string staged_name = entry.filename().string(); + if (!is_valid_wheel_filename(staged_name)) { + // uv accepts only the lowercase ".whl" extension. A stored wheel with an uppercase + // extension keeps its name on disk; only the staged input copy is normalized. + const std::string normalized_name = entry.stem().string() + ".whl"; + if (is_valid_wheel_filename(normalized_name)) { + staged_name = normalized_name; + } else { + // Cloud downloads and side-loaded wheels can carry names uv rejects. Stage a copy + // under a name derived from the wheel's own metadata; the stored wheel is left + // untouched. + WheelInstallMetadata metadata; + std::string metadata_error; + if (!read_wheel_install_metadata(entry, metadata, metadata_error)) { + error = "Failed to read wheel metadata for installation: " + metadata_error; + return false; + } + + const std::string tag = wheel_filename_tag(metadata.tags); + if (tag.empty()) { + error = "Wheel " + entry.filename().string() + + " has no usable filename tag and declares no well-formed python-abi-platform tag in its WHEEL file."; + return false; + } + staged_name = make_wheel_filename(metadata.name, metadata.version, tag); + if (staged_name.empty()) { + error = "Cannot build a valid wheel filename from the metadata of " + entry.filename().string() + "."; + return false; + } + } + } + + remove_stale_scratch_dirs(plugin_root); + + boost::system::error_code ec; + const std::string unique = fs::unique_path("%%%%-%%%%-%%%%").string(); + const fs::path staging_root = plugin_root / (std::string(STAGING_DIR_PREFIX) + unique); + const fs::path staging_input = staging_root / "input"; + const fs::path staging_target = staging_root / "target"; + const fs::path io_staging_input = extended_path(staging_input); + const fs::path io_staging_target = extended_path(staging_target); + + auto fail = [&error, &staging_root](const std::string& message) { + remove_tree_quietly(staging_root); + error = message; + return false; + }; + + fs::create_directories(io_staging_input, ec); + if (ec) + return fail("Failed to create wheel staging directory " + staging_input.string() + ": " + ec.message()); + + const fs::path staged_wheel = staging_input / staged_name; + fs::copy_file(io_entry, extended_path(staged_wheel), ec); + if (ec) + return fail("Failed to stage plugin wheel " + entry.string() + ": " + ec.message()); + + const std::string python_executable = PythonInterpreter::bundled_python_executable(); + if (python_executable.empty()) + return fail("Bundled Python executable not found. Plugin wheel installation is unavailable."); + + // uv receives the plain absolute paths, not the extended-length form: uv is a Rust program whose + // standard library qualifies and verbatim-prefixes a long path itself, and a "\\?\" argument + // would change how it interprets the path. Only this process's own filesystem calls need the + // prefix. + const std::vector args = {"--no-config", + "pip", + "install", + "--python", + python_executable, + "--no-python-downloads", + "--no-deps", + "--no-index", + "--no-cache", + "--link-mode", + "copy", + "--target", + staging_target.string(), + staged_wheel.string()}; + + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] installing " << staged_name << " for " << descriptor.plugin_key + << " into " << staging_target.string(); + + const UvRunner uv_runner = runner ? runner : UvRunner(default_uv_runner); + std::string uv_error; + if (!uv_runner(args, INSTALL_TIMEOUT, uv_error)) { + if (uv_error.empty()) + uv_error = "uv pip install failed"; + return fail(uv_error); + } + + if (!fs::is_directory(io_staging_target, ec)) + return fail("uv reported success but did not create the plugin target."); + if (!entry_package_present(staging_target, descriptor.entry_package)) + return fail("uv reported success but did not install the entry package '" + descriptor.entry_package + "'."); + + std::string fingerprint; + std::uint64_t wheel_size = 0; + std::string fingerprint_error; + if (!fingerprint_file(entry, fingerprint, wheel_size, fingerprint_error)) + return fail(fingerprint_error); + + { + nlohmann::json marker; + marker["format"] = INSTALL_FORMAT; + marker["size"] = wheel_size; + marker["fingerprint"] = fingerprint; + marker["abi"] = PythonInterpreter::python_abi_tag(); + marker["entry_package"] = descriptor.entry_package; + + boost::nowide::ofstream file(io_path_string(io_staging_target / MARKER_FILE_NAME)); + if (!file) + return fail("Failed to write the wheel installation marker."); + file << marker.dump(2, ' ', false, nlohmann::json::error_handler_t::replace); + if (!file) + return fail("Failed to write the wheel installation marker."); + } + + // Promote only a complete target. The previous target is retired under a name discovery + // ignores and is restored if promotion fails; it is never deleted before the new one is live. + // The target's parent (__whl_extracted__) also holds dependency extractions, so creating it is + // safe; only the entry package's own subdirectory is replaced. + ec.clear(); + fs::create_directories(io_target.parent_path(), ec); + if (ec) + return fail("Failed to create the plugin wheel extraction directory " + target.parent_path().string() + + ": " + ec.message()); + + const fs::path previous = plugin_root / (std::string(PREVIOUS_DIR_PREFIX) + unique); + const fs::path io_previous = extended_path(previous); + ec.clear(); + const bool had_target = fs::exists(io_target, ec); + // Boost's exists() reports an absent path through ec as not-found; a fresh install legitimately + // has no target. Only a different error means the probe itself failed. + if (ec && ec != boost::system::errc::no_such_file_or_directory) + return fail("Failed to inspect the existing wheel installation target: " + ec.message()); + if (had_target) { + fs::rename(io_target, io_previous, ec); + if (ec) { + std::string message = "Failed to move the previous wheel installation aside: " + ec.message(); + remove_tree_quietly(staging_root); + error = std::move(message); + return false; + } + } + + fs::rename(io_staging_target, io_target, ec); + if (ec) { + std::string message = "Failed to activate the new wheel installation: " + ec.message(); + if (had_target) { + boost::system::error_code restore_ec; + fs::rename(io_previous, io_target, restore_ec); + if (restore_ec) { + // Keep the retired target: it may still be the only usable copy. + message += " The previous installation could not be restored and was kept at " + previous.string() + ": " + + restore_ec.message(); + } + } + remove_tree_quietly(staging_root); + error = std::move(message); + return false; + } + + // staging_target moved into place; this removes the input copy and the empty staging wrapper. + remove_tree_quietly(staging_root); + + if (had_target) + remove_tree_quietly(previous); + + BOOST_LOG_TRIVIAL(info) << "[plugin_wheel_install] installed " << entry.filename().string() << " for " + << descriptor.plugin_key << " into " << target.string(); + return true; +} + +} // namespace Slic3r::plugin_wheel_install diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index add3887a2a..40a03de7f6 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -4,6 +4,8 @@ #include +#include +#include #include #include #include @@ -128,6 +130,21 @@ bool read_python_plugin_metadata(const boost::filesystem::path& py_path, PluginD // Returns true on success. bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginDescriptor& descriptor, std::string& error); +// The subset of wheel metadata uv needs to accept a staged copy under a valid filename: the +// distribution name and version from METADATA and the declared WHEEL Tag lines. +struct WheelInstallMetadata +{ + std::string name; + std::string version; + std::vector tags; +}; +bool read_wheel_install_metadata(const boost::filesystem::path& whl_path, WheelInstallMetadata& out, std::string& error); + +// True when the path carries the wheel package extension, compared case-insensitively: a package +// stored on a case-insensitive filesystem can end in ".WHL". Only uv requires the lower-case +// spelling for the file it is handed, so the staged copy is normalized instead of rejecting it. +bool has_wheel_extension(const boost::filesystem::path& path); + // Find the single plugin entry file (.py or .whl) in a directory. // Ignores __whl_extracted__ and hidden files/dirs. // Returns the path to the entry file, or an empty path with error set if zero or multiple candidates. @@ -202,3 +219,79 @@ bool read_install_state(const boost::filesystem::path& plugin_dir, PluginDescrip bool read_install_state(const boost::filesystem::path& plugin_dir, PluginInstallState& out); } // namespace Slic3r + +// uv-based installation of a wheel plugin's entry wheel. +namespace Slic3r::plugin_wheel_install { + +// Shared wheel extraction root inside the plugin root. Dependency wheels are extracted into it, +// and the entry wheel is installed into /. This is the same path +// the pre-uv loader extracted the entry wheel to, so there is one cache location. The "__" prefix +// keeps discovery from treating it as a plugin package (see is_ignored_plugin_directory()). +inline constexpr const char* EXTRACTED_DIR_NAME = "__whl_extracted__"; + +// Staging and retirement directories, also inside the plugin root and ignored by discovery. +inline constexpr const char* STAGING_DIR_PREFIX = "__wheel_staging__-"; +inline constexpr const char* PREVIOUS_DIR_PREFIX = "__wheel_prev__-"; + +// Marker written into the target before it is promoted. Bump INSTALL_FORMAT when the layout or +// the uv invocation changes, so an existing target is rebuilt instead of reused. +inline constexpr const char* MARKER_FILE_NAME = "__wheel_install__.json"; +inline constexpr int INSTALL_FORMAT = 2; + +inline constexpr std::chrono::seconds INSTALL_TIMEOUT{120}; + +// Runs `uv ` and reports success. Injectable so tests can exercise staging, promotion and +// reuse without a real uv binary. +using UvRunner = std::function& args, std::chrono::seconds timeout, std::string& error)>; + +// True for a filename shaped like a PEP 427 wheel: name-version(-build)?-python-abi-platform.whl, +// where the three trailing components look like real interpreter/ABI/platform tags. uv performs +// the full metadata and compatibility validation; this only decides whether the stored name can be +// handed to uv as-is or a metadata-derived copy has to be staged. +bool is_valid_wheel_filename(const std::string& filename); + +// Build a PEP 427 wheel filename from metadata. Returns an empty string when any component is +// empty or cannot be escaped into the allowed character set. +std::string make_wheel_filename(const std::string& name, const std::string& version, const std::string& tag); + +// Return a python-abi-platform tag for a staged wheel filename from the tags the wheel declares. +// A declared tag compatible with the bundled interpreter is preferred (so a wheel declaring both +// py2 and py3 uses py3); this never invents a tag. Among the chosen tags, simple platform +// alternatives are combined into one PEP 425 compressed tag set. uv performs the final +// platform/architecture compatibility check. Empty when no well-formed tag exists. +std::string wheel_filename_tag(const std::vector& tags); + +// True for a safe dotted package path: non-empty components separated by '.', with no ASCII path +// separators, control characters, or characters Windows forbids in filenames. Bytes >= 0x80 are +// allowed, so non-ASCII (Unicode) import names are not rejected. This is path-component safety, +// not a Python identifier check; an unimportable name is reported when the module is imported. +bool is_valid_entry_package(const std::string& entry_package); + +// Path of the installed target: /__whl_extracted__/. Does not touch +// the disk. Empty when entry_package is not a safe import name. +std::string install_dir(const std::string& plugin_root, const std::string& entry_package); + +// True when the target exists and the marker proves it was installed from the current entry wheel +// for this interpreter and entry package. +bool is_installed(const PluginDescriptor& descriptor); + +// Delete the plugin's installed-wheel cache (the whole __whl_extracted__ subtree). The plugin root +// must already have passed resolve_allowed_plugin_root(): this only removes the cache directory, +// never the plugin root, the stored wheel or the install sidecar. Removal uses the extended-length +// form, so a cache whose own root passes MAX_PATH is still cleared on Windows. On failure `error` +// explains the cause. +bool delete_install_cache(const boost::filesystem::path& plugin_root, std::string& error); + +// Install the plugin's entry wheel with uv into the legacy extraction path +// /__whl_extracted__/ unless a matching installation already exists. +// An existing markerless directory there is a pre-uv extraction: when it already contains the entry +// package it is used directly, without running uv. A markerless target without the entry package, +// and a target whose marker is stale or invalid, is replaced. Directories for dependency wheels +// elsewhere under __whl_extracted__/ are never touched; a dependency whose filename stem equals the +// entry package is reported as a collision instead of being replaced. The wheel is installed to a +// fresh staging target and promoted only after a successful, complete installation; the previous +// target is restored on failure. On failure `error` explains the cause and no partial target is +// importable. +bool ensure_installed(const PluginDescriptor& descriptor, std::string& error, const UvRunner& runner = {}); + +} // namespace Slic3r::plugin_wheel_install diff --git a/src/slic3r/plugin/PluginLoader.cpp b/src/slic3r/plugin/PluginLoader.cpp index a324f389aa..06aa7a3f2e 100644 --- a/src/slic3r/plugin/PluginLoader.cpp +++ b/src/slic3r/plugin/PluginLoader.cpp @@ -23,15 +23,14 @@ #include #include #include -#include #include "slic3r/plugin/PluginDescriptor.hpp" #include +#include #include #include #include "slic3r/plugin/PythonPluginInterface.hpp" #include #include -#include #include #include @@ -148,6 +147,15 @@ void teardown_capabilities(std::vector& plugin_paths, @@ -155,35 +163,57 @@ bool add_wheel_dependencies_to_sys_path(const PluginDescriptor& descriptor, { namespace fs = boost::filesystem; - const fs::path entry_path(descriptor.entry_path); - const fs::path plugin_dir = entry_path.has_extension() ? entry_path.parent_path() : entry_path; - if (!fs::exists(plugin_dir) || !fs::is_directory(plugin_dir)) + // The plugin folder, and every cache directory below it, can pass the legacy Windows + // MAX_PATH, where the plain spelling cannot be probed at all. Each probe below therefore + // falls back to the extended-length form (the identity off Windows), and only keeps it where + // the plain spelling failed: those paths are what a plugin then sees as __file__ and sys.path + // and what the host compares against the plain plugin root, so an install that resolves + // plainly keeps the plain path it had before. + const fs::path plain_entry_path(descriptor.entry_path); + const fs::path plain_plugin_dir = plain_entry_path.has_extension() ? plain_entry_path.parent_path() : plain_entry_path; + + // Walk the folder through whichever spelling reaches it; an install that fits uses the plain + // one, as before. + const bool plain_reachable = plain_path_exists(plain_plugin_dir); + const fs::path entry_path = plain_reachable ? plain_entry_path : extended_path(plain_entry_path); + const fs::path scan_dir = plain_reachable ? plain_plugin_dir : extended_path(plain_plugin_dir); + + boost::system::error_code scan_ec; + if (!fs::is_directory(scan_dir, scan_ec) || scan_ec) return true; PythonInterpreter& interpreter = PythonInterpreter::instance(); - for (fs::directory_iterator it(plugin_dir); it != fs::directory_iterator(); ++it) { - if (!fs::is_regular_file(it->status()) || it->path().extension() != ".whl") + for (fs::directory_iterator it(scan_dir); it != fs::directory_iterator(); ++it) { + if (!fs::is_regular_file(it->status()) || !has_wheel_extension(it->path())) continue; - // Skip the entry file itself — it is loaded by its own path. + // Skip the entry file itself — it is loaded by its own path. Both sides carry the same + // spelling, so the comparison holds in the extended form too. if (it->path() == entry_path) continue; - const fs::path dep_dir = plugin_dir / "__whl_extracted__" / it->path().stem().string(); - if (!fs::exists(dep_dir)) { + // Build from the plain folder so the recorded spelling stays plain whenever it can. + const fs::path plain_dep_dir = plain_plugin_dir / plugin_wheel_install::EXTRACTED_DIR_NAME / it->path().stem().string(); + const fs::path io_dep_dir = extended_path(plain_dep_dir); + if (!plain_path_exists(plain_dep_dir) && !plain_path_exists(io_dep_dir)) { std::string extract_error; - if (!extract_zip_to_directory(it->path(), dep_dir, extract_error)) { + if (!extract_zip_to_directory(it->path(), plain_dep_dir, extract_error)) { // TRN %1% is the dependency file, %2% the error detail. - error = GUI::format(_u8L("Failed to extract plugin .whl dependency %1%: %2%"), it->path().string(), extract_error); + error = GUI::format(_u8L("Failed to extract plugin .whl dependency %1%: %2%"), + (plain_plugin_dir / it->path().filename()).string(), extract_error); return false; } } - std::string syspath_error; - if (!interpreter.add_plugin_sys_path(dep_dir.string(), syspath_error)) { + // The string handed to the interpreter is the one recorded for unload, so the sys.path + // entry is removed by the same key. Re-probe after extraction: a first extraction through + // a path that fits resolves plainly and must keep that spelling. + const std::string dep_path = plain_path_exists(plain_dep_dir) ? plain_dep_dir.string() : io_dep_dir.string(); + std::string syspath_error; + if (!interpreter.add_plugin_sys_path(dep_path, syspath_error)) { error = GUI::format(_u8L("Failed to add .whl dependency to sys.path: %1%"), syspath_error); return false; } - plugin_paths.push_back(dep_dir.string()); + plugin_paths.push_back(dep_path); } return true; @@ -199,12 +229,13 @@ PyObject* import_plugin_module(const PluginDescriptor& descriptor, if (descriptor.entry_package.empty()) return interpreter.load_module_from_file(descriptor.entry_path, error, &plugin_paths, &plugin_modules); - if (boost::filesystem::path(descriptor.entry_path).extension() == ".whl") - return interpreter.load_module_from_whl( - descriptor.entry_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules); + // A wheel entry is imported from the directory its installation lives in; a .py entry in place. + const std::string dir_path = has_wheel_extension(descriptor.entry_path) ? + plugin_wheel_install::install_dir(descriptor.plugin_root, descriptor.entry_package) : + descriptor.entry_path; return interpreter.load_module_from_directory( - descriptor.entry_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules); + dir_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules); } std::string plugin_module_name(const PluginDescriptor& descriptor) @@ -291,6 +322,22 @@ bool load(const PluginDescriptor& descriptor, plugin.descriptor = descriptor; plugin.module_name = plugin_module_name(descriptor); + // Wheel entries have one installation and one loading path: uv installs the entry wheel into + // the legacy extraction path, then the entry package is imported from there. An existing + // markerless extraction at that path is a pre-uv cache and is used directly when it contains + // the entry package. Dependency wheels are extracted alongside it under __whl_extracted__/ + // and are not touched. + const bool has_entry_wheel = plugin_package_extension(descriptor.entry_path) == ".whl"; + if (has_entry_wheel) { + std::string wheel_install_error; + if (!plugin_wheel_install::ensure_installed(descriptor, wheel_install_error)) { + // Report the failure instead of silently falling back to extraction. + // TRN %1% is the uv/installation error detail. + error = GUI::format(_u8L("Failed to install plugin wheel: %1%"), wheel_install_error); + return false; + } + } + if (!skip_deps) { std::string pkg_install_error; if (!install_packages(descriptor.dependencies, pkg_install_error)) { @@ -510,12 +557,6 @@ bool install_packages(const std::vector& pkgs, std::string& error) if (pkgs.empty()) return true; - const std::string uv_path = PythonInterpreter::bundled_uv_path(); - if (uv_path.empty()) { - error = "Bundled uv executable not found. Python package installation is unavailable."; - return false; - } - const std::string python_executable = PythonInterpreter::bundled_python_executable(); if (python_executable.empty()) { error = "Bundled Python executable not found. Python package installation is unavailable."; @@ -538,81 +579,7 @@ bool install_packages(const std::vector& pkgs, std::string& error) BOOST_LOG_TRIVIAL(info) << "Installing Python packages via uv for " << python_executable << ": " << boost::algorithm::join(pkgs, ", "); - try { - namespace process = boost::process; - - process::ipstream std_err; - process::child child(uv_path, process::args(args), -#ifdef _WIN32 - // uv.exe (and the python.exe it spawns) are console-subsystem programs. - // OrcaSlicer is a GUI app with no console of its own, so without this flag - // Windows allocates a fresh console window for the child that flashes on - // screen during startup plugin loading. Matches ProcessRunner/MediaPlayCtrl. - process::windows::create_no_window, -#endif - process::std_err > std_err); - - std::string err_output; - std::thread stderr_reader([&std_err, &err_output]() { - std::string line; - while (std::getline(std_err, line)) { - err_output += line + '\n'; - } - }); - - // Wait up to 120 seconds for package install to complete. - // - // NOTE: we poll child.running() instead of calling child.wait_for(). - // On macOS (which lacks sigtimedwait) boost.process v1 implements the - // timed waits with a sigwait()-based fallback that deadlocks inside a - // multi-threaded process: SIGCHLD is delivered to an arbitrary thread - // and consumed by an async handler, so the worker thread's sigwait() - // never returns and the timeout never fires — the plugin load hangs - // forever (the "Loading" status never clears). child.running() uses - // waitpid(WNOHANG), which behaves correctly on every platform. - // (boost.process v2, in Boost >= 1.86, implements timed waits via Asio - // and is unaffected — revisit this when the bundled Boost is upgraded.) - constexpr auto kInstallTimeout = std::chrono::seconds(120); - const auto deadline = std::chrono::steady_clock::now() + kInstallTimeout; - - std::error_code run_ec; - while (child.running(run_ec)) { - if (run_ec) { - stderr_reader.join(); - error = "Failed to query uv process status: " + run_ec.message(); - BOOST_LOG_TRIVIAL(error) << error; - return false; - } - if (std::chrono::steady_clock::now() >= deadline) { - std::error_code term_ec; - child.terminate(term_ec); - child.wait(term_ec); - stderr_reader.join(); - error = "uv pip install timed out after 120s"; - BOOST_LOG_TRIVIAL(error) << error; - return false; - } - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - stderr_reader.join(); - - const int exit_code = child.exit_code(); - if (exit_code != 0) { - if (!err_output.empty()) - error = "uv pip install failed (exit code " + std::to_string(exit_code) + "): " + err_output; - else - error = "uv pip install failed with exit code " + std::to_string(exit_code); - BOOST_LOG_TRIVIAL(error) << error; - return false; - } - - BOOST_LOG_TRIVIAL(info) << "Python packages installed successfully"; - return true; - } catch (const std::exception& ex) { - error = std::string("Failed to run uv: ") + ex.what(); - BOOST_LOG_TRIVIAL(error) << error; - return false; - } + return PythonInterpreter::run_uv(args, std::chrono::seconds(120), error); } bool inspect_local_plugin_package(const boost::filesystem::path& filepath, @@ -634,7 +601,11 @@ bool inspect_local_plugin_package(const boost::filesystem::path& filepath, boost::system::error_code ec; const fs::path source_path = canonical_or_absolute(filepath); - if (!fs::exists(source_path, ec) || !fs::is_regular_file(source_path, ec)) + // Both the package file chosen by the user and the install folder derived from its name can + // pass the legacy Windows MAX_PATH, where the plain spelling cannot be probed. The descriptor + // keeps the plain paths; only these probes use the extended-length form. + const fs::path io_source_path = extended_path(source_path); + if (!fs::exists(io_source_path, ec) || !fs::is_regular_file(io_source_path, ec)) return fail("Plugin package is not a file: " + filepath.string()); std::string metadata_error; @@ -646,7 +617,7 @@ bool inspect_local_plugin_package(const boost::filesystem::path& filepath, plugin_descriptor.plugin_root = final_dir.string(); ec.clear(); - const fs::file_status final_status = fs::status(final_dir, ec); + const fs::file_status final_status = fs::status(extended_path(final_dir), ec); if (ec && final_status.type() != fs::file_not_found) return fail("Failed to check existing plugin " + final_dir.string() + ": " + ec.message()); @@ -677,6 +648,7 @@ bool install_plugin(const boost::filesystem::path& filepath, const bool is_cloud_install = !cloud_uuid.empty(); fs::path backup_dir; + fs::path io_backup_dir; bool backup_created = false; auto fail = [&error](const std::string& message) { @@ -687,7 +659,14 @@ bool install_plugin(const boost::filesystem::path& filepath, boost::system::error_code ec; const fs::path source_path = canonical_or_absolute(filepath); - if (!fs::exists(source_path, ec) || !fs::is_regular_file(source_path, ec)) + // The installed copy is //, so a long + // wheel filename pushes the cache past the legacy Windows MAX_PATH even when the plugin root + // stays well below it. The descriptor and the error messages keep the plain spelling; every + // filesystem operation below goes through the extended-length form, which the Win32 APIs + // accept past the limit. extended_path() is the identity off Windows. + const fs::path io_source_path = extended_path(source_path); + + if (!fs::exists(io_source_path, ec) || !fs::is_regular_file(io_source_path, ec)) return fail(GUI::format(_u8L("Plugin package is not a file: %1%"), filepath.string())); const std::string ext = plugin_package_extension(source_path); @@ -701,7 +680,7 @@ bool install_plugin(const boost::filesystem::path& filepath, const fs::path plugin_root = is_cloud_install && !cloud_user_id.empty() ? fs::path(get_cloud_plugin_dir(cloud_user_id)) : local_plugin_root(); - fs::create_directories(plugin_root, ec); + fs::create_directories(extended_path(plugin_root), ec); if (ec) // TRN %1% is a folder path, %2% the system error message. return fail(GUI::format(_u8L("Failed to create plugin directory %1%: %2%"), plugin_root.string(), ec.message())); @@ -735,6 +714,11 @@ bool install_plugin(const boost::filesystem::path& filepath, const fs::path final_dir = is_cloud_install ? plugin_root / cloud_uuid : local_plugin_install_dir(source_path); const fs::path dest_file = final_dir / source_path.filename(); + // The spelled-out install and backup paths above are the identity used by the descriptor and + // the error messages; these are the same locations in the form the filesystem calls need. + const fs::path io_final_dir = extended_path(final_dir); + const fs::path io_dest_file = extended_path(dest_file); + // Local key is the plugin file stem; cloud key is the cloud UUID. if (is_cloud_install) plugin_descriptor.plugin_key = cloud_uuid; @@ -747,12 +731,12 @@ bool install_plugin(const boost::filesystem::path& filepath, auto restore_backup = [&]() { // A fresh install has no backup, but its partial destination must still be removed. boost::system::error_code restore_ec; - fs::remove_all(final_dir, restore_ec); + fs::remove_all(io_final_dir, restore_ec); if (!backup_created) return; restore_ec.clear(); - fs::rename(backup_dir, final_dir, restore_ec); + fs::rename(io_backup_dir, io_final_dir, restore_ec); if (restore_ec) { BOOST_LOG_TRIVIAL(error) << "Failed to restore plugin backup " << backup_dir.string() << " to " << final_dir.string() << ": " << restore_ec.message(); @@ -765,10 +749,11 @@ bool install_plugin(const boost::filesystem::path& filepath, // Backup existing installation if present. The "__" prefix keeps an abandoned backup out of // discovery if the process dies or the final cleanup below cannot remove it. - if (fs::exists(final_dir, ec)) { + if (fs::exists(io_final_dir, ec)) { backup_dir = plugin_root / ("__" + final_dir.filename().string() + ".backup-" + fs::unique_path("%%%%-%%%%-%%%%").string()); - fs::rename(final_dir, backup_dir, ec); + io_backup_dir = extended_path(backup_dir); + fs::rename(io_final_dir, io_backup_dir, ec); if (ec) // TRN %1% is a folder path, %2% the system error message. return fail(GUI::format(_u8L("Failed to back up existing plugin %1%: %2%"), final_dir.string(), ec.message())); @@ -776,13 +761,13 @@ bool install_plugin(const boost::filesystem::path& filepath, } // Create the plugin directory and copy the file. - fs::create_directories(final_dir, ec); + fs::create_directories(io_final_dir, ec); if (ec) { restore_backup(); return fail(GUI::format(_u8L("Failed to create plugin directory %1%: %2%"), final_dir.string(), ec.message())); } - fs::copy_file(source_path, dest_file, ec); + fs::copy_file(io_source_path, io_dest_file, ec); if (ec) { restore_backup(); // TRN %1% is a file path, %2% the system error message. @@ -824,7 +809,7 @@ bool install_plugin(const boost::filesystem::path& filepath, if (backup_created) { boost::system::error_code remove_ec; - fs::remove_all(backup_dir, remove_ec); + fs::remove_all(io_backup_dir, remove_ec); if (remove_ec) BOOST_LOG_TRIVIAL(warning) << "Failed to remove plugin backup " << backup_dir.string() << ": " << remove_ec.message(); } @@ -833,7 +818,7 @@ bool install_plugin(const boost::filesystem::path& filepath, if (is_cloud_install) { boost::system::error_code remove_ec; - fs::remove(source_path, remove_ec); + fs::remove(io_source_path, remove_ec); } return true; } diff --git a/src/slic3r/plugin/PythonInterpreter.cpp b/src/slic3r/plugin/PythonInterpreter.cpp index dbec595add..7060d4bf3a 100644 --- a/src/slic3r/plugin/PythonInterpreter.cpp +++ b/src/slic3r/plugin/PythonInterpreter.cpp @@ -6,13 +6,14 @@ #include #include #include +#include #include #include +#include #include #include #include #include -#include "PluginFsUtils.hpp" #include #include @@ -22,12 +23,15 @@ #include #include #include +#include #include #include #include #include #include #include +#include +#include #include #include #include @@ -190,6 +194,91 @@ std::string executable_name(const char* base) #endif } +// The plain Win32 APIs refuse paths at MAX_PATH (260) unless long paths are enabled; +// extended_path() is what reaches past it. Off Windows there is no such limit. +bool fits_plain_windows_path(const boost::filesystem::path& path) +{ +#ifdef _WIN32 + constexpr std::size_t kLegacyWindowsPathLimit = 260; + return path.wstring().size() < kLegacyWindowsPathLimit; +#else + (void) path; + return true; +#endif +} + +// True when `directory` can be listed through its plain spelling and every entry file the finder +// would probe for `stem` also fits there: ".py" or a compiled "..pyd"/".so". +// A namespace package has none of them, so being able to list the directory is all its import +// needs. +bool plain_path_reaches_entry_files(const boost::filesystem::path& directory, const std::string& stem) +{ + namespace fs = boost::filesystem; + + const std::string leaf = stem + "."; + boost::system::error_code ec; + fs::directory_iterator it(directory, ec); + const fs::directory_iterator end; + for (; !ec && it != end; it.increment(ec)) { + const fs::path& candidate = it->path(); + const std::string filename = candidate.filename().string(); + if (filename.compare(0, leaf.size(), leaf) != 0) + continue; + + const std::string ext = candidate.extension().string(); + if (ext != ".py" && ext != ".pyd" && ext != ".so" && ext != ".dll") + continue; + if (!fits_plain_windows_path(candidate)) + return false; + } + + // An unreadable directory cannot be probed; the extended-length form may still reach it. + return !ec; +} + +// True when the plain spelling of the sys.path entry `dir` reaches everything the import of +// `pkg_name` needs. A directory below the legacy Windows MAX_PATH can still hold package files +// above it, and the finder then silently treats the package as a namespace package: an +// unreachable __init__.py reads exactly like a missing one. The probes here therefore check the +// entry files themselves, so a namespace package and a compiled-only package keep the plain +// spelling, while any entry file past the limit gets the extended-length form, which imports it +// just as well. +bool module_entry_reachable(const boost::filesystem::path& dir, const std::string& pkg_name) +{ + namespace fs = boost::filesystem; + + fs::path relative; + std::string component; + for (const char ch : pkg_name) { + if (ch == '.') { + relative /= component; + component.clear(); + } else { + component += ch; + } + } + if (component.empty()) + return false; + relative /= component; + + const fs::path entry = dir / relative; + + boost::system::error_code ec; + if (fs::is_directory(entry, ec)) + return plain_path_reaches_entry_files(entry, "__init__"); + + // Boost reports a missing path through ec too (ENOENT, or on Windows ERROR_FILE_NOT_FOUND / + // ERROR_PATH_NOT_FOUND), so the code alone cannot tell the single-module layout from a path + // past MAX_PATH. The length can: a fitting absent entry is a module that lives next to it, + // while one that does not fit cannot be probed plainly and takes the extended-length form. + if (!fits_plain_windows_path(entry)) + return false; + + // A single module: .py or a compiled ..pyd/.so next to the package path. + const fs::path parent = relative.parent_path().empty() ? dir : dir / relative.parent_path(); + return plain_path_reaches_entry_files(parent, relative.filename().string()); +} + bool add_sys_path_entry(const boost::filesystem::path& path, std::string& error, bool* inserted = nullptr) { if (inserted) @@ -480,6 +569,105 @@ std::string PythonInterpreter::bundled_uv_path() return {}; } +bool PythonInterpreter::run_uv(const std::vector& args, std::chrono::seconds timeout, std::string& error) +{ + error.clear(); + + const std::string uv_path = bundled_uv_path(); + if (uv_path.empty()) { + error = "Bundled uv executable not found. Python package installation is unavailable."; + return false; + } + + try { + namespace process = boost::process; + + process::ipstream std_err; +#ifdef _WIN32 + // boost::process' narrow overload spawns through CreateProcessA, which interprets the + // executable and arguments in the active ANSI codepage. The uv path and every argument + // here are UTF-8 (boost::nowide::nowide_filesystem makes path::string() UTF-8), so hand + // Boost UTF-16 strings and let it spawn through CreateProcessW instead. + const std::wstring uv_path_wide = boost::nowide::widen(uv_path); + std::vector args_wide; + args_wide.reserve(args.size()); + for (const std::string& arg : args) + args_wide.emplace_back(boost::nowide::widen(arg)); +#endif + process::child child( +#ifdef _WIN32 + uv_path_wide, process::args(args_wide), +#else + uv_path, process::args(args), +#endif +#ifdef _WIN32 + // uv.exe (and the python.exe it spawns) are console-subsystem programs. + // OrcaSlicer is a GUI app with no console of its own, so without this flag + // Windows allocates a fresh console window for the child that flashes on + // screen during startup plugin loading. Matches ProcessRunner/MediaPlayCtrl. + process::windows::create_no_window, +#endif + process::std_err > std_err); + + std::string err_output; + std::thread stderr_reader([&std_err, &err_output]() { + std::string line; + while (std::getline(std_err, line)) { + err_output += line + '\n'; + } + }); + + // NOTE: we poll child.running() instead of calling child.wait_for(). + // On macOS (which lacks sigtimedwait) boost.process v1 implements the + // timed waits with a sigwait()-based fallback that deadlocks inside a + // multi-threaded process: SIGCHLD is delivered to an arbitrary thread + // and consumed by an async handler, so the worker thread's sigwait() + // never returns and the timeout never fires — the plugin load hangs + // forever (the "Loading" status never clears). child.running() uses + // waitpid(WNOHANG), which behaves correctly on every platform. + // (boost.process v2, in Boost >= 1.86, implements timed waits via Asio + // and is unaffected — revisit this when the bundled Boost is upgraded.) + const auto deadline = std::chrono::steady_clock::now() + timeout; + + std::error_code run_ec; + while (child.running(run_ec)) { + if (run_ec) { + stderr_reader.join(); + error = "Failed to query uv process status: " + run_ec.message(); + BOOST_LOG_TRIVIAL(error) << error; + return false; + } + if (std::chrono::steady_clock::now() >= deadline) { + std::error_code term_ec; + child.terminate(term_ec); + child.wait(term_ec); + stderr_reader.join(); + error = "uv pip install timed out after " + std::to_string(timeout.count()) + "s"; + BOOST_LOG_TRIVIAL(error) << error; + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + stderr_reader.join(); + + const int exit_code = child.exit_code(); + if (exit_code != 0) { + if (!err_output.empty()) + error = "uv pip install failed (exit code " + std::to_string(exit_code) + "): " + err_output; + else + error = "uv pip install failed with exit code " + std::to_string(exit_code); + BOOST_LOG_TRIVIAL(error) << error; + return false; + } + + return true; + } catch (const std::exception& ex) { + error = std::string("Failed to run uv: ") + ex.what(); + BOOST_LOG_TRIVIAL(error) << error; + return false; + } +} + bool PythonInterpreter::initialize() { std::unique_lock runtime_lock(m_runtime_mutex); @@ -1170,9 +1358,19 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p } namespace fs = boost::filesystem; - fs::path dir(dir_path); + // A wheel cache below the data directory can pass the legacy Windows MAX_PATH, in the + // directory itself or in the package files below it, where boost::filesystem and the + // interpreter's finder cannot reach either. The plain spelling is what the plugin then sees as + // __file__ and sys.path, and what the host compares against the plain plugin root, so it is + // kept while the entry module is reachable through it; otherwise the extended-length form is + // used for the probe and for sys.path, and the recorded entry matches what is on it. + // extended_path() is the identity off Windows. + fs::path io_dir(dir_path); + if (!io_dir.empty() && !module_entry_reachable(io_dir, pkg_name)) + io_dir = extended_path(io_dir); - if (!fs::exists(dir) || !fs::is_directory(dir)) { + boost::system::error_code ec; + if (!fs::is_directory(io_dir, ec) || ec) { error = "Directory does not exist: " + dir_path; return nullptr; } @@ -1183,7 +1381,7 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p return nullptr; } - const std::string directory = dir.string(); + const std::string directory = io_dir.string(); if (!add_plugin_sys_path_locked(directory, error)) return nullptr; if (plugin_paths) @@ -1206,34 +1404,4 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p return module; } -PyObject* PythonInterpreter::load_module_from_whl(const std::string& file_path, - const std::string& pkg_name, - std::string& error, - std::vector* plugin_paths, - std::vector* plugin_modules) -{ - if (!m_initialized.load(std::memory_order_acquire)) { - error = "Python interpreter not initialized"; - return nullptr; - } - - namespace fs = boost::filesystem; - - fs::path whl_path(file_path); - - if (!fs::exists(whl_path)) { - error = "File does not exist: " + file_path; - return nullptr; - } - - fs::path extract_dir = whl_path.parent_path() / "__whl_extracted__" / pkg_name; - - if (!fs::exists(extract_dir)) { - if (!extract_zip_to_directory(whl_path, extract_dir, error)) - return nullptr; - } - - return load_module_from_directory(extract_dir.string(), pkg_name, error, plugin_paths, plugin_modules); -} - } // namespace Slic3r diff --git a/src/slic3r/plugin/PythonInterpreter.hpp b/src/slic3r/plugin/PythonInterpreter.hpp index 1ae9db92be..da71741e77 100644 --- a/src/slic3r/plugin/PythonInterpreter.hpp +++ b/src/slic3r/plugin/PythonInterpreter.hpp @@ -62,6 +62,14 @@ public: // Bundled uv executable path, or empty when uv is not bundled/found. static std::string bundled_uv_path(); + // Run the bundled uv with `args` (everything after the executable), capturing its stderr. + // Blocks the calling thread until the child exits or `timeout` elapses. + // + // `error` is set to an actionable message on failure: a missing bundled uv, a failed wait, a + // timeout, a non-zero exit status, or the exception thrown while spawning the child. Arguments + // are passed as an array; nothing is routed through a shell. + static bool run_uv(const std::vector& args, std::chrono::seconds timeout, std::string& error); + // Python ABI tag for the bundled interpreter, e.g. "cp312". static std::string python_abi_tag(); @@ -86,11 +94,6 @@ public: std::string& error, std::vector* plugin_paths = nullptr, std::vector* plugin_modules = nullptr); - PyObject* load_module_from_whl(const std::string& whl_path, - const std::string& pkg_name, - std::string& error, - std::vector* plugin_paths = nullptr, - std::vector* plugin_modules = nullptr); PyObject* load_module_from_directory(const std::string& dir_path, const std::string& pkg_name, std::string& error, diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index d6f180ac56..3b3e8fb4a9 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -46,6 +46,7 @@ add_executable(${_TEST_NAME}_tests test_plugin_install.cpp test_plugin_update.cpp test_plugin_lifecycle.cpp + test_plugin_wheel_install.cpp test_plugin_resource_texture.cpp test_plugin_printer_agent.cpp test_post_processor.cpp diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index a295230db3..c130b08748 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -5090,6 +5090,76 @@ TEST_CASE("An implicit writable root matches a target spelled with the other 8.3 #endif } +TEST_CASE("An extended-length spelling names the same location as its plain form", "[audit][Regression]") +{ +#ifndef _WIN32 + SKIP("The extended-length path prefix exists only on Windows"); +#else + ScopedTemporaryDir temp{"orca-plugin-audit-extended-paths"}; + const fs::path root = temp.path() / "root"; + const fs::path outside = temp.path() / "outside"; + fs::create_directories(root / "sub"); + fs::create_directories(outside); + + // A plugin's __file__ is spelled the way its sys.path entry was, and a cache past MAX_PATH can + // only be canonicalized in the extended-length form, while allowed roots are registered plainly. + // The same location has to compare equal in both spellings, and the boundary has to stay put. + const fs::path extended_root = extended_path(root); + const fs::path extended_outside = extended_path(outside); + REQUIRE(extended_root != root); + REQUIRE(extended_outside != outside); + + PluginAuditManager& mgr = PluginAuditManager::instance(); + + SECTION("a plain root contains extended-spelled targets") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(root); + + CHECK(is_inside_allowed_root(extended_path(root / "sub" / "file.txt"), root)); + CHECK(is_inside_allowed_root(root, extended_root)); + CHECK(mgr.delete_target_inside_writable_allowed_root(extended_path(root / "sub").string())); + // A target that does not exist yet is still inside: only the existing prefix is compared. + CHECK(mgr.delete_target_inside_writable_allowed_root(extended_path(root / "not-created-yet").string())); + + // Outside stays outside in the extended spelling too, including a name that only shares the + // root's prefix. + CHECK_FALSE(is_inside_allowed_root(extended_outside / "file.txt", root)); + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root(extended_outside.string())); + CHECK_FALSE(is_inside_allowed_root(extended_path(fs::path(root.string() + "_sibling") / "file.txt"), root)); + } + + SECTION("an extended-spelled root contains plain targets") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(extended_root); + + CHECK(is_inside_allowed_root(root / "sub" / "file.txt", extended_root)); + CHECK(is_inside_allowed_root(extended_root, root)); + CHECK(mgr.delete_target_inside_writable_allowed_root((root / "sub").string())); + + CHECK_FALSE(is_inside_allowed_root(outside / "file.txt", extended_root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(root.string() + "_sibling"), extended_root)); + } + + SECTION("device paths that are not drive-letter aliases stay outside") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(root); + + // "\\?\C:\..." is the only device-namespace alias of a lettered path that the comparison + // rewrites. A volume GUID, a named pipe, the "\\.\" device namespace and the NT "\??\" + // prefix name other objects, so stripping the prefix would invent a path inside the root; + // they must stay unmatched, as must an extended UNC spelling of some other share. + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\\\?\\Volume{00000000-0000-0000-0000-000000000000}\\file.txt"), root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\\\?\\PIPE\\orca-audit"), root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\\\.\\pipe\\orca-audit"), root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\??\\C:\\Windows\\win.ini"), root)); + CHECK_FALSE(is_inside_allowed_root(fs::path(L"\\\\?\\UNC\\orca-audit-host\\share\\file.txt"), root)); + } +#endif +} + TEST_CASE("An asynchronous recursive delete approval is single-use and bound to its plugin and target", "[audit][Python]") { AuditHarness harness; diff --git a/tests/slic3rutils/test_plugin_install.cpp b/tests/slic3rutils/test_plugin_install.cpp index 9fb39f277f..1590b5bb96 100644 --- a/tests/slic3rutils/test_plugin_install.cpp +++ b/tests/slic3rutils/test_plugin_install.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -21,6 +22,8 @@ #include "test_utils.hpp" #include +#include +#include #include #include @@ -76,6 +79,43 @@ fs::path to_extended_path(const fs::path& p) return Slic3r::extended_path(p); } +// Write a small sentinel file through the extended-length form too, so a file whose parent sits +// near MAX_PATH can be created and left in place on Windows. +bool write_file_at_extended_path(const fs::path& path, const std::string& contents) +{ + fs::create_directories(to_extended_path(path.parent_path())); +#ifdef _WIN32 + const std::string io_path = boost::nowide::narrow(to_extended_path(path).wstring()); +#else + const std::string io_path = to_extended_path(path).string(); +#endif + boost::nowide::ofstream out(io_path, std::ios::binary | std::ios::trunc); + if (!out) + return false; + out.write(contents.data(), static_cast(contents.size())); + out.close(); + return static_cast(out); +} + +// A minimal installable wheel: one dist-info directory holding METADATA, WHEEL and RECORD, plus a +// module. install_plugin only caches the archive, so the module body is never imported. +void write_wheel(const fs::path& path, const std::string& dist_name) +{ + fs::create_directories(path.parent_path()); + + Zipper zipper(path.string(), Zipper::NO_COMPRESSION); + const std::string module = "VALUE = 1\n"; + const std::string metadata = "Metadata-Version: 2.1\nName: " + dist_name + "\nVersion: 1.0\n\n"; + const std::string wheel = "Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n"; + const std::string record = "demo_pkg/__init__.py,,\n"; + const std::string info = dist_name + "-1.0.dist-info/"; + zipper.add_entry("demo_pkg/__init__.py", module.data(), module.size()); + zipper.add_entry(info + "METADATA", metadata.data(), metadata.size()); + zipper.add_entry(info + "WHEEL", wheel.data(), wheel.size()); + zipper.add_entry(info + "RECORD", record.data(), record.size()); + zipper.finalize(); +} + // Brings the plugin system up for a case that drives a real plugin load, and tears it down // afterwards. Declare it first in the test so it is destroyed last; the interpreter itself is // process-wide and finalized once by the suite's run-end handler. @@ -195,6 +235,44 @@ TEST_CASE("install_plugin accepts a side-loaded .py with complete PEP 723 metada CHECK(error.empty()); } +TEST_CASE("install_plugin caches a wheel whose destination passes MAX_PATH", "[PluginInstall][Regression]") +{ + ScopedDataDir data_dir_guard("long-path-install"); + ScopedTemporaryDir wheel_source("long-path-wheel-source"); + + // data_dir()/orca_plugins// is the cached copy. A long distribution + // name in the wheel filename pushes that copy past MAX_PATH while the plugin root stays well + // below it, and the Win32 APIs then refuse to create, copy or read the cache unless every + // operation goes through the extended-length form. + fs::path deep_data_dir = data_dir_guard.dir; + while (deep_data_dir.string().size() < 140) + deep_data_dir /= "deep_component"; + fs::create_directories(to_extended_path(deep_data_dir)); + set_data_dir(deep_data_dir.string()); + + const std::string dist_name = "demo_plugin_with_a_distribution_name_long_enough_to_push_the_cached_copy_past_max_path"; + const fs::path wheel = wheel_source.path() / (dist_name + "-1.0-py3-none-any.whl"); + write_wheel(wheel, dist_name); + if (wheel.string().size() >= 260) + SKIP("Temporary directory is too long for a below-MAX_PATH wheel source"); + + PluginDescriptor descriptor; + std::string error; + REQUIRE(plugin_loader::install_plugin(wheel, /*cloud_user_id=*/"", descriptor, error)); + CHECK(error.empty()); + + // The installed package, its descriptor identity and the sidecar beside it are all below the + // deep plugin folder, so each of them has to be reachable past the limit. + const fs::path installed = fs::path(descriptor.entry_path); + REQUIRE(installed.string().size() > 260); + CHECK(fs::is_regular_file(to_extended_path(installed))); + CHECK(fs::is_regular_file(to_extended_path(fs::path(descriptor.plugin_root) / INSTALL_STATE_FILE))); + + // ScopedDataDir's plain remove_all cannot reach past MAX_PATH on Windows. + boost::system::error_code cleanup_ec; + fs::remove_all(to_extended_path(deep_data_dir), cleanup_ec); +} + TEST_CASE("a .py plugin's PEP 723 dependencies split only at the commas between items", "[PluginInstall][PluginFsUtils]") { // Each layout holds the same two items; the first has a comma inside its quotes, as a version @@ -900,3 +978,99 @@ TEST_CASE("extract_zip_to_directory rejects an entry that escapes the destinatio CHECK_THAT(error, Catch::Matchers::ContainsSubstring("escapes the plugin package")); CHECK_FALSE(fs::exists(dir.path() / "escape.txt")); } + +TEST_CASE("deleting a plugin's install cache reaches a cache root past MAX_PATH", + "[PluginInstall][PluginFsUtils][Regression]") +{ + ScopedTemporaryDir plugins_dir("deep-cache-delete"); + const fs::path plugins_root = plugins_dir.path(); + + // Keep the plugin root below MAX_PATH and size the last component so the cache root, one + // directory deeper, passes it. The removal root is what the extended-length form has to reach. + const std::size_t base_length = plugins_root.string().size(); + if (base_length + 2 > 249) + SKIP("Temporary path is too long for a cache root below MAX_PATH"); + const fs::path plugin_root = plugins_root / std::string(249 - base_length, 'c'); + const fs::path cache_root = plugin_root / plugin_wheel_install::EXTRACTED_DIR_NAME; + REQUIRE(plugin_root.string().size() < 260); + REQUIRE(cache_root.string().size() > 260); + + fs::create_directories(to_extended_path(cache_root / "demo_pkg")); + + // The real layout: the plugin root is a child of orca_plugins, and plugin_data is its sibling + // there, not a child of the plugin root. + const fs::path stored_wheel = plugin_root / "demo_pkg-1.0-py3-none-any.whl"; + const fs::path install_sidecar = plugin_root / INSTALL_STATE_FILE; + const fs::path plugin_data = plugins_root / PLUGIN_DATA_DIR / "demo_plugin"; + const fs::path plugin_data_file = plugin_data / "settings.json"; + REQUIRE(write_file_at_extended_path(stored_wheel, "stored wheel sentinel\n")); + REQUIRE(write_file_at_extended_path(install_sidecar, "{\"enabled\": true}\n")); + REQUIRE(write_file_at_extended_path(plugin_data_file, "{\"value\": 1}\n")); + + std::string error; + const bool removed = plugin_wheel_install::delete_install_cache(plugin_root, error); + INFO("cache delete error: " << error); + REQUIRE(removed); + CHECK(error.empty()); + CHECK_FALSE(fs::exists(to_extended_path(cache_root))); + + // Only the cache goes: the stored wheel, install sidecar, plugin root and the sibling plugin + // data all stay. + CHECK(fs::is_directory(to_extended_path(plugin_root))); + CHECK(fs::is_regular_file(to_extended_path(stored_wheel))); + CHECK(fs::is_regular_file(to_extended_path(install_sidecar))); + CHECK(fs::is_regular_file(to_extended_path(plugin_data_file))); + + // Remove the deep plugin root explicitly; ScopedTemporaryDir cleans up the rest. + boost::system::error_code cleanup_ec; + fs::remove_all(to_extended_path(plugin_root), cleanup_ec); + CHECK_FALSE(cleanup_ec); +} + +TEST_CASE("a deep plugin root is authorized inside its directory and then deleted", + "[PluginInstall][PluginFsUtils][Regression]") +{ + ScopedTemporaryDir dir("deep-plugin-root-delete"); + + const fs::path plugin_root = dir.path() / std::string(240, 'p'); + REQUIRE(plugin_root.string().size() > 260); + fs::create_directories(to_extended_path(plugin_root / "demo_pkg")); + + PluginDescriptor descriptor; + descriptor.plugin_root = plugin_root.string(); + + // The authorization check runs on the same deep root that removal will use. + fs::path resolved_root; + std::string error; + REQUIRE(resolve_allowed_plugin_root(descriptor, {dir.path().string()}, "outside plugin root", + resolved_root, error)); + CHECK(error.empty()); + + const bool deleted = delete_plugin_root(resolved_root, descriptor.plugin_root, error); + INFO("plugin delete error: " << error); + REQUIRE(deleted); + CHECK(error.empty()); + CHECK_FALSE(fs::exists(to_extended_path(plugin_root))); +} + +TEST_CASE("a plugin root outside the allowed directories is rejected before deletion", + "[PluginInstall][PluginFsUtils]") +{ + ScopedTemporaryDir allowed_dir("allowed-plugin-root"); + ScopedTemporaryDir outside_dir("outside-plugin-root"); + + const fs::path outside_root = outside_dir.path() / "plugin"; + fs::create_directories(outside_root); + + PluginDescriptor descriptor; + descriptor.plugin_root = outside_root.string(); + + fs::path resolved_root; + std::string error; + CHECK_FALSE(resolve_allowed_plugin_root(descriptor, {allowed_dir.path().string()}, "outside plugin root", + resolved_root, error)); + CHECK(error == "outside plugin root"); + + // Rejection happens before removal, so the outside root is untouched. + CHECK(fs::is_directory(outside_root)); +} diff --git a/tests/slic3rutils/test_plugin_lifecycle.cpp b/tests/slic3rutils/test_plugin_lifecycle.cpp index 86636f21a5..ed55ef0464 100644 --- a/tests/slic3rutils/test_plugin_lifecycle.cpp +++ b/tests/slic3rutils/test_plugin_lifecycle.cpp @@ -1,9 +1,12 @@ #include #include +#include +#include #include #include #include +#include #include #include #include @@ -27,6 +30,7 @@ #include #include #include +#include #include #include #include "slic3r/plugin/PythonPluginInterface.hpp" @@ -217,6 +221,84 @@ fs::path write_plugin(const ScopedDataDir& data_dir_guard, const std::string& st return plugin_dir; } +// Path forms for a tree past the legacy Windows MAX_PATH (260): the extended-length form reaches +// it and is the identity elsewhere, while the UTF-8 spelling is what the interpreter's filesystem +// encoding and boost::nowide expect on Windows. +fs::path long_path(const fs::path& path) +{ + return extended_path(path); +} + +std::string path_utf8(const fs::path& path) +{ +#ifdef _WIN32 + return boost::nowide::narrow(path.wstring()); +#else + return path.string(); +#endif +} + +// Writes /__init__.py, creating the tree through the extended-length form so the +// fixture is buildable past MAX_PATH on Windows. +void write_long_path_package(const fs::path& package_dir) +{ + boost::system::error_code ec; + fs::create_directories(long_path(package_dir), ec); + REQUIRE_FALSE(ec); + + boost::nowide::ofstream init(path_utf8(long_path(package_dir) / "__init__.py")); + init << "VALUE = \"long\"\n"; + REQUIRE(init.good()); +} + +// Loads the package the way the wheel loader does and checks that its body ran, that the recorded +// sys.path entry is exactly the one on sys.path, and that unloading removes it again. +void check_package_import(const fs::path& package_parent, const std::string& pkg_name) +{ + PythonInterpreter& interpreter = PythonInterpreter::instance(); + std::vector paths; + std::vector modules; + std::string error; + // The plain path goes in: reaching the files is the loader's job, not the caller's. + PyObject* module = interpreter.load_module_from_directory(path_utf8(package_parent), pkg_name, error, &paths, &modules); + INFO("module load error: " << error); + REQUIRE(module != nullptr); + REQUIRE(error.empty()); + REQUIRE(paths.size() == 1); + + { + PythonGILState gil; + REQUIRE(gil); + PyObjectPtr value(PyObject_GetAttrString(module, "VALUE")); + REQUIRE(value); + REQUIRE(PyUnicode_Check(value.get())); + CHECK(std::string(PyUnicode_AsUTF8(value.get())) == "long"); + + PyObject* sys_path = PySys_GetObject("path"); + REQUIRE(sys_path != nullptr); + PyObjectPtr entry(PyUnicode_DecodeFSDefault(paths.front().c_str())); + REQUIRE(entry); + CHECK(PySequence_Contains(sys_path, entry.get()) == 1); + } + + Plugin loaded; + loaded.module = module; + loaded.module_name = pkg_name; + loaded.plugin_sys_paths = paths; + loaded.plugin_modules = modules; + loaded.release_module(); + + { + PythonGILState gil; + REQUIRE(gil); + PyObject* sys_path = PySys_GetObject("path"); + REQUIRE(sys_path != nullptr); + PyObjectPtr entry(PyUnicode_DecodeFSDefault(paths.front().c_str())); + REQUIRE(entry); + CHECK(PySequence_Contains(sys_path, entry.get()) == 0); + } +} + // Loads a plugin and blocks until the detached worker thread is done with it. bool load_and_wait(PluginManager& manager, const std::string& plugin_key, @@ -738,6 +820,184 @@ TEST_CASE("Python module release removes package submodules and owned sys.path", loaded.release_module(); } +TEST_CASE("A package imports from a plugin directory longer than MAX_PATH", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("long-path-import-dir"); + + // The sys.path entry itself — the wheel cache — is past the legacy Windows MAX_PATH, so it can + // be neither probed nor imported from through the plain spelling. Components stay short enough + // for NAME_MAX on every platform, so the same tree is valid off Windows. + fs::path package_parent = dir.path(); + while (path_utf8(package_parent).size() < 280) + package_parent /= "deep_plugin_directory_component"; + REQUIRE(path_utf8(package_parent).size() > 260); + + write_long_path_package(package_parent / "long_path_package"); + check_package_import(package_parent, "long_path_package"); + + // Only the extended-length form can remove the deep tree on Windows; the guard then removes + // the shallow remainder. + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(package_parent), cleanup_ec); +} + +TEST_CASE("A package imports when only its files pass MAX_PATH", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("long-path-import-files"); + + // The sys.path entry stays below the limit, so a directory probe alone would accept it, but the + // package file below it does not. The finder reads the unreachable __init__.py as absent and + // accepts the directory as a namespace package, so the loader has to check the entry file + // instead of the directory. + fs::path package_parent = dir.path(); + const std::size_t base_len = path_utf8(package_parent).size() + 1; // the separator before padding + const std::size_t target_len = 250; + if (base_len >= target_len) + SKIP("Temporary directory is too long for a below-MAX_PATH parent"); + package_parent /= std::string(target_len - base_len, 'd'); + REQUIRE(path_utf8(package_parent).size() == target_len); + + const fs::path package_dir = package_parent / "long_path_package"; + REQUIRE(path_utf8(package_dir / "__init__.py").size() > 260); + + write_long_path_package(package_dir); + check_package_import(package_parent, "long_path_package"); + + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(package_parent), cleanup_ec); +} + +TEST_CASE("A namespace package imports through its plain directory path", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("plain-import-namespace"); + const fs::path package_parent = dir.path(); + const std::string pkg_name = "orca_test_namespace_package"; + fs::create_directories(package_parent / pkg_name); + { + std::ofstream submodule((package_parent / pkg_name / "submodule.py").string(), std::ios::binary); + submodule << "VALUE = \"namespace\"\n"; + REQUIRE(submodule.good()); + } + + PythonInterpreter& interpreter = PythonInterpreter::instance(); + std::vector paths; + std::vector modules; + std::string error; + PyObject* module = interpreter.load_module_from_directory(path_utf8(package_parent), pkg_name, error, &paths, &modules); + INFO("module load error: " << error); + REQUIRE(module != nullptr); + REQUIRE(paths.size() == 1); + + // The directory is short enough for the plain Win32 APIs, and a namespace package has no + // __init__.py to probe, so the spelling the caller passed must be the one recorded rather than + // an extended-length path. + CHECK(paths.front() == path_utf8(package_parent)); + + Plugin loaded; + loaded.module = module; + loaded.module_name = pkg_name; + loaded.plugin_sys_paths = paths; + loaded.plugin_modules = modules; + loaded.release_module(); +} + +TEST_CASE("A compiled-only package keeps its plain directory path", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("plain-import-compiled"); + const fs::path package_parent = dir.path(); + const std::string pkg_name = "orca_test_compiled_package"; + fs::create_directories(package_parent / pkg_name); + // A package with no .py entry at all: only a compiled initializer the finder probes by name. + // The fixture is not a loadable extension module, so the import itself fails; the recorded + // sys.path entry is what this test protects. A short directory must not gain the extended-length + // prefix just because there is no .py file to probe. +#ifdef _WIN32 + const fs::path compiled_init = package_parent / pkg_name / "__init__.pyd"; +#else + const fs::path compiled_init = package_parent / pkg_name / "__init__.so"; +#endif + { + std::ofstream compiled(compiled_init.string(), std::ios::binary); + compiled << "not a real extension module\n"; + REQUIRE(compiled.good()); + } + + PythonInterpreter& interpreter = PythonInterpreter::instance(); + std::vector paths; + std::vector modules; + std::string error; + PyObject* module = interpreter.load_module_from_directory(path_utf8(package_parent), pkg_name, error, &paths, &modules); + CHECK(module == nullptr); + CHECK_FALSE(error.empty()); + REQUIRE(paths.size() == 1); + CHECK(paths.front() == path_utf8(package_parent)); + + Plugin loaded; + loaded.module = module; + loaded.module_name = pkg_name; + loaded.plugin_sys_paths = paths; + loaded.plugin_modules = modules; + loaded.release_module(); +} + +TEST_CASE("A compiled-only module keeps its plain directory path", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedTemporaryDir dir("plain-import-compiled-module"); + const fs::path module_parent = dir.path(); + const std::string module_name = "orca_test_compiled_module"; + // A top-level compiled module has no directory beside it, so the probe of that path + // reports "not found". That must not be read as a path past MAX_PATH. As with the package + // fixture, the file is not a loadable extension module, so the import fails after the sys.path + // entry has been recorded. +#ifdef _WIN32 + const fs::path compiled_module = module_parent / (module_name + ".pyd"); +#else + const fs::path compiled_module = module_parent / (module_name + ".so"); +#endif + { + std::ofstream compiled(compiled_module.string(), std::ios::binary); + compiled << "not a real extension module\n"; + REQUIRE(compiled.good()); + } + + PythonInterpreter& interpreter = PythonInterpreter::instance(); + std::vector paths; + std::vector modules; + std::string error; + PyObject* module = interpreter.load_module_from_directory(path_utf8(module_parent), module_name, error, &paths, &modules); + CHECK(module == nullptr); + CHECK_FALSE(error.empty()); + REQUIRE(paths.size() == 1); + CHECK(paths.front() == path_utf8(module_parent)); + + Plugin loaded; + loaded.module = module; + loaded.module_name = module_name; + loaded.plugin_sys_paths = paths; + loaded.plugin_modules = modules; + loaded.release_module(); +} + TEST_CASE("A capability disabled in the sidecar loads disabled", "[PluginLifecycle][Python]") { ScopedPluginManager plugin_system; diff --git a/tests/slic3rutils/test_plugin_wheel_install.cpp b/tests/slic3rutils/test_plugin_wheel_install.cpp new file mode 100644 index 0000000000..b6df07d6fb --- /dev/null +++ b/tests/slic3rutils/test_plugin_wheel_install.cpp @@ -0,0 +1,810 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "catch2/catch_test_macros.hpp" +#include "catch2/matchers/catch_matchers.hpp" +#include "test_utils.hpp" + +using namespace Slic3r; +namespace fs = boost::filesystem; +namespace wheel_install = Slic3r::plugin_wheel_install; + +namespace { + +// The long-path-capable form of a path, which the production code and a real uv (Rust std) use on +// Windows past MAX_PATH. A test that reaches a deep cache has to reach it the same way; on other +// platforms both helpers are the identity. +fs::path long_path(const fs::path& path) +{ + return extended_path(path); +} + +std::string long_path_utf8(const fs::path& path) +{ +#ifdef _WIN32 + return boost::nowide::narrow(extended_path(path).wstring()); +#else + return path.string(); +#endif +} + +void write_wheel(const fs::path& path, + const std::string& tag, + const std::string& module_payload, + const std::string& dist_name = "demo_pkg", + const std::string& version = "1.0") +{ + const fs::path io_path = long_path(path); + if (fs::exists(io_path)) + fs::remove(io_path); + + Zipper zipper(path.string(), Zipper::NO_COMPRESSION); + + const std::string metadata = "Metadata-Version: 2.1\nName: demo-pkg\nVersion: " + version + "\n\n"; + zipper.add_entry(dist_name + "/__init__.py", module_payload.data(), module_payload.size()); + zipper.add_entry(dist_name + "-" + version + ".dist-info/METADATA", metadata.data(), metadata.size()); + + const std::string wheel = "Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: " + tag + "\n"; + zipper.add_entry(dist_name + "-" + version + ".dist-info/WHEEL", wheel.data(), wheel.size()); + + const std::string record = dist_name + "/__init__.py,,\n"; + zipper.add_entry(dist_name + "-" + version + ".dist-info/RECORD", record.data(), record.size()); + + zipper.finalize(); +} + +PluginDescriptor make_descriptor(const fs::path& plugin_root, const fs::path& wheel) +{ + PluginDescriptor descriptor; + descriptor.plugin_key = "demo_plugin"; + descriptor.plugin_root = plugin_root.string(); + descriptor.entry_path = wheel.string(); + descriptor.entry_package = "demo_pkg"; + descriptor.set_metadata_valid(true); + return descriptor; +} + +std::string arg_after(const std::vector& args, const std::string& flag) +{ + for (std::size_t i = 0; i + 1 < args.size(); ++i) { + if (args[i] == flag) + return args[i + 1]; + } + return {}; +} + +// A uv stand-in: creates the directory tree uv would have installed into. It records the command +// line so a test can assert on the staged filename and the safety flags. +wheel_install::UvRunner fake_uv(std::vector* captured, int* call_count, std::string failure) +{ + return [captured, call_count, failure](const std::vector& args, std::chrono::seconds, std::string& error) { + if (call_count != nullptr) + ++*call_count; + if (captured != nullptr) + *captured = args; + + if (!failure.empty()) { + error = failure; + return false; + } + + const fs::path target = arg_after(args, "--target"); + if (target.empty()) { + error = "fake uv: no --target"; + return false; + } + + // The staged wheel must be a real file with a PEP 427 filename, not the stored name. + const fs::path staged(args.back()); + if (!fs::is_regular_file(long_path(staged))) { + error = "fake uv: staged wheel missing"; + return false; + } + + // A real uv writes the target even when it is past MAX_PATH, so this stand-in must too. + fs::create_directories(long_path(target / "demo_pkg")); + boost::nowide::ofstream init(long_path_utf8(target / "demo_pkg" / "__init__.py")); + init << "VALUE = 1\n"; + return true; + }; +} + +// Neither a staging directory nor a retired-previous directory may outlive a successful install. +bool has_install_scratch_leftovers(const fs::path& plugin_root) +{ + for (fs::directory_iterator it(long_path(plugin_root)); it != fs::directory_iterator(); ++it) { + const std::string name = it->path().filename().string(); + if (name.rfind(wheel_install::STAGING_DIR_PREFIX, 0) == 0 || + name.rfind(wheel_install::PREVIOUS_DIR_PREFIX, 0) == 0) + return true; + } + return false; +} + +// A plugin folder deep enough that its install cache and staging paths exceed the legacy Windows +// MAX_PATH (260), while every component stays far below NAME_MAX so the path is also valid on +// Linux and macOS. +fs::path make_deep_plugin_root(const fs::path& base) +{ + fs::path path = base; + while (path.string().size() < 300) + path /= "deep_plugin_directory_component"; + return path / "plugin"; +} + +// A parent directory that still fits below MAX_PATH (260) while /plugin and a standard +// wheel file name inside it do not: discovery has to enumerate the entry past that limit. +fs::path make_boundary_plugin_parent(const fs::path& base) +{ + constexpr std::size_t parent_length = 230; + const std::string component = "boundary_plugin_directory"; + fs::path path = base; + while (path.string().size() + 1 + component.size() < parent_length) + path /= component; + if (path.string().size() + 1 < parent_length) + path /= std::string(parent_length - path.string().size() - 1, 'p'); + return path; +} + +} // namespace + +TEST_CASE("wheel filenames are validated by their PEP 427 shape", "[PluginWheelInstall]") +{ + CHECK(wheel_install::is_valid_wheel_filename("demo-1.0-py3-none-any.whl")); + CHECK(wheel_install::is_valid_wheel_filename("demo_pkg-1.0-1build-py3-none-any.whl")); + CHECK(wheel_install::is_valid_wheel_filename("demo-1.0+local-cp312-cp312-manylinux_2_17_x86_64.whl")); + CHECK(wheel_install::is_valid_wheel_filename("demo-1!2.0-py3-none-any.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-1.0-py3-none-any!.whl")); + + // Too few or too many components, a non-.whl extension, an empty component, or a path separator + // is not a wheel filename uv would accept. + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-1.0-py3-none-any.zip")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-1.0-py3-none.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-1.0--py3-none-any.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo/1.0-py3-none-any.whl")); + + // A cloud download name splits into five components but its components are not tags, so it + // must be restaged from metadata before uv sees it. + CHECK_FALSE(wheel_install::is_valid_wheel_filename("cloud_plugin-1a2b-3c4d-5e6f-7a8b9c0d1e2f.whl")); + CHECK_FALSE(wheel_install::is_valid_wheel_filename("demo-notaversion-py3-none-any.whl")); +} + +TEST_CASE("a missing wheel filename is rebuilt from metadata", "[PluginWheelInstall]") +{ + CHECK(wheel_install::make_wheel_filename("My Plugin", "1.0.0", "py3-none-any") == + "My_Plugin-1.0.0-py3-none-any.whl"); + CHECK(wheel_install::make_wheel_filename("demo", "1!2.0", "py3-none-any") == + "demo-1!2.0-py3-none-any.whl"); + + // The tag is a python-abi-platform triple, so its two '-' separators are part of the tag and + // must survive into the filename, which then has to pass the wheel-filename check. + const std::string pure = wheel_install::make_wheel_filename("demo", "1.0", "py3-none-any"); + REQUIRE_FALSE(pure.empty()); + CHECK(pure == "demo-1.0-py3-none-any.whl"); + CHECK(wheel_install::is_valid_wheel_filename(pure)); + + const std::string native = + wheel_install::make_wheel_filename("demo", "1.0", "cp312-cp312-manylinux_2_17_x86_64"); + REQUIRE_FALSE(native.empty()); + CHECK(native == "demo-1.0-cp312-cp312-manylinux_2_17_x86_64.whl"); + CHECK(wheel_install::is_valid_wheel_filename(native)); + + // Characters uv would reject are escaped; a component that escapes to nothing is refused. + CHECK(wheel_install::make_wheel_filename("demo", "1.0 rc1", "py3-none-any") == "demo-1.0_rc1-py3-none-any.whl"); + CHECK(wheel_install::make_wheel_filename("", "1.0", "py3-none-any").empty()); + CHECK(wheel_install::make_wheel_filename("demo", "1.0", "").empty()); + + // Not a triple, or not a plausible triple: no valid wheel filename can be built. + CHECK(wheel_install::make_wheel_filename("demo", "1.0", "py3-none").empty()); + CHECK(wheel_install::make_wheel_filename("demo", "1.0", "py3/any").empty()); + CHECK(wheel_install::make_wheel_filename("demo", "1.0", "abc-def-ghi").empty()); +} + +TEST_CASE("a staged wheel filename uses the tags the wheel declares", "[PluginWheelInstall]") +{ + CHECK(wheel_install::wheel_filename_tag({}).empty()); + CHECK(wheel_install::wheel_filename_tag({"not-a-tag"}).empty()); + + // No tag is invented: a wheel that only declares py2 keeps that declared tag (uv reports the + // incompatibility), while a wheel declaring both uses the interpreter-compatible one. + CHECK(wheel_install::wheel_filename_tag({"py2-none-any"}) == "py2-none-any"); + CHECK(wheel_install::wheel_filename_tag({"py2-none-any", "py3-none-any"}) == "py3-none-any"); + CHECK(wheel_install::wheel_filename_tag({"cp311-cp311-linux_x86_64", "cp312-cp312-linux_x86_64"}) == + "cp312-cp312-linux_x86_64"); + + // Tags that differ only in platform are combined into a standard compressed tag set. + CHECK(wheel_install::wheel_filename_tag({"cp312-cp312-manylinux_2_17_x86_64", + "cp312-cp312-musllinux_1_2_x86_64"}) == + "cp312-cp312-manylinux_2_17_x86_64.musllinux_1_2_x86_64"); + + // A different interpreter/ABI tag is not merged: the first declared tag is kept. + CHECK(wheel_install::wheel_filename_tag({"cp312-cp312-linux_x86_64", "cp311-cp311-linux_x86_64"}) == + "cp312-cp312-linux_x86_64"); +} + +TEST_CASE("the uv wheel target reuses the legacy entry extraction path", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-target"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + + // One cache location: the directory the pre-uv loader extracted the entry wheel into. + const fs::path expected = plugin_root / "__whl_extracted__" / "demo_pkg"; + CHECK(fs::path(wheel_install::install_dir(plugin_root.string(), "demo_pkg")) == expected); + CHECK(fs::path(wheel_install::install_dir(plugin_root.string(), "pkg.sub")) == + plugin_root / "__whl_extracted__" / "pkg.sub"); + + // The entry package becomes a path component, so path syntax and traversal are refused. + CHECK(wheel_install::install_dir(plugin_root.string(), "").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), "../escape").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), "pkg/sub").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), "pkg\\sub").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), ".hidden").empty()); + CHECK(wheel_install::install_dir(plugin_root.string(), "pkg..sub").empty()); +} + +TEST_CASE("a markerless legacy extraction is used directly without running uv", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-legacy-accept"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + // A pre-uv extraction, plus a separate dependency extraction that must survive. + const fs::path legacy_target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + const fs::path dep_dir = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "dep_pkg"; + fs::create_directories(legacy_target / "demo_pkg"); + fs::create_directories(dep_dir); + { + std::ofstream legacy_file((legacy_target / "written_by_plugin.txt").string()); + legacy_file << "old cache contents\n"; + std::ofstream init_file((legacy_target / "demo_pkg" / "__init__.py").string()); + init_file << "VALUE = 1\n"; + std::ofstream dep_file((dep_dir / "sentinel.txt").string()); + dep_file << "dependency extraction\n"; + } + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 0); + + // The legacy extraction is importable as-is, so it is used without being rewritten. + CHECK(fs::is_regular_file(legacy_target / "written_by_plugin.txt")); + CHECK(fs::is_regular_file(legacy_target / "demo_pkg" / "__init__.py")); + CHECK_FALSE(fs::exists(legacy_target / wheel_install::MARKER_FILE_NAME)); + + // Dependency extractions under the same parent are untouched. + CHECK(fs::is_regular_file(dep_dir / "sentinel.txt")); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); +} + +TEST_CASE("a markerless entry target without the entry package is replaced", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-legacy-incomplete"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + const fs::path target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + fs::create_directories(target); + { + std::ofstream sentinel((target / "sentinel.txt").string()); + sentinel << "incomplete extraction\n"; + } + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + + CHECK_FALSE(fs::exists(target / "sentinel.txt")); + CHECK(fs::is_regular_file(target / "demo_pkg" / "__init__.py")); + CHECK(fs::is_regular_file(target / wheel_install::MARKER_FILE_NAME)); +} + +TEST_CASE("an invalid marker still triggers reinstallation", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-invalid-marker"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + // A marker makes the target uv-managed even when it is unreadable, so the entry package that + // is present does not turn it into an accepted legacy extraction. + const fs::path target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + fs::create_directories(target / "demo_pkg"); + { + std::ofstream sentinel((target / "sentinel.txt").string()); + sentinel << "stale uv installation\n"; + std::ofstream marker((target / wheel_install::MARKER_FILE_NAME).string()); + marker << "not json\n"; + } + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + + CHECK_FALSE(fs::exists(target / "sentinel.txt")); + CHECK(fs::is_regular_file(target / "demo_pkg" / "__init__.py")); +} + +TEST_CASE("the shared extraction parent alone is not a legacy entry extraction", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-parent-only"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + // Dependency extractions under __whl_extracted__/ do not make the entry look installed. + const fs::path dep_dir = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "dep_pkg"; + fs::create_directories(dep_dir); + { + std::ofstream dep_file((dep_dir / "__init__.py").string()); + dep_file << "DEPENDENCY = 1\n"; + } + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + + CHECK(fs::is_directory(plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg")); + CHECK(fs::is_regular_file(dep_dir / "__init__.py")); +} + +TEST_CASE("a dependency extraction at the entry target is not replaced", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-collision"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + // A dependency wheel whose stem is the entry package maps to the same extraction directory. + write_wheel(plugin_root / "demo_pkg.whl", "py3-none-any", "DEPENDENCY = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + const fs::path target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + fs::create_directories(target); + { + std::ofstream sentinel((target / "sentinel.txt").string()); + sentinel << "dependency extraction\n"; + } + + int calls = 0; + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 0); + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("collides")); + + // The dependency extraction is left exactly as it was. + CHECK(fs::is_regular_file(target / "sentinel.txt")); + CHECK_FALSE(fs::exists(target / "demo_pkg")); +} + +TEST_CASE("the entry wheel itself is not treated as a dependency collision", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-entry-stem"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + // A stored wheel renamed to exactly the entry package: its stem matches the target directory, + // but it is the entry and must not be mistaken for a dependency extraction. + const fs::path wheel = plugin_root / "demo_pkg.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + CHECK(fs::is_directory(plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg")); +} + +TEST_CASE("an uppercase dependency wheel extension is treated as a wheel", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-uppercase-dependency"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + // The extension is matched case-insensitively everywhere a wheel is recognized, so this + // dependency maps to the same extraction directory as the entry package and must be refused. + write_wheel(plugin_root / "demo_pkg.WHL", "py3-none-any", "DEPENDENCY = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + int calls = 0; + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 0); + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("collides")); + CHECK_FALSE(fs::exists(plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg")); +} + +TEST_CASE("non-ASCII entry package names are accepted", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-unicode-package"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + + // "pkg_ü" in UTF-8. A Unicode Python identifier must remain a safe path component. + const std::string unicode_package = "pkg_\xC3\xBC"; + CHECK(wheel_install::is_valid_entry_package(unicode_package)); + CHECK(fs::path(wheel_install::install_dir(plugin_root.string(), unicode_package)) == + plugin_root / wheel_install::EXTRACTED_DIR_NAME / unicode_package); +} + +TEST_CASE("an unsafe entry package is rejected before touching the disk", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-unsafe-package"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + for (const std::string& entry_package : + {"../escape", "pkg/sub", "pkg\\sub", "pkg..sub", ".hidden", "pkg*sub", "pkg:sub", "pkg\x01sub"}) { + PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + descriptor.entry_package = entry_package; + + int calls = 0; + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 0); + CHECK_FALSE(fs::exists(plugin_root / wheel_install::EXTRACTED_DIR_NAME)); + } +} + +TEST_CASE("a failed uv install leaves the previous extraction in place", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-legacy-fail"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + const fs::path target = plugin_root / wheel_install::EXTRACTED_DIR_NAME / "demo_pkg"; + fs::create_directories(target); + { + std::ofstream sentinel((target / "sentinel.txt").string()); + sentinel << "previous contents\n"; + } + + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, nullptr, "simulated uv failure"))); + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("simulated uv failure")); + + // uv failed before promotion, so the previous directory is still the only cache copy. + CHECK(fs::is_regular_file(target / "sentinel.txt")); + CHECK_FALSE(fs::exists(target / "demo_pkg")); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); +} + +TEST_CASE("a wheel with an invalid stored name is staged under a valid name", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-stage"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::vector captured; + int calls = 0; + std::string error; + + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, &calls, ""))); + CHECK(error.empty()); + CHECK(calls == 1); + + // The stored wheel keeps its name; only the staged copy uv reads carries a valid one. + CHECK(fs::path(descriptor.entry_path).filename().string() == "plugin.whl"); + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); + // uv installs into a staging target; the promoted target is the one loading uses. + const fs::path uv_target(arg_after(captured, "--target")); + CHECK(uv_target.filename().string() == "target"); + CHECK(uv_target.parent_path().filename().string().rfind(wheel_install::STAGING_DIR_PREFIX, 0) == 0); + const std::string installed_dir = wheel_install::install_dir(plugin_root.string(), "demo_pkg"); + CHECK(uv_target != fs::path(installed_dir)); + CHECK(std::find(captured.begin(), captured.end(), "--no-deps") != captured.end()); + CHECK(std::find(captured.begin(), captured.end(), "--no-index") != captured.end()); + CHECK(std::find(captured.begin(), captured.end(), "--no-python-downloads") != captured.end()); + + CHECK(fs::is_directory(installed_dir)); + CHECK(fs::path(installed_dir) == plugin_root / "__whl_extracted__" / "demo_pkg"); + CHECK(fs::is_regular_file(fs::path(installed_dir) / wheel_install::MARKER_FILE_NAME)); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); +} + +TEST_CASE("a wheel with a valid stored name is passed to uv unchanged", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-valid-name"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "demo_pkg-1.0-py3-none-any.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::vector captured; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, nullptr, ""))); + + // The stored wheel is neither renamed on disk nor renamed in the staged copy. + CHECK(fs::path(descriptor.entry_path).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); +} + +TEST_CASE("an uppercase stored wheel extension is staged under a lowercase .whl name", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-uppercase"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "demo_pkg-1.0-py3-none-any.WHL"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::vector captured; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, nullptr, ""))); + + // The stored file keeps its name; uv only sees the lowercase extension it accepts. + CHECK(fs::path(descriptor.entry_path).filename().string() == "demo_pkg-1.0-py3-none-any.WHL"); + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); +} + +TEST_CASE("an unchanged wheel reuses its installation without running uv again", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-reuse"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + REQUIRE(calls == 1); + + // No uv invocation, no network, no disk rewrite on the next load. + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 1); +} + +TEST_CASE("changed wheel content invalidates the uv installation", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-changed"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + REQUIRE(calls == 1); + + write_wheel(wheel, "py3-none-any", "VALUE = 2\n"); + + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 2); +} + +TEST_CASE("a failed uv install leaves no importable target behind", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-fail"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::string error; + CHECK_FALSE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, nullptr, "simulated uv failure"))); + CHECK_THAT(error, Catch::Matchers::ContainsSubstring("simulated uv failure")); + + CHECK_FALSE(fs::exists(wheel_install::install_dir(plugin_root.string(), "demo_pkg"))); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); +} + +TEST_CASE("a declared wheel tag is used unchanged in the staged filename", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-declared-tag"); + const fs::path plugin_root = dir.path() / "plugin"; + fs::create_directories(plugin_root); + const fs::path wheel = plugin_root / "plugin.whl"; + // A Python-2-only tag: the backend never rewrites it into a claim about this interpreter. uv + // performs the compatibility check on the staged filename. + write_wheel(wheel, "py2-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + std::vector captured; + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, &calls, ""))); + CHECK(calls == 1); + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py2-none-any.whl"); +} + +TEST_CASE("a wheel installs into a plugin path longer than MAX_PATH", "[PluginWheelInstall][Regression]") +{ + ScopedTemporaryDir dir("wheel-install-long-path"); + const fs::path plugin_root = make_deep_plugin_root(dir.path()); + // Past the legacy Windows MAX_PATH (260): the staging, cache, marker and promotion paths are + // all deeper still, so none of them is reachable without the extended-length form there. The + // same tree is valid on Linux and macOS. + REQUIRE(plugin_root.string().size() > 260); + fs::create_directories(long_path(plugin_root)); + + const fs::path wheel = plugin_root / "plugin.whl"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + const PluginDescriptor descriptor = make_descriptor(plugin_root, wheel); + + // An incomplete previous extraction: the install has to retire and replace it, so the + // promotion renames and the cleanup of the retired directory run on deep paths too. + const fs::path target = long_path(fs::path(wheel_install::install_dir(plugin_root.string(), "demo_pkg"))); + fs::create_directories(target); + { + boost::nowide::ofstream sentinel(long_path_utf8(target / "sentinel.txt")); + sentinel << "previous contents\n"; + } + + std::vector captured; + int calls = 0; + std::string error; + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(&captured, &calls, ""))); + CHECK(error.empty()); + CHECK(calls == 1); + // The wheel's stored name is invalid, so it is staged under a PEP 427 name read from the + // metadata of the deep wheel. + CHECK(fs::path(captured.back()).filename().string() == "demo_pkg-1.0-py3-none-any.whl"); + + // The new extraction, its marker and the entry package are all readable at the deep cache + // path, and the retired previous extraction is gone. + CHECK(fs::is_directory(target / "demo_pkg")); + CHECK(fs::is_regular_file(target / "demo_pkg" / "__init__.py")); + CHECK(fs::is_regular_file(target / wheel_install::MARKER_FILE_NAME)); + CHECK_FALSE(fs::exists(target / "sentinel.txt")); + CHECK_FALSE(has_install_scratch_leftovers(plugin_root)); + + // The marker and the entry wheel fingerprint are read back from the deep paths, so no uv run + // and no rewrite happens on the next load. + REQUIRE(wheel_install::ensure_installed(descriptor, error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 1); + + // The scoped temp guard removes the base directory best-effort, but a path past MAX_PATH needs + // the extended form to be removed at all. + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(plugin_root), cleanup_ec); +} + +TEST_CASE("an uppercase wheel extension is discovered as a wheel plugin", "[PluginWheelInstall]") +{ + ScopedTemporaryDir dir("wheel-install-uppercase-discovery"); + const fs::path plugin_parent = dir.path() / "plugins"; + const fs::path plugin_root = plugin_parent / "demo_plugin"; + fs::create_directories(plugin_root); + // A package stored with an upper-case extension is still a wheel: discovery has to read its + // metadata instead of reporting a .py entry that does not exist. + const fs::path wheel = plugin_root / "demo_pkg-1.0-py3-none-any.WHL"; + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + std::string error; + const std::vector discovered = discover_plugin_packages({plugin_parent.string()}, error); + REQUIRE(error.empty()); + REQUIRE(discovered.size() == 1); + CHECK(discovered.front().is_metadata_valid()); + CHECK(discovered.front().entry_package == "demo_pkg"); + CHECK(discovered.front().entry_path == wheel.string()); +} + +TEST_CASE("a wheel is discovered under a plugin folder just below MAX_PATH", "[PluginWheelInstall][Regression]") +{ + ScopedTemporaryDir dir("wheel-install-discovery-boundary"); + const fs::path plugin_parent = make_boundary_plugin_parent(dir.path()); + const fs::path plugin_root = plugin_parent / "plugin"; + const fs::path wheel = plugin_root / "demo_pkg-1.0-py3-none-any.whl"; + // The plugin folder fits below MAX_PATH; the entry wheel inside it does not, so discovery has to + // probe the children in extended form or the package looks like it has no entry file at all. + REQUIRE(plugin_root.string().size() < 260); + REQUIRE(wheel.string().size() > 260); + fs::create_directories(long_path(plugin_root)); + write_wheel(wheel, "py3-none-any", "VALUE = 1\n"); + + std::string error; + const std::vector discovered = discover_plugin_packages({plugin_parent.string()}, error); + REQUIRE(error.empty()); + REQUIRE(discovered.size() == 1); + CHECK(discovered.front().is_metadata_valid()); + CHECK(discovered.front().entry_package == "demo_pkg"); + // The discovered paths keep their normal spelling; only the probes use the extended form. + CHECK(discovered.front().plugin_root == plugin_root.string()); + CHECK(discovered.front().entry_path == wheel.string()); + + // The install stages one level deeper still, and the next load reuses it from the marker. + int calls = 0; + std::string install_error; + REQUIRE(wheel_install::ensure_installed(discovered.front(), install_error, fake_uv(nullptr, &calls, ""))); + CHECK(calls == 1); + + const fs::path target = long_path(fs::path(wheel_install::install_dir(plugin_root.string(), "demo_pkg"))); + CHECK(fs::is_regular_file(target / wheel_install::MARKER_FILE_NAME)); + REQUIRE(wheel_install::ensure_installed(discovered.front(), install_error, fake_uv(nullptr, &calls, "should not run"))); + CHECK(calls == 1); + + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(plugin_root), cleanup_ec); +} + +TEST_CASE("the install-state marker round-trips at a path longer than MAX_PATH", "[PluginWheelInstall][Regression]") +{ + ScopedTemporaryDir dir("plugin-state-long-path"); + const fs::path plugin_root = make_deep_plugin_root(dir.path()); + REQUIRE(plugin_root.string().size() > 260); + fs::create_directories(long_path(plugin_root)); + + PluginDescriptor descriptor = make_descriptor(plugin_root, plugin_root / "plugin.whl"); + descriptor.name = "Demo Plugin"; + + // The sidecar is written through a temporary in the same deep directory and moved into place + // with the platform replace primitive, then read back through the same extended paths. + PluginInstallState state; + { + // The sidecar API expects the install-state lock across its read-modify-write callers. + std::lock_guard state_lock(install_state_mutex()); + REQUIRE(write_install_state(plugin_root, descriptor)); + REQUIRE(read_install_state(plugin_root, state)); + } + CHECK(fs::is_regular_file(long_path(plugin_root / INSTALL_STATE_FILE))); + CHECK(state.plugin_name == "Demo Plugin"); + CHECK(state.installed_from == "local"); + + boost::system::error_code cleanup_ec; + fs::remove_all(long_path(plugin_root), cleanup_ec); +} From ea4927b60173d2d94297bc6e9be8fefe30d3de66 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:41:23 +0800 Subject: [PATCH 17/36] Trim Trailing Zeros at the Decimal Separator wxWidgets Wrote (#17704) * Trim Trailing Zeros at the Decimal Separator wxWidgets Wrote double_to_string formats with wxNumberFormatter, which writes the UI locale's decimal separator, but trimmed after the C locale's separator. When the two differ, as reported on macOS in Czech and Russian, nothing was trimmed and fields showed 0.2000. Trim at wxNumberFormatter::GetDecimalSeparator() instead. * Parse Point Fields Whichever Decimal Separator They Show Point fields write X and Y with the UI locale's decimal separator but read them back with ToDouble, which uses the C locale's. When the two differ, any value with decimals fails with Invalid numeric and resets. Read them with string_to_double_any_separator, which converts the other separator to the C locale's before ToDouble, so every input ToDouble accepted before still parses. --- src/slic3r/GUI/Field.cpp | 19 +++++--- src/slic3r/GUI/Field.hpp | 2 + tests/slic3rutils/CMakeLists.txt | 1 + tests/slic3rutils/test_field_number_text.cpp | 50 ++++++++++++++++++++ 4 files changed, 66 insertions(+), 6 deletions(-) create mode 100644 tests/slic3rutils/test_field_number_text.cpp diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index 15427850bd..3f3886a1ca 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -104,12 +104,11 @@ wxString double_to_string(double const value, const int max_precision /*= 4*/) wxString s = wxNumberFormatter::ToString(value, max_precision, wxNumberFormatter::Style_None); - // The following code comes from wxNumberFormatter::RemoveTrailingZeroes(wxString& s) - // with the exception that here one sets the decimal separator explicitely to dot. + // The following code comes from wxNumberFormatter::RemoveTrailingZeroes(wxString& s). // If number is in scientific format, trailing zeroes belong to the exponent and cannot be removed. if (s.find_first_of("eE") == wxString::npos) { - char dec_sep = is_decimal_separator_point() ? '.' : ','; - const size_t posDecSep = s.find(dec_sep); + // The separator ToString() wrote, from the UI locale, which can differ from the C locale's. + const size_t posDecSep = s.find(wxNumberFormatter::GetDecimalSeparator()); // No decimal point => removing trailing zeroes irrelevant for integer number. if (posDecSep != wxString::npos) { // Find the last character to keep. @@ -127,6 +126,14 @@ wxString double_to_string(double const value, const int max_precision /*= 4*/) return s; } +bool string_to_double_any_separator(wxString str, double* value) +{ + // The text may carry the UI locale's separator or the C locale's, and the two can differ. + const char dec_sep = is_decimal_separator_point() ? '.' : ','; + str.Replace(dec_sep == '.' ? ',' : '.', dec_sep, false); + return str.ToDouble(value); +} + wxString get_thumbnail_string(const Vec2d& value) { wxString ret_str = wxString::Format("%.2fx%.2f", value[0], value[1]); @@ -2900,8 +2907,8 @@ void PointCtrl::set_value(const boost::any& value, bool change_event) boost::any& PointCtrl::get_value() { double x, y; - if (!x_textctrl->GetValue().ToDouble(&x) || - !y_textctrl->GetValue().ToDouble(&y)) + if (!string_to_double_any_separator(x_textctrl->GetValue(), &x) || + !string_to_double_any_separator(y_textctrl->GetValue(), &y)) { set_value(m_value.empty() ? Vec2d(0.0, 0.0) : m_value, true); show_error(m_parent, _L("Invalid numeric.")); diff --git a/src/slic3r/GUI/Field.hpp b/src/slic3r/GUI/Field.hpp index acdf0c21a2..72c3e31705 100644 --- a/src/slic3r/GUI/Field.hpp +++ b/src/slic3r/GUI/Field.hpp @@ -59,6 +59,8 @@ using t_change = std::function; wxString double_to_string(double const value, const int max_precision = 4); +// Parses a number shown in a field, whichever decimal separator it uses. +bool string_to_double_any_separator(wxString str, double* value); wxString get_thumbnail_string(const Vec2d& value); wxString get_thumbnails_string(const std::vector& values); wxString get_formatted_tooltip_text(const ConfigOptionDef& opt, const t_config_option_key& id); diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 3b3e8fb4a9..36db245c61 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -15,6 +15,7 @@ add_executable(${_TEST_NAME}_tests test_network_discovery.cpp test_filament_bitmap_utils.cpp test_colour_picker_field.cpp + test_field_number_text.cpp test_filament_color_picker.cpp test_ams_materials_setting.cpp test_gcode_preview_colors.cpp diff --git a/tests/slic3rutils/test_field_number_text.cpp b/tests/slic3rutils/test_field_number_text.cpp new file mode 100644 index 0000000000..889802e0d4 --- /dev/null +++ b/tests/slic3rutils/test_field_number_text.cpp @@ -0,0 +1,50 @@ +#include "slic3r/GUI/Field.hpp" +#include "libslic3r/LocalesUtils.hpp" +#include "test_utils.hpp" + +#include +#include +#include +#include +#include + +using namespace Slic3r; +using namespace Slic3r::GUI; +using Catch::Matchers::WithinAbs; + +TEST_CASE("Numbers drop trailing zeros when the C locale writes a comma and the UI locale a point", "[Field]") +{ + CommaNumericLocale comma; + CNumericLocalesSetter outer; + if (!comma.apply()) + SKIP("no locale with a comma decimal separator is installed"); + if (wxNumberFormatter::GetDecimalSeparator() != '.') + SKIP("the UI locale does not write a decimal point"); + + CHECK(double_to_string(0.2) == wxString("0.2")); + CHECK(double_to_string(0.42) == wxString("0.42")); + CHECK(double_to_string(100.) == wxString("100")); +} + +TEST_CASE("Field numbers parse back whichever decimal separator they show", "[Field]") +{ + CommaNumericLocale comma; + CNumericLocalesSetter outer; + if (!comma.apply()) + SKIP("no locale with a comma decimal separator is installed"); + + double value = 0.; + // As point fields write it, in the UI locale. + REQUIRE(string_to_double_any_separator(wxNumberFormatter::ToString(0.5, 2, wxNumberFormatter::Style_None), &value)); + CHECK_THAT(value, WithinAbs(0.5, 1e-12)); + REQUIRE(string_to_double_any_separator("0.25", &value)); + CHECK_THAT(value, WithinAbs(0.25, 1e-12)); + REQUIRE(string_to_double_any_separator("0,25", &value)); + CHECK_THAT(value, WithinAbs(0.25, 1e-12)); + REQUIRE(string_to_double_any_separator("-1,5", &value)); + CHECK_THAT(value, WithinAbs(-1.5, 1e-12)); + // Accepted by ToDouble before, so typing it must keep working. + REQUIRE(string_to_double_any_separator("0.", &value)); + CHECK_THAT(value, WithinAbs(0., 1e-12)); + CHECK_FALSE(string_to_double_any_separator("abc", &value)); +} From 1e1543f006a64c9a249535ae2c8a7071c6c0830a Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:41:42 +0800 Subject: [PATCH 18/36] Read the CFS Lite Slots a SPARKX i7 Sends After Reporting No CFS (#17702) A SPARKX i7 with a CFS Lite reports "cfsConnect": 0 and then answers the slot query. The query stopped at that status, so filament sync found no slots. It now keeps reading for a short no-CFS deadline and treats the printer as having no CFS only when no slots arrive. --- src/slic3r/Utils/CrealityPrint.cpp | 34 ++++++++++++++-------- src/slic3r/Utils/CrealityPrint.hpp | 13 +++++---- tests/slic3rutils/test_creality_print.cpp | 35 +++++++++++++++++------ 3 files changed, 56 insertions(+), 26 deletions(-) diff --git a/src/slic3r/Utils/CrealityPrint.cpp b/src/slic3r/Utils/CrealityPrint.cpp index 4b492718c1..bd50cf949d 100644 --- a/src/slic3r/Utils/CrealityPrint.cpp +++ b/src/slic3r/Utils/CrealityPrint.cpp @@ -278,16 +278,20 @@ static int reported_cfs_connect(const std::string& msg) return cfs_connect == 1 ? 1 : -1; } -// Sends the CFS slot query and returns the reply, or nothing once a status reports no CFS connected, which also sets *no_cfs. +// Sends the CFS slot query and returns the reply, or nothing when none arrives in time. // 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. +// A status reporting no CFS connected cuts the wait to no_cfs_reply from then, and sets *no_cfs if no reply follows: a SPARKX i7 +// reports no CFS connected for its CFS Lite and still sends the slots. static std::string ws_query_slots(net::io_context& ioc, websocket::stream& ws, std::chrono::milliseconds slots_reply, std::chrono::milliseconds cfs_reply, + std::chrono::milliseconds no_cfs_reply, bool* no_cfs) { - const auto sent = std::chrono::steady_clock::now(); - auto deadline = sent + slots_reply; + const auto sent = std::chrono::steady_clock::now(); + auto deadline = sent + slots_reply; + bool reported_no_cfs = false; beast::get_lowest_layer(ws).expires_at(deadline); ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"boxsInfo", 1}}}}); @@ -309,16 +313,22 @@ static std::string ws_query_slots(net::io_context& ioc, if (msg.find("boxsInfo") != std::string::npos) return msg; const int cfs_connect = reported_cfs_connect(msg); - if (cfs_connect == 0) { - BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer reports no CFS connected"; - if (no_cfs) - *no_cfs = true; - return {}; - } - if (cfs_connect == 1) { - deadline = sent + std::max(slots_reply, cfs_reply); + if (cfs_connect == 0 && !reported_no_cfs) { + reported_no_cfs = true; + deadline = std::min(deadline, std::chrono::steady_clock::now() + no_cfs_reply); beast::get_lowest_layer(ws).expires_at(deadline); } + if (cfs_connect == 1) { + reported_no_cfs = false; + deadline = sent + std::max(slots_reply, cfs_reply); + beast::get_lowest_layer(ws).expires_at(deadline); + } + } + if (reported_no_cfs) { + BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer reports no CFS connected"; + if (no_cfs) + *no_cfs = true; + return {}; } BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a 'boxsInfo' response"; return {}; @@ -420,7 +430,7 @@ std::string CrealityPrint::query_boxes_info(bool* no_cfs) const websocket::stream ws{ioc}; ws_connect(ioc, ws, m_host, ws_settings.port, ws_settings.connect); - std::string result = ws_query_slots(ioc, ws, ws_settings.slots_reply, ws_settings.reply, no_cfs); + std::string result = ws_query_slots(ioc, ws, ws_settings.slots_reply, ws_settings.reply, ws_settings.no_cfs_reply, no_cfs); ws_close(ioc, ws, ws_settings.close); return result; diff --git a/src/slic3r/Utils/CrealityPrint.hpp b/src/slic3r/Utils/CrealityPrint.hpp index 060581a89b..77b62f925d 100644 --- a/src/slic3r/Utils/CrealityPrint.hpp +++ b/src/slic3r/Utils/CrealityPrint.hpp @@ -21,7 +21,7 @@ struct CrealityPrinterInfo { bool reachable{false}; bool multi_color{false}; - bool no_cfs{false}; // The printer reports that no CFS is connected + bool no_cfs{false}; // The printer reports that no CFS is connected and lists no slots std::string model_name; std::string boxes_json; // Empty unless the printer lists its CFS slots }; @@ -49,7 +49,7 @@ 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); - // Sets *no_cfs to whether the printer reports that no CFS is connected. + // Sets *no_cfs when the printer reports that no CFS is connected and then lists no slots. 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; @@ -66,10 +66,11 @@ 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 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 + 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 no_cfs_reply{std::chrono::seconds(2)}; // The CFS slot query once a status reports no CFS connected + std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake } ws_settings; private: diff --git a/tests/slic3rutils/test_creality_print.cpp b/tests/slic3rutils/test_creality_print.cpp index 0859154ad8..afcca252a9 100644 --- a/tests/slic3rutils/test_creality_print.cpp +++ b/tests/slic3rutils/test_creality_print.cpp @@ -60,6 +60,7 @@ enum class Behavior { 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 + ReportsNoCfsThenSlots, // Sends a status reporting no CFS connected, then the CFS slots, as a SPARKX i7 with a CFS Lite does 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 @@ -175,6 +176,12 @@ private: wait_for_release(); return; } + if (first && m_behavior == Behavior::ReportsNoCfsThenSlots) { + ws.write(net::buffer(std::string(R"({"cfsConnect":0,"nozzleTemp":"25.000000"})")), ec); + ws.write(net::buffer(std::string(R"({"connectionCount":1})")), ec); + ws.write(net::buffer(slots), ec); + continue; + } 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) { @@ -262,13 +269,14 @@ DynamicPrintConfig host_config(const std::string& url) 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; + 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.no_cfs_reply = deadline; + host->ws_settings.close = deadline; return host; } @@ -319,6 +327,7 @@ TEST_CASE("The CFS slot query has a shorter default deadline than a command", "[ const TestHost host(&config); CHECK(host.ws_settings.slots_reply < host.ws_settings.reply); + CHECK(host.ws_settings.no_cfs_reply < host.ws_settings.slots_reply); } TEST_CASE("Querying the CFS slots waits on a silent printer for the slot deadline, not the command one", "[CrealityPrint]") @@ -332,7 +341,7 @@ TEST_CASE("Querying the CFS slots waits on a silent printer for the slot deadlin CHECK(reply.empty()); } -TEST_CASE("Querying the CFS slots stops at a status reporting no CFS connected", "[CrealityPrint]") +TEST_CASE("Querying the CFS slots waits only the no-CFS deadline after a status reporting no CFS connected", "[CrealityPrint]") { FakeCrealityPrinter printer(Behavior::ReportsNoCfs, "K1C"); const auto host = make_host(printer, 200ms); @@ -343,6 +352,16 @@ TEST_CASE("Querying the CFS slots stops at a status reporting no CFS connected", CHECK(reply.empty()); } +TEST_CASE("Querying the CFS slots reads the slots sent after a status reporting no CFS connected", "[CrealityPrint]") +{ + FakeCrealityPrinter printer(Behavior::ReportsNoCfsThenSlots, "F022"); + 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("Querying the CFS slots waits past a status reporting a CFS connected", "[CrealityPrint]") { FakeCrealityPrinter printer(Behavior::ReportsCfs, "K1C"); From 0d7bea5763aa5e18cbfb67aa7ae73431a689e409 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:44:04 +0800 Subject: [PATCH 19/36] List and Load Resource Textures Whose Paths Pass MAX_PATH on Windows (#17730) * Test Resource Textures Whose Paths Pass MAX_PATH * List and Load Resource Textures Whose Paths Pass MAX_PATH on Windows --- src/slic3r/GUI/TextureLibrary.cpp | 11 +++- src/slic3r/plugin/PluginFsUtils.cpp | 14 ++++- .../test_plugin_resource_texture.cpp | 56 +++++++++++++++++++ 3 files changed, 75 insertions(+), 6 deletions(-) diff --git a/src/slic3r/GUI/TextureLibrary.cpp b/src/slic3r/GUI/TextureLibrary.cpp index 3d76791027..08e3935084 100644 --- a/src/slic3r/GUI/TextureLibrary.cpp +++ b/src/slic3r/GUI/TextureLibrary.cpp @@ -17,6 +17,8 @@ #include #include +#include +#include #include #include #include @@ -219,7 +221,8 @@ wxImage image_from_decoded(const DecodedHeightTexture &image, std::vector read_file_bytes(const std::string &path) { - std::ifstream ifs(path, std::ios::binary); + // A plugin pack can extract a texture past Windows' MAX_PATH, which only extended_path() reaches. + boost::filesystem::ifstream ifs(extended_path(boost::filesystem::path(path)), std::ios::binary); return std::vector(std::istreambuf_iterator(ifs), std::istreambuf_iterator()); } @@ -451,8 +454,10 @@ std::shared_ptr> load_texture_image_data(const std::s // Not a PNG at all (a jpg somebody copied into the folder by hand, say): convert it the same way // an import would - keeping its colour if it has any - but leave the file on disk alone. - wxImage image; - if (!image.LoadFile(from_u8(path)) || !image.IsOk()) { + // Decoded from the bytes already read: reopening the file by name would hit MAX_PATH again. + wxImage image; + wxMemoryInputStream stream(bytes.data(), bytes.size()); + if (!image.LoadFile(stream) || !image.IsOk()) { error = _u8L("Could not load the selected image."); return nullptr; } diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index a1215949a3..dea29d3e82 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -1701,8 +1701,12 @@ std::vector collect_resource_texture_files(const std::string& dir, for (fs::directory_iterator it(resolved_dir, ec), end; it != end && !ec; it.increment(ec)) { const fs::path& path = it->path(); + // Plugin extraction writes through extended_path(), so a pack file can sit past Windows' + // MAX_PATH; the plain path cannot reach it there. + const fs::path io_path = extended_path(path); + boost::system::error_code file_ec; - if (!fs::is_regular_file(path, ec) || ec) + if (!fs::is_regular_file(io_path, file_ec) || file_ec) continue; std::string ext = path.extension().string(); @@ -1710,8 +1714,12 @@ std::vector collect_resource_texture_files(const std::string& dir, if (ext != ".png" && ext != ".jpg" && ext != ".jpeg" && ext != ".bmp") continue; - // Re-check per file: a symlink inside the pack must not resolve outside it. - if (!is_inside_allowed_root(path, resolved_root)) + // Re-check per file: a symlink inside the pack must not resolve outside it. Any other entry is a + // direct child of resolved_dir, checked above. is_inside_allowed_root() resolves the plain path, + // so a symlink that path cannot reach is refused rather than trusted. + const fs::file_status status = fs::symlink_status(io_path, file_ec); + if (file_ec || (fs::is_symlink(status) && (!fs::exists(path, file_ec) || file_ec || + !is_inside_allowed_root(path, resolved_root)))) continue; files.push_back(path.string()); diff --git a/tests/slic3rutils/test_plugin_resource_texture.cpp b/tests/slic3rutils/test_plugin_resource_texture.cpp index c4c9feab9e..951cd4b591 100644 --- a/tests/slic3rutils/test_plugin_resource_texture.cpp +++ b/tests/slic3rutils/test_plugin_resource_texture.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include @@ -305,6 +306,26 @@ bool load_project(const std::string& path, Model& model, const ScopedTemporaryDi return loaded; } +// A gray texture (".png", or ".bmp" for the decode fallback) whose full path is longer than the +// 260-character MAX_PATH the Win32 APIs enforce when LongPathsEnabled is off. A 240-character name stays +// under the NTFS 255 limit per component. It is written through extended_path(), as plugin extraction +// writes it. +fs::path write_long_path_texture(const fs::path& dir, const std::string& ext = ".png") +{ + const fs::path file = dir / (std::string(240, 'a') + ext); + REQUIRE(file.string().size() > 260); + + ScopedTemporaryDir staging("tex-long-src"); + const fs::path source = staging.path() / ("src" + ext); + if (ext == ".bmp") + write_bytes(source, make_gray_bmp(4, 4, 128)); + else + write_gray_png(source, 128); + fs::create_directories(dir); + fs::copy_file(source, extended_path(file)); + return file; +} + } // namespace // ── Validation (collect_resource_texture_files, no Python) ────────────────────────────────────── @@ -323,6 +344,41 @@ TEST_CASE("A texture file directly inside the plugin folder is listed", "[Plugin CHECK(fs::path(files.front()).filename() == "grain.png"); } +TEST_CASE("A texture whose full path is longer than MAX_PATH is listed", "[PluginResourceTexture]") +{ + ScopedTemporaryDir root("tex-long"); + const fs::path file = write_long_path_texture(root.path() / "textures"); + + std::string error; + const std::vector files = + collect_resource_texture_files((root.path() / "textures").string(), root.string(), error); + + CHECK(error.empty()); + REQUIRE(files.size() == 1); + CHECK(fs::path(files.front()).filename() == file.filename()); + + // ScopedTemporaryDir's plain remove_all cannot reach past MAX_PATH on Windows. + fs::remove(extended_path(file)); +} + +TEST_CASE("A texture whose full path is longer than MAX_PATH loads", "[PluginResourceTexture]") +{ + ensure_wx_image_handlers(); + const std::string ext = GENERATE(".png", ".bmp"); + ScopedTemporaryDir root("tex-long"); + const fs::path file = write_long_path_texture(root.path() / "textures", ext); + + std::string error; + const auto bytes = GUI::load_texture_image_data(file.string(), error); + + CHECK(error.empty()); + REQUIRE(bytes != nullptr); + CHECK_FALSE(bytes->empty()); + + // ScopedTemporaryDir's plain remove_all cannot reach past MAX_PATH on Windows. + fs::remove(extended_path(file)); +} + TEST_CASE("A directory reached with a parent-directory escape is refused", "[PluginResourceTexture]") { ScopedTemporaryDir parent("tex-escape"); From cdd695117fe1ffc5f663c48d33b36e5afabe8efb Mon Sep 17 00:00:00 2001 From: Rodrigo Faselli <162915171+RF47@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:05:58 -0300 Subject: [PATCH 20/36] Fix cone seam pcurve selection in OCCT (#17720) Since the OCCT 8.0.1 update, some STEP files imported with cone faces missing. OCCT told the two seam pcurves of a cone apart with a 1e-7 threshold, which fails when the neighboring pcurves end slightly past the seam. The OCCT patch now picks the closer pcurve. The #16290 fix is kept. Also stops admesh from merging unrelated edges of open meshes from STEP and SVG import on ARM64. A mesh built in memory reaches the nearby check with a tolerance of 0, and dividing by it was undefined. The check now returns early, which is what x86-64 already did. --- ...epMesh-seam-pcurve-at-edge-parameter.patch | 28 -- .../0001-BRepMesh-seam-pcurve-selection.patch | 25 ++ deps/OCCT/OCCT.cmake | 8 +- deps_src/admesh/connect.cpp | 6 + tests/data/cone_band_seam_overshoot.step | 408 ++++++++++++++++++ tests/libslic3r/test_step.cpp | 27 ++ 6 files changed, 471 insertions(+), 31 deletions(-) delete mode 100644 deps/OCCT/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch create mode 100644 deps/OCCT/0001-BRepMesh-seam-pcurve-selection.patch create mode 100644 tests/data/cone_band_seam_overshoot.step diff --git a/deps/OCCT/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch b/deps/OCCT/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch deleted file mode 100644 index 84c599a5f3..0000000000 --- a/deps/OCCT/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch +++ /dev/null @@ -1,28 +0,0 @@ -diff --git a/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx b/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx -index 6f63781..9b1c08e 100644 ---- a/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx -+++ b/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx -@@ -210,10 +210,10 @@ private: - - // Define two pcurves of the seam-edge. - occ::handle aPC1, aPC2; -- double af, al; -+ double af, al, af1, al1; - - aE.Orientation(TopAbs_FORWARD); -- aPC1 = BRep_Tool::CurveOnSurface(aE, aF, af, al); -+ aPC1 = BRep_Tool::CurveOnSurface(aE, aF, af1, al1); - - aE.Orientation(TopAbs_REVERSED); - aPC2 = BRep_Tool::CurveOnSurface(aE, aF, af, al); -@@ -224,7 +224,9 @@ private: - } - - // Select the correct pcurve of the seam-edge. -- const gp_Pnt2d& aFPntOfPC1 = aPC1->Value(aPC1->FirstParameter()); -+ // Use the edge's first parameter. A Geom2d_Line's FirstParameter() is -Precision::Infinite(), -+ // where a direction of (2e-16, -1) from rounding error gives an X far outside the U range. -+ const gp_Pnt2d aFPntOfPC1 = aPC1->Value(af1); - - if (std::abs(aLPntOfIPC1.X() - aFPntOfPC1.X()) > Precision::Confusion()) - { diff --git a/deps/OCCT/0001-BRepMesh-seam-pcurve-selection.patch b/deps/OCCT/0001-BRepMesh-seam-pcurve-selection.patch new file mode 100644 index 0000000000..dc202d1827 --- /dev/null +++ b/deps/OCCT/0001-BRepMesh-seam-pcurve-selection.patch @@ -0,0 +1,25 @@ +diff --git a/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx b/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx +index 6f63781..97a20d3 100644 +--- a/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx ++++ b/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx +@@ -223,10 +223,16 @@ private: + return false; + } + +- // Select the correct pcurve of the seam-edge. +- const gp_Pnt2d& aFPntOfPC1 = aPC1->Value(aPC1->FirstParameter()); +- +- if (std::abs(aLPntOfIPC1.X() - aFPntOfPC1.X()) > Precision::Confusion()) ++ // Select the correct pcurve of the seam-edge: the one closer to the discrete pcurve. ++ // Both pcurves of a seam share the edge's range, so evaluate them at its start. A ++ // Geom2d_Line's FirstParameter() is -Precision::Infinite(), where a direction of (2e-16, -1) ++ // from rounding error gives an X far outside the U range. A Precision::Confusion() threshold ++ // fails too, because BRepMesh_ModelHealer has already moved the ends of the discrete pcurve ++ // onto those of the neighbouring edges, whose pcurves can end slightly past the seam. ++ const gp_Pnt2d aFPntOfPC1 = aPC1->Value(af); ++ const gp_Pnt2d aFPntOfPC2 = aPC2->Value(af); ++ ++ if (std::abs(aLPntOfIPC1.X() - aFPntOfPC1.X()) > std::abs(aLPntOfIPC1.X() - aFPntOfPC2.X())) + { + std::swap(aPC1, aPC2); + } diff --git a/deps/OCCT/OCCT.cmake b/deps/OCCT/OCCT.cmake index d41b3bd886..fed828ad54 100644 --- a/deps/OCCT/OCCT.cmake +++ b/deps/OCCT/OCCT.cmake @@ -48,12 +48,14 @@ endif () orcaslicer_add_cmake_project(OCCT URL https://github.com/Open-Cascade-SAS/OCCT/archive/refs/tags/V8_0_1.zip URL_HASH SHA256=7c033d917ee8f040c0512d289dcc5f02c148889d5bac17c3e25639accb44f0da - # Makes BRepMesh triangulate cone faces whose seam pcurve is slightly tilted - # (Open-Cascade-SAS/OCCT#572); remove the patch once an OCCT release includes the fix. + # 0001 makes BRepMesh pair each seam pcurve of a cone with the right side of the seam, which + # failed when the seam pcurve is slightly tilted (Open-Cascade-SAS/OCCT#572) or the adjacent + # pcurves end slightly past the seam. Either way the face meshed to a sliver or not at all. + # Remove the patch once an OCCT release includes the fix. # 0002 compiles one file without optimization under cl for ARM64, where MSVC 14.52 crashes # on it with an internal compiler error; remove it once the runner image ships a fixed MSVC. PATCH_COMMAND git apply ${OCCT_DIRECTORY_FLAG} --verbose --ignore-space-change --whitespace=fix - ${CMAKE_CURRENT_LIST_DIR}/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch + ${CMAKE_CURRENT_LIST_DIR}/0001-BRepMesh-seam-pcurve-selection.patch ${CMAKE_CURRENT_LIST_DIR}/0002-BRepGraph-MSVC-ARM64-ICE-workaround.patch #DEPENDS dep_Boost CMAKE_ARGS diff --git a/deps_src/admesh/connect.cpp b/deps_src/admesh/connect.cpp index 30a199120d..d0a3f909b6 100644 --- a/deps_src/admesh/connect.cpp +++ b/deps_src/admesh/connect.cpp @@ -488,6 +488,12 @@ void stl_check_facets_nearby(stl_file *stl, float tolerance) // No need to check any further. All facets are connected. return; + // A mesh built in memory has no shortest edge, so the tolerance arrives as 0, and load_nearby() would divide by it. + // Converting the infinities and NaNs to int is undefined: x86-64 makes them all INT_MIN, so no edge was ever + // matched, while ARM64 saturates them by sign and merged unrelated edges. Keep the x86-64 result everywhere. + if (!(tolerance > 0.f)) + return; + HashTableEdges hash_table(stl->stats.number_of_facets); for (uint32_t i = 0; i < stl->stats.number_of_facets; ++ i) { //FIXME is the copy necessary? diff --git a/tests/data/cone_band_seam_overshoot.step b/tests/data/cone_band_seam_overshoot.step new file mode 100644 index 0000000000..e7b580aa2b --- /dev/null +++ b/tests/data/cone_band_seam_overshoot.step @@ -0,0 +1,408 @@ +ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('Open CASCADE Model'),'2;1'); +FILE_NAME('Open CASCADE Shape Model','2026-11-19T16:06:59',('Author'),( + 'Open CASCADE'),'Open CASCADE STEP processor 8.0','Open CASCADE 8.0' + ,'Unknown'); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#1 = APPLICATION_PROTOCOL_DEFINITION('international standard', + 'automotive_design',2000,#2); +#2 = APPLICATION_CONTEXT( + 'core data for automotive mechanical design processes'); +#3 = SHAPE_DEFINITION_REPRESENTATION(#4,#10); +#4 = PRODUCT_DEFINITION_SHAPE('','',#5); +#5 = PRODUCT_DEFINITION('design','',#6,#9); +#6 = PRODUCT_DEFINITION_FORMATION('','',#7); +#7 = PRODUCT('Open CASCADE STEP translator 8.0 1', + 'Open CASCADE STEP translator 8.0 1','',(#8)); +#8 = PRODUCT_CONTEXT('',#2,'mechanical'); +#9 = PRODUCT_DEFINITION_CONTEXT('part definition',#2,'design'); +#10 = MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#11,#15),#225); +#11 = AXIS2_PLACEMENT_3D('',#12,#13,#14); +#12 = CARTESIAN_POINT('',(0.,0.,0.)); +#13 = DIRECTION('',(0.,0.,1.)); +#14 = DIRECTION('',(1.,0.,-0.)); +#15 = SHELL_BASED_SURFACE_MODEL('',(#16)); +#16 = OPEN_SHELL('',(#17)); +#17 = ADVANCED_FACE('',(#18),#51,.T.); +#18 = FACE_BOUND('',#19,.T.); +#19 = EDGE_LOOP('',(#20,#61,#84,#118,#136,#171,#172,#209)); +#20 = ORIENTED_EDGE('',*,*,#21,.T.); +#21 = EDGE_CURVE('',#22,#24,#26,.T.); +#22 = VERTEX_POINT('',#23); +#23 = CARTESIAN_POINT('',(4.143759803741,-4.874444458849,69.872014613543 + )); +#24 = VERTEX_POINT('',#25); +#25 = CARTESIAN_POINT('',(-12.29864740029,-3.981026217535, + 68.506159421151)); +#26 = SURFACE_CURVE('',#27,(#50),.PCURVE_S1.); +#27 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#28,#29,#30,#31,#32,#33,#34,#35, + #36,#37,#38,#39,#40,#41,#42,#43,#44,#45,#46,#47,#48,#49), + .UNSPECIFIED.,.F.,.F.,(4,3,3,3,3,3,3,4),(0.,0.37190743837, + 0.74381487674,1.11572231511,1.48762975348,1.983506337973, + 2.23144463022,2.529141946975),.UNSPECIFIED.); +#28 = CARTESIAN_POINT('',(4.143759803725,-4.874444458851,69.872014613543 + )); +#29 = CARTESIAN_POINT('',(4.029039479458,-6.099264561044,69.754781673223 + )); +#30 = CARTESIAN_POINT('',(3.635412845026,-7.295135950986,69.615587068332 + )); +#31 = CARTESIAN_POINT('',(3.000986439986,-8.345127490291,69.468007573028 + )); +#32 = CARTESIAN_POINT('',(2.366560034947,-9.395119029597,69.320428077723 + )); +#33 = CARTESIAN_POINT('',(1.491333859301,-10.29923071826,69.164463692005 + )); +#34 = CARTESIAN_POINT('',(0.462690190863,-10.96670470189,69.015728860463 + )); +#35 = CARTESIAN_POINT('',(-0.565953477574,-11.63417868553,68.86699402892 + )); +#36 = CARTESIAN_POINT('',(-1.748014638803,-12.06501496412, + 68.725488751553)); +#37 = CARTESIAN_POINT('',(-2.968374982818,-12.21880646908, + 68.604858207553)); +#38 = CARTESIAN_POINT('',(-4.188735326832,-12.37259797405, + 68.484227663552)); +#39 = CARTESIAN_POINT('',(-5.447394853632,-12.24934470538, + 68.384471852918)); +#40 = CARTESIAN_POINT('',(-6.616838482239,-11.85783039067,68.31602103766 + )); +#41 = CARTESIAN_POINT('',(-8.176096653714,-11.33581130439, + 68.224753283981)); +#42 = CARTESIAN_POINT('',(-9.576748783956,-10.33688369181, + 68.189138855415)); +#43 = CARTESIAN_POINT('',(-10.58137693017,-9.031652960205,68.21510243469 + )); +#44 = CARTESIAN_POINT('',(-11.08369100327,-8.379037594403, + 68.228084224327)); +#45 = CARTESIAN_POINT('',(-11.48699908037,-7.649846448845, + 68.256460515925)); +#46 = CARTESIAN_POINT('',(-11.77442415228,-6.878633185846, + 68.298690442896)); +#47 = CARTESIAN_POINT('',(-12.11953289646,-5.952644235287, + 68.349395543072)); +#48 = CARTESIAN_POINT('',(-12.29757783178,-4.966073709505,68.42007286513 + )); +#49 = CARTESIAN_POINT('',(-12.29864740029,-3.981026217535, + 68.506159421151)); +#50 = PCURVE('',#51,#56); +#51 = CONICAL_SURFACE('',#52,8.25,1.666512371394E-02); +#52 = AXIS2_PLACEMENT_3D('',#53,#54,#55); +#53 = CARTESIAN_POINT('',(-4.167416546478,-4.151558268342, + 70.452528145107)); +#54 = DIRECTION('',(8.715574274766E-02,8.682408883347E-02, + -0.992403876506)); +#55 = DIRECTION('',(0.996194698092,-7.596123493896E-03, + 8.682408883347E-02)); +#56 = DEFINITIONAL_REPRESENTATION('',(#57),#60); +#57 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#58,#59),.UNSPECIFIED.,.F.,.F.,(2, + 2),(0.,2.529141946975),.PIECEWISE_BEZIER_KNOTS.); +#58 = CARTESIAN_POINT('',(6.376509579999,1.237706692175)); +#59 = CARTESIAN_POINT('',(9.424807694257,1.237705820714)); +#60 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2) +PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE','' + ) ); +#61 = ORIENTED_EDGE('',*,*,#62,.T.); +#62 = EDGE_CURVE('',#24,#63,#65,.T.); +#63 = VERTEX_POINT('',#64); +#64 = CARTESIAN_POINT('',(-11.8668393524,-3.459571861966,62.542838503986 + )); +#65 = SEAM_CURVE('',#66,(#70,#77),.PCURVE_S1.); +#66 = LINE('',#67,#68); +#67 = CARTESIAN_POINT('',(-12.38602280573,-4.088890249517, + 69.736229412231)); +#68 = VECTOR('',#69,1.); +#69 = DIRECTION('',(7.054270086241E-02,8.69386169222E-02,-0.993712938551 + )); +#70 = PCURVE('',#51,#71); +#71 = DEFINITIONAL_REPRESENTATION('',(#72),#76); +#72 = LINE('',#73,#74); +#73 = CARTESIAN_POINT('',(9.424777960769,-3.3302065773E-15)); +#74 = VECTOR('',#75,1.); +#75 = DIRECTION('',(0.,1.)); +#76 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2) +PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE','' + ) ); +#77 = PCURVE('',#51,#78); +#78 = DEFINITIONAL_REPRESENTATION('',(#79),#83); +#79 = LINE('',#80,#81); +#80 = CARTESIAN_POINT('',(3.14159265359,-3.3302065773E-15)); +#81 = VECTOR('',#82,1.); +#82 = DIRECTION('',(0.,1.)); +#83 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2) +PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE','' + ) ); +#84 = ORIENTED_EDGE('',*,*,#85,.T.); +#85 = EDGE_CURVE('',#63,#86,#88,.T.); +#86 = VERTEX_POINT('',#87); +#87 = CARTESIAN_POINT('',(4.75702271724,-4.453754621641,63.91581382788) + ); +#88 = SURFACE_CURVE('',#89,(#112),.PCURVE_S1.); +#89 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#90,#91,#92,#93,#94,#95,#96,#97, + #98,#99,#100,#101,#102,#103,#104,#105,#106,#107,#108,#109,#110,#111) + ,.UNSPECIFIED.,.F.,.F.,(4,3,3,3,3,3,3,4),(2.718902929729, + 3.010964145992,3.261821852983,3.763537266966,4.139823827454, + 4.516110387941,4.892396948428,5.268683508916),.UNSPECIFIED.); +#90 = CARTESIAN_POINT('',(-11.86683935239,-3.459571861965, + 62.542838503986)); +#91 = CARTESIAN_POINT('',(-11.86937709332,-4.426034233901, + 62.458061131061)); +#92 = CARTESIAN_POINT('',(-11.70896301475,-5.393774766903, + 62.387482827713)); +#93 = CARTESIAN_POINT('',(-11.38149547781,-6.306025299713,62.33643038214 + )); +#94 = CARTESIAN_POINT('',(-11.10022651481,-7.089577048867,62.29258033044 + )); +#95 = CARTESIAN_POINT('',(-10.69571445902,-7.832191248394, + 62.263135410637)); +#96 = CARTESIAN_POINT('',(-10.19237858665,-8.49827843209,62.249064726986 + )); +#97 = CARTESIAN_POINT('',(-9.185706841918,-9.83045279948,62.220923359685 + )); +#98 = CARTESIAN_POINT('',(-7.783739830833,-10.85651910354, + 62.254278936995)); +#99 = CARTESIAN_POINT('',(-6.211992111038,-11.40193452483, + 62.344596644395)); +#100 = CARTESIAN_POINT('',(-5.033181321192,-11.8109960908, + 62.412334924946)); +#101 = CARTESIAN_POINT('',(-3.758868882695,-11.9496915352, + 62.512114403672)); +#102 = CARTESIAN_POINT('',(-2.521619747312,-11.80753342024, + 62.633210379822)); +#103 = CARTESIAN_POINT('',(-1.284370611928,-11.66537530528, + 62.754306355971)); +#104 = CARTESIAN_POINT('',(-8.418477965762E-02,-11.24236363094, + 62.896718829545)); +#105 = CARTESIAN_POINT('',(0.964036704717,-10.57823477998,63.04688037961 + )); +#106 = CARTESIAN_POINT('',(2.012258189092,-9.91410592903,63.197041929676 + )); +#107 = CARTESIAN_POINT('',(2.908515325572,-9.008859901449, + 63.354952556234)); +#108 = CARTESIAN_POINT('',(3.562304174523,-7.953319785154, + 63.504717954247)); +#109 = CARTESIAN_POINT('',(4.216093023475,-6.897779668859,63.65448335226 + )); +#110 = CARTESIAN_POINT('',(4.627413584898,-5.691945463852, + 63.796103521729)); +#111 = CARTESIAN_POINT('',(4.757022717202,-4.453754621644, + 63.915813827868)); +#112 = PCURVE('',#51,#113); +#113 = DEFINITIONAL_REPRESENTATION('',(#114),#117); +#114 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#115,#116),.UNSPECIFIED.,.F.,.F., + (2,2),(2.718902929729,5.268683508916),.PIECEWISE_BEZIER_KNOTS.); +#115 = CARTESIAN_POINT('',(9.424775367365,7.238497013832)); +#116 = CARTESIAN_POINT('',(6.387399122293,7.238638837649)); +#117 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2) +PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE','' + ) ); +#118 = ORIENTED_EDGE('',*,*,#119,.T.); +#119 = EDGE_CURVE('',#86,#120,#122,.T.); +#120 = VERTEX_POINT('',#121); +#121 = CARTESIAN_POINT('',(4.763507424532,-4.389388517509, + 63.922014637813)); +#122 = SURFACE_CURVE('',#123,(#130),.PCURVE_S1.); +#123 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#124,#125,#126,#127,#128,#129), + .UNSPECIFIED.,.F.,.F.,(4,2,4),(0.,3.249430989361E-03, + 6.498861978722E-03),.UNSPECIFIED.); +#124 = CARTESIAN_POINT('',(4.757022717206,-4.453754621644, + 63.915813827868)); +#125 = CARTESIAN_POINT('',(4.758145172852,-4.443031501464, + 63.916850556582)); +#126 = CARTESIAN_POINT('',(4.759246797592,-4.432306053903, + 63.917885659486)); +#127 = CARTESIAN_POINT('',(4.761408372809,-4.410850625235, + 63.919952601975)); +#128 = CARTESIAN_POINT('',(4.762468321249,-4.400120664336, + 63.920984439613)); +#129 = CARTESIAN_POINT('',(4.763507424532,-4.389388517509, + 63.922014637813)); +#130 = PCURVE('',#51,#131); +#131 = DEFINITIONAL_REPRESENTATION('',(#132),#135); +#132 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#133,#134),.UNSPECIFIED.,.F.,.F., + (2,2),(0.,6.498861978722E-03),.PIECEWISE_BEZIER_KNOTS.); +#133 = CARTESIAN_POINT('',(6.387399122293,7.238638837649)); +#134 = CARTESIAN_POINT('',(6.379635251372,7.238638837649)); +#135 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2) +PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE','' + ) ); +#136 = ORIENTED_EDGE('',*,*,#137,.T.); +#137 = EDGE_CURVE('',#120,#63,#138,.T.); +#138 = SURFACE_CURVE('',#139,(#165),.PCURVE_S1.); +#139 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#140,#141,#142,#143,#144,#145, + #146,#147,#148,#149,#150,#151,#152,#153,#154,#155,#156,#157,#158, + #159,#160,#161,#162,#163,#164),.UNSPECIFIED.,.F.,.F.,(4,3,3,3,3,3,3, + 3,4),(0.,0.376379539117,0.752759078234,1.129138617351,1.505518156469 + ,1.881897695586,2.164182349923,2.258277234703,2.718902929729), + .UNSPECIFIED.); +#140 = CARTESIAN_POINT('',(4.763507424532,-4.389388517509, + 63.922014637813)); +#141 = CARTESIAN_POINT('',(4.883491920427,-3.150155374883, + 64.040970870365)); +#142 = CARTESIAN_POINT('',(4.720833010841,-1.881926911817, + 64.137641313649)); +#143 = CARTESIAN_POINT('',(4.29177713392,-0.709212197811,64.202559644177 + )); +#144 = CARTESIAN_POINT('',(3.862721257,0.463502516196,64.267477974704)); +#145 = CARTESIAN_POINT('',(3.167268412747,1.540703481143,64.300644192476 + )); +#146 = CARTESIAN_POINT('',(2.273495756837,2.415374288815,64.298674305201 + )); +#147 = CARTESIAN_POINT('',(1.379723100927,3.290045096488,64.296704417926 + )); +#148 = CARTESIAN_POINT('',(0.287630633361,3.962185746887,64.259598425604 + )); +#149 = CARTESIAN_POINT('',(-0.893605154041,4.365900727323,64.19117940922 + )); +#150 = CARTESIAN_POINT('',(-2.074840941442,4.769615707759, + 64.122760392836)); +#151 = CARTESIAN_POINT('',(-3.345220048677,4.904905018232, + 64.023028352389)); +#152 = CARTESIAN_POINT('',(-4.58171278018,4.758163349392,63.901597796786 + )); +#153 = CARTESIAN_POINT('',(-5.818205511682,4.611421680552, + 63.780167241183)); +#154 = CARTESIAN_POINT('',(-7.02081186745,4.1826490324,63.637038170423) + ); +#155 = CARTESIAN_POINT('',(-8.065522144736,3.514301141115, + 63.486815866392)); +#156 = CARTESIAN_POINT('',(-8.849054852701,3.013040222651,63.37414913837 + )); +#157 = CARTESIAN_POINT('',(-9.543771016519,2.377018229924, + 63.257492466632)); +#158 = CARTESIAN_POINT('',(-10.1208386321,1.644000024014,63.142681957346 + )); +#159 = CARTESIAN_POINT('',(-10.31319450396,1.399660622043, + 63.104411787584)); +#160 = CARTESIAN_POINT('',(-10.49247831491,1.144543863053, + 63.066346746984)); +#161 = CARTESIAN_POINT('',(-10.6555275489,0.880008227365,63.028883428364 + )); +#162 = CARTESIAN_POINT('',(-11.45370767211,-0.41498151978, + 62.845488048078)); +#163 = CARTESIAN_POINT('',(-11.86283793131,-1.935687816598, + 62.676512498712)); +#164 = CARTESIAN_POINT('',(-11.8668393524,-3.459571861966, + 62.542838503986)); +#165 = PCURVE('',#51,#166); +#166 = DEFINITIONAL_REPRESENTATION('',(#167),#170); +#167 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#168,#169),.UNSPECIFIED.,.F.,.F., + (2,2),(0.,2.718902929729),.PIECEWISE_BEZIER_KNOTS.); +#168 = CARTESIAN_POINT('',(6.379635251372,7.238638837649)); +#169 = CARTESIAN_POINT('',(3.141590060185,7.238497013832)); +#170 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2) +PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE','' + ) ); +#171 = ORIENTED_EDGE('',*,*,#62,.F.); +#172 = ORIENTED_EDGE('',*,*,#173,.T.); +#173 = EDGE_CURVE('',#24,#174,#176,.T.); +#174 = VERTEX_POINT('',#175); +#175 = CARTESIAN_POINT('',(4.149473588578,-4.810776140259,69.87808667055 + )); +#176 = SURFACE_CURVE('',#177,(#203),.PCURVE_S1.); +#177 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#178,#179,#180,#181,#182,#183, + #184,#185,#186,#187,#188,#189,#190,#191,#192,#193,#194,#195,#196, + #197,#198,#199,#200,#201,#202),.UNSPECIFIED.,.F.,.F.,(4,3,3,3,3,3,3, + 3,4),(2.529141946975,2.603325106943,2.975097425779,3.346869744615, + 3.718642063451,4.090414382287,4.462186701123,4.833959019959, + 5.205731338795),.UNSPECIFIED.); +#178 = CARTESIAN_POINT('',(-12.29864740029,-3.981026217535, + 68.506159421151)); +#179 = CARTESIAN_POINT('',(-12.29891402281,-3.73547313371, + 68.527619116728)); +#180 = CARTESIAN_POINT('',(-12.28818326443,-3.490014692339, + 68.550036353563)); +#181 = CARTESIAN_POINT('',(-12.26630159044,-3.24561292317, + 68.573340448815)); +#182 = CARTESIAN_POINT('',(-12.15664057458,-2.020782213733, + 68.690129994234)); +#183 = CARTESIAN_POINT('',(-11.76691769672,-0.8224904536,68.829193515027 + )); +#184 = CARTESIAN_POINT('',(-11.13645348098,0.229933555183, + 68.976637853055)); +#185 = CARTESIAN_POINT('',(-10.50598926524,1.282357563966, + 69.124082191083)); +#186 = CARTESIAN_POINT('',(-9.634783711627,2.188913821399, + 69.279907346346)); +#187 = CARTESIAN_POINT('',(-8.608543800092,2.860523259039, + 69.428792878436)); +#188 = CARTESIAN_POINT('',(-7.582303888557,3.532132696679, + 69.577678410526)); +#189 = CARTESIAN_POINT('',(-6.401029619107,3.968795314526, + 69.719624319445)); +#190 = CARTESIAN_POINT('',(-5.181669553845,4.127115459444, + 69.840563220766)); +#191 = CARTESIAN_POINT('',(-3.962309488584,4.285435604362, + 69.961502122087)); +#192 = CARTESIAN_POINT('',(-2.70486362751,4.165413276351,70.06143401581) + ); +#193 = CARTESIAN_POINT('',(-1.533296826342,3.779222761759, + 70.130537066304)); +#194 = CARTESIAN_POINT('',(-0.361730025175,3.393032247166, + 70.199640116798)); +#195 = CARTESIAN_POINT('',(0.723957716087,2.740673545991,70.237914324062 + )); +#196 = CARTESIAN_POINT('',(1.616230879826,1.886055040854,70.241506870802 + )); +#197 = CARTESIAN_POINT('',(2.508504043565,1.031436535718,70.245099417541 + )); +#198 = CARTESIAN_POINT('',(3.207362629782,-2.544177338112E-02, + 70.214010303756)); +#199 = CARTESIAN_POINT('',(3.64390522245,-1.179558338951,70.151376605138 + )); +#200 = CARTESIAN_POINT('',(4.080447815118,-2.333674904522,70.08874290652 + )); +#201 = CARTESIAN_POINT('',(4.254674414237,-3.585029726563,69.99456462307 + )); +#202 = CARTESIAN_POINT('',(4.149473588575,-4.810776140259,69.87808667055 + )); +#203 = PCURVE('',#51,#204); +#204 = DEFINITIONAL_REPRESENTATION('',(#205),#208); +#205 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#206,#207),.UNSPECIFIED.,.F.,.F., + (2,2),(2.529141946975,5.205731338795),.PIECEWISE_BEZIER_KNOTS.); +#206 = CARTESIAN_POINT('',(3.141622387077,1.237705820714)); +#207 = CARTESIAN_POINT('',(6.368745709079,1.237706692175)); +#208 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2) +PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE','' + ) ); +#209 = ORIENTED_EDGE('',*,*,#210,.T.); +#210 = EDGE_CURVE('',#174,#22,#211,.T.); +#211 = SURFACE_CURVE('',#212,(#219),.PCURVE_S1.); +#212 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#213,#214,#215,#216,#217,#218), + .UNSPECIFIED.,.F.,.F.,(4,2,4),(0.,3.21060559169E-03,6.42121118338E-03) + ,.UNSPECIFIED.); +#213 = CARTESIAN_POINT('',(4.149473588578,-4.810776140259,69.87808667055 + )); +#214 = CARTESIAN_POINT('',(4.148562516505,-4.821391487794,69.87707793503 + )); +#215 = CARTESIAN_POINT('',(4.147630827754,-4.832004899757, + 69.876067558235)); +#216 = CARTESIAN_POINT('',(4.145726227421,-4.853227732586, + 69.874043533514)); +#217 = CARTESIAN_POINT('',(4.144753317635,-4.863837133464, + 69.873029887494)); +#218 = CARTESIAN_POINT('',(4.143759803725,-4.874444458851, + 69.872014613543)); +#219 = PCURVE('',#51,#220); +#220 = DEFINITIONAL_REPRESENTATION('',(#221),#224); +#221 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#222,#223),.UNSPECIFIED.,.F.,.F., + (2,2),(0.,6.42121118338E-03),.PIECEWISE_BEZIER_KNOTS.); +#222 = CARTESIAN_POINT('',(6.368745709079,1.237706692175)); +#223 = CARTESIAN_POINT('',(6.376509579999,1.237706692175)); +#224 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2) +PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE','' + ) ); +#225 = ( GEOMETRIC_REPRESENTATION_CONTEXT(3) +GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#229)) GLOBAL_UNIT_ASSIGNED_CONTEXT +((#226,#227,#228)) REPRESENTATION_CONTEXT('Context #1', + '3D Context with UNIT and UNCERTAINTY') ); +#226 = ( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) ); +#227 = ( NAMED_UNIT(*) PLANE_ANGLE_UNIT() SI_UNIT($,.RADIAN.) ); +#228 = ( NAMED_UNIT(*) SI_UNIT($,.STERADIAN.) SOLID_ANGLE_UNIT() ); +#229 = UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(5.E-03),#226, + 'distance_accuracy_value','confusion accuracy'); +#230 = PRODUCT_RELATED_PRODUCT_CATEGORY('part',$,(#7)); +ENDSEC; +END-ISO-10303-21; diff --git a/tests/libslic3r/test_step.cpp b/tests/libslic3r/test_step.cpp index 45714e8cd5..e94019dbdb 100644 --- a/tests/libslic3r/test_step.cpp +++ b/tests/libslic3r/test_step.cpp @@ -35,6 +35,7 @@ #include #include #include +#include "admesh/stl.h" #include "libslic3r/BoundingBox.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/Format/STEP.hpp" @@ -122,6 +123,32 @@ TEST_CASE("A cone with a slightly tilted seam imports as a closed mesh", "[Step] CHECK(its_num_open_edges(model.objects.front()->volumes.front()->mesh().its) == 0); } +// The fixture is one band of a tilted chimney exported from Fusion: a full turn of a cone of 313.77 mm², +// whose B-spline boundary pcurves end up to 3e-5 past the seam. Meshed wrongly, it becomes a flat disc of +// about 220 mm² over its top circle. +TEST_CASE("A cone band whose boundary ends past the seam meshes its whole surface", "[Step]") +{ + const std::string path = std::string(TEST_DATA_DIR) + PATH_SEPARATOR "cone_band_seam_overshoot.step"; + + Model model; + bool cancel = false; + Step step(path); + + REQUIRE(step.load() == Step::Step_Status::LOAD_SUCCESS); + REQUIRE(step.mesh(&model, cancel, false) == Step::Step_Status::MESH_SUCCESS); + + REQUIRE(model.objects.size() == 1); + REQUIRE(model.objects.front()->volumes.size() == 1); + const indexed_triangle_set &its = model.objects.front()->volumes.front()->mesh().its; + double area = 0.; + for (const stl_triangle_vertex_indices &face : its.indices) + area += 0.5 * (its.vertices[face[1]] - its.vertices[face[0]]) + .cast() + .cross((its.vertices[face[2]] - its.vertices[face[0]]).cast()) + .norm(); + CHECK_THAT(area, Catch::Matchers::WithinRel(313.77, 0.01)); +} + // The fixture holds two trimmed planes in a geometric set and no shells or solids, as some CAD exporters write // surface models, so OCCT reads it as a compound of loose faces. TEST_CASE("A surface model imports whether or not compounds are split", "[Step]") From c4096cadb6b68ba6588636ab29607d7ce63a0bef Mon Sep 17 00:00:00 2001 From: Kris Austin Date: Fri, 20 Nov 2026 16:51:19 -0600 Subject: [PATCH 21/36] Clone the wxWidgets fork fully so a pinned commit stays reachable (#17742) GIT_TAG pins a commit, but GIT_SHALLOW fetches only the fork's branch head, so the checkout failed as soon as the fork moved past that commit. Every source build broke at the wxWidgets download step with "unable to read tree", including distribution packages built from the 2.5.1 tarball and our own deps jobs on a cache miss. Pinning the new head instead would work until the next time the fork moves. A full clone keeps the deliberate pin and cannot go stale. Fixes #17740 --- deps/wxWidgets/wxWidgets.cmake | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/deps/wxWidgets/wxWidgets.cmake b/deps/wxWidgets/wxWidgets.cmake index df6e55ddd8..f2e30e8a22 100644 --- a/deps/wxWidgets/wxWidgets.cmake +++ b/deps/wxWidgets/wxWidgets.cmake @@ -45,7 +45,9 @@ orcaslicer_add_cmake_project( wxWidgets GIT_REPOSITORY "https://github.com/OrcaSlicer/Orca-deps-wxWidgets" GIT_TAG b44c39c100975a0ac0e46f937aa3f3eae5e18631 - GIT_SHALLOW ON + # Not shallow: GIT_TAG is a commit, and a shallow clone fetches only the branch head, so the + # checkout fails as soon as the fork moves past it. + GIT_SHALLOW OFF GIT_SUBMODULES 3rdparty/catch 3rdparty/pcre 3rdparty/libwebp DEPENDS ${PNG_PKG} ${ZLIB_PKG} ${EXPAT_PKG} ${JPEG_PKG} CMAKE_ARGS From ced396fedc05842467f147ec67e926e4eb577faf Mon Sep 17 00:00:00 2001 From: Kris Austin Date: Fri, 20 Nov 2026 17:19:27 -0600 Subject: [PATCH 22/36] Pin the Flatpak wxWidgets source by commit alone (#17743) flatpak-builder checks that a named branch's tip is the pinned commit, so the source download failed as soon as the fork's v3.3.2 branch moved past b44c39c1. Both Flatpak jobs stopped with "Git commit for branch v3.3.2 is 89844cb1..., but expected b44c39c1...". #17742 fixed the same breakage in the CMake deps recipe, which the Flatpak build does not use. The manifest carries its own pin, so it needed its own fix. Dropping the branch keeps the commit pin and leaves nothing that goes stale when the fork moves. kde-extra-cmake-modules in this file already pins itself the safe way, with an immovable tag plus its commit. disable-shallow-clone makes git fetch full history, which it needs to check out a commit that is no longer a branch tip. Also rewords the comment #17742 left in deps/wxWidgets/wxWidgets.cmake. No build change there. Reported in #17740. --- deps/wxWidgets/wxWidgets.cmake | 4 ++-- scripts/flatpak/com.orcaslicer.OrcaSlicer.yml | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/deps/wxWidgets/wxWidgets.cmake b/deps/wxWidgets/wxWidgets.cmake index f2e30e8a22..2f384e6cbe 100644 --- a/deps/wxWidgets/wxWidgets.cmake +++ b/deps/wxWidgets/wxWidgets.cmake @@ -45,8 +45,8 @@ orcaslicer_add_cmake_project( wxWidgets GIT_REPOSITORY "https://github.com/OrcaSlicer/Orca-deps-wxWidgets" GIT_TAG b44c39c100975a0ac0e46f937aa3f3eae5e18631 - # Not shallow: GIT_TAG is a commit, and a shallow clone fetches only the branch head, so the - # checkout fails as soon as the fork moves past it. + # A shallow clone fetches only the branch head, so checking out a pinned commit fails once the + # branch moves past it. GIT_SHALLOW OFF GIT_SUBMODULES 3rdparty/catch 3rdparty/pcre 3rdparty/libwebp DEPENDS ${PNG_PKG} ${ZLIB_PKG} ${EXPAT_PKG} ${JPEG_PKG} diff --git a/scripts/flatpak/com.orcaslicer.OrcaSlicer.yml b/scripts/flatpak/com.orcaslicer.OrcaSlicer.yml index 46ed319244..13e395b4e0 100644 --- a/scripts/flatpak/com.orcaslicer.OrcaSlicer.yml +++ b/scripts/flatpak/com.orcaslicer.OrcaSlicer.yml @@ -119,8 +119,10 @@ modules: # submodules (PCRE2, etc.) that are not included in GitHub tarballs. - type: git url: https://github.com/OrcaSlicer/Orca-deps-wxWidgets.git - branch: v3.3.2 + # flatpak-builder requires a named branch's tip to be the pinned commit, so this names no + # branch and clones in full, which git needs to check out a commit that is not a tip. commit: b44c39c100975a0ac0e46f937aa3f3eae5e18631 + disable-shallow-clone: true # OrcaSlicer C++ dependencies (built offline with pre-downloaded archives) - name: orca_deps From 49b84637eea5ad27905786756c039ecb5d12f09f Mon Sep 17 00:00:00 2001 From: TheLegendTubaGuy <95944177+thelegendtubaguy@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:07:36 -0600 Subject: [PATCH 23/36] Fix Stack Overflow When Nesting Clipper2 Results With Cyclic Splits (#17592) Backport PolyClipping/Clipper2 f97d65d. CheckSplitOwner descended into an emptied OutRec's splits without the recursive_split guard, so emptied OutRecs that referred to each other recursed until the stack overflowed. Fixes #17584 --- deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp | 10 ++++++++-- tests/libslic3r/test_clipper_utils.cpp | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp b/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp index a3a5c7ca1b..db1166d311 100644 --- a/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp +++ b/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp @@ -2978,8 +2978,14 @@ namespace Clipper2Lib { for (size_t idx = 0; idx < splits->size(); ++idx) { OutRec* split = (*splits)[idx]; - if (!split->pts && split->splits && - CheckSplitOwner(outrec, split->splits)) return true; //#942 + if (!split->pts && split->splits) + { + if (split->recursive_split == outrec) continue; + split->recursive_split = outrec; // emptied OutRecs can reference each other + + if (CheckSplitOwner(outrec, split->splits)) return true; //#942 + } + split = GetRealOutRec(split); if (!split || split == outrec || split->recursive_split == outrec) continue; split->recursive_split = outrec; // prevent infinite loops diff --git a/tests/libslic3r/test_clipper_utils.cpp b/tests/libslic3r/test_clipper_utils.cpp index ce1b3b76fa..44f74969e5 100644 --- a/tests/libslic3r/test_clipper_utils.cpp +++ b/tests/libslic3r/test_clipper_utils.cpp @@ -877,3 +877,11 @@ TEST_CASE("Uniting a few polygons in groups is one union", "[ClipperUtils]") { CHECK(union_overlapping_ex(polygons) == union_ex(polygons)); CHECK(union_overlapping_ex({}).empty()); } + +TEST_CASE("An even-odd union of a path retracing its edges covers the same area as the flat union", "[ClipperUtils]") { + // Building the PolyTree of this path leaves emptied output loops that point at each other, and looking for a + // loop's owner through them recursed until the stack overflowed. + const Polygons subject{ Polygon({ { 3, 0 }, { 3, 5 }, { 0, 3 }, { 5, 3 }, { 0, 5 }, { 5, 3 }, { 0, 3 }, + { 0, 0 }, { 0, 3 }, { 5, 3 }, { 0, 0 }, { 3, 3 }, { 2, 3 } }) }; + CHECK_THAT(area(union_ex(subject, pftEvenOdd)), Catch::Matchers::WithinRel(area(union_(subject, pftEvenOdd)), 1e-9)); +} From 84f199cb04d2ee6d2283f99c80cd2a174f4e1623 Mon Sep 17 00:00:00 2001 From: Ian Chua Date: Sat, 21 Nov 2026 17:25:55 +0800 Subject: [PATCH 24/36] fix: correct windows python audit format (#17697) --- ...01-winapi-createprocess-audit-format.patch | 11 ++++ deps/python3/patch_winapi_audit.cmake | 38 +++++++++++++ deps/python3/python3.cmake | 11 ++++ tests/slic3rutils/test_plugin_audit.cpp | 54 +++++++++++++++++++ 4 files changed, 114 insertions(+) create mode 100644 deps/python3/0001-winapi-createprocess-audit-format.patch create mode 100644 deps/python3/patch_winapi_audit.cmake diff --git a/deps/python3/0001-winapi-createprocess-audit-format.patch b/deps/python3/0001-winapi-createprocess-audit-format.patch new file mode 100644 index 0000000000..a081e51164 --- /dev/null +++ b/deps/python3/0001-winapi-createprocess-audit-format.patch @@ -0,0 +1,11 @@ +--- a/Modules/_winapi.c ++++ b/Modules/_winapi.c +@@ -1252,7 +1252,7 @@ _winapi_CreateProcess_impl(PyObject *module, const Py_UNICODE *application_name, + wchar_t *command_line_copy = NULL; + AttributeList attribute_list = {0}; + +- if (PySys_Audit("_winapi.CreateProcess", "uuu", application_name, ++ if (PySys_Audit("_winapi.CreateProcess", "uOu", application_name, + command_line, current_directory) < 0) { + return NULL; + } diff --git a/deps/python3/patch_winapi_audit.cmake b/deps/python3/patch_winapi_audit.cmake new file mode 100644 index 0000000000..85610c0eb3 --- /dev/null +++ b/deps/python3/patch_winapi_audit.cmake @@ -0,0 +1,38 @@ +# Applied as PATCH_COMMAND for CPython on Windows, from the extracted source directory. +# +# CPython 3.12.13 raises the _winapi.CreateProcess audit event with PySys_Audit format "uuu", +# although command_line is a Python object: audit hooks receive garbage instead of the command +# line. PluginAuditManager turns that argument into a process grant's target, so the prompt +# named the wrong executable and the grant it saved could not cover a real call. The patch +# changes the format to "uOu", as upstream does (python/cpython#159237), until the pinned +# CPython release carries the fix. +# +# Applying is idempotent: ExternalProject re-runs the patch step when PATCH_COMMAND changes or +# the patch stamp is missing, which can happen on a source tree that already carries the patch. +# A reverse check recognises that state instead of failing the build on an already patched file. +# When the pinned CPython release carries the fix, drop this script, its patch and PATCH_COMMAND. + +set(_patch "${CMAKE_CURRENT_LIST_DIR}/0001-winapi-createprocess-audit-format.patch") + +if(NOT GIT_EXECUTABLE) + message(FATAL_ERROR "GIT_EXECUTABLE is required") +endif() + +execute_process( + COMMAND "${GIT_EXECUTABLE}" apply --check --reverse --ignore-space-change "${_patch}" + RESULT_VARIABLE _already_applied + OUTPUT_QUIET + ERROR_QUIET +) +if(_already_applied EQUAL 0) + message(STATUS "CPython: _winapi.CreateProcess audit format is already patched") + return() +endif() + +execute_process( + COMMAND "${GIT_EXECUTABLE}" apply --verbose --ignore-space-change --whitespace=fix "${_patch}" + RESULT_VARIABLE _apply_result +) +if(NOT _apply_result EQUAL 0) + message(FATAL_ERROR "CPython: failed to apply ${_patch} (exit ${_apply_result})") +endif() diff --git a/deps/python3/python3.cmake b/deps/python3/python3.cmake index 4f60bb1b14..7e5745af79 100644 --- a/deps/python3/python3.cmake +++ b/deps/python3/python3.cmake @@ -181,6 +181,16 @@ if(WIN32) -DPYTHON_LAYOUT_ARCH=${_python_layout_arch} -P ${CMAKE_CURRENT_LIST_DIR}/stage_windows.cmake ) + # CPython 3.12.13 raises the _winapi.CreateProcess audit event with PySys_Audit's "u" format + # for command_line although it is a Python object, so audit hooks received garbage instead of + # the command line and the plugin audit prompt named the wrong executable. Apply upstream's + # "uOu" fix (python/cpython#159237) until the pinned release carries it. The step tolerates + # an already patched tree, which a re-run after a stamp change can meet. + set(_python_patch_cmd + ${CMAKE_COMMAND} + "-DGIT_EXECUTABLE=${GIT_EXECUTABLE}" + -P "${CMAKE_CURRENT_LIST_DIR}/patch_winapi_audit.cmake" + ) elseif(APPLE) # macOS configuration if(CMAKE_OSX_ARCHITECTURES) @@ -351,6 +361,7 @@ ExternalProject_Add(dep_python3 URL_HASH SHA256=${_python_sha256} DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/python3 BUILD_IN_SOURCE ON + PATCH_COMMAND ${_python_patch_cmd} CONFIGURE_COMMAND ${_conf_cmd} BUILD_COMMAND ${_build_cmd} INSTALL_COMMAND ${_install_cmd} diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index c130b08748..151949176b 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -1426,6 +1426,8 @@ import http.client, http.server, os, pathlib, shutil, socket, subprocess, sys, t import urllib.request, zipfile if os.name != "nt": import pty +else: + import _winapi APPROVED = os.path.join(OUTSIDE, "approved.txt") PRIVATE = os.path.join(OUTSIDE, "private.txt") @@ -2706,6 +2708,58 @@ site_packages_outcome = attempt(lambda: open(SITE_PACKAGE_FILE).close()) CHECK(describe(harness.prompts) == write_prompt + site_packages_prompt); } +#ifdef _WIN32 +TEST_CASE("A real _winapi.CreateProcess audit event reports its command line as text", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // subprocess reaches this event on Windows. CPython 3.12.13 raised it with PySys_Audit's "uuu" + // format, reading the command-line object as a wide string, so audit hooks received garbage + // instead of the text subprocess passed. The deps patch raises "uOu" (as upstream does, + // python/cpython#159237) until the pinned release carries the fix. + // + // The event is raised before the arguments are used, so a rejected environment mapping ends + // the call after the hook saw the event, without reaching CreateProcessW. Run outside a + // plugin scope, so the hook below is reached: the plugin audit hook aborts the event when it + // denies, and a real prompt is asserted separately at the end. + python.exec(R"PY( +WINAPI_AUDIT_CALLS = [] + +def record_winapi_audit(event, args): + if event == "_winapi.CreateProcess": + WINAPI_AUDIT_CALLS.append(args) + +sys.addaudithook(record_winapi_audit) + +DENIED_EXECUTABLE = os.path.join(OUTSIDE, "Program Files", "audit-denied.exe") +COMMAND_LINE = '"' + DENIED_EXECUTABLE + '" --flag' +try: + _winapi.CreateProcess(None, COMMAND_LINE, None, None, False, 0, object(), None, + subprocess.STARTUPINFO()) + audit_arguments_outcome = "started" +except TypeError: + audit_arguments_outcome = "stopped" +)PY"); + CHECK(python.str("audit_arguments_outcome") == "stopped"); + INFO("recorded audit arguments: " << python.str("WINAPI_AUDIT_CALLS")); + CHECK(python.eval("WINAPI_AUDIT_CALLS == [(None, COMMAND_LINE, None)]") == "True"); + + // In a plugin scope the same call is prompted and denied, and the prompt names the command + // line exactly as the caller passed it, which an approval saves as the process grant. + python.run_as(PLUGIN, R"PY( +create_process_outcome = attempt(lambda: _winapi.CreateProcess( + None, COMMAND_LINE, None, None, False, 0, None, None, subprocess.STARTUPINFO())) +)PY"); + CHECK(python.str("create_process_outcome") == "denied"); + CHECK(describe(harness.prompts) == "_winapi.CreateProcess: " + python.str("COMMAND_LINE") + "\n"); +} +#endif + TEST_CASE("A filesystem wildcard grant covers the folder and its descendants at any depth", "[audit][Python]") { AuditHarness harness; From 5a1ffc6a631ead5886f1c22920deb341fc1a0106 Mon Sep 17 00:00:00 2001 From: Ian Chua Date: Sat, 21 Nov 2026 19:30:47 +0800 Subject: [PATCH 25/36] fix: correct windows process audit test expectation (#17757) --- tests/slic3rutils/test_plugin_audit.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index 151949176b..938b6f1920 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -2749,14 +2749,14 @@ except TypeError: INFO("recorded audit arguments: " << python.str("WINAPI_AUDIT_CALLS")); CHECK(python.eval("WINAPI_AUDIT_CALLS == [(None, COMMAND_LINE, None)]") == "True"); - // In a plugin scope the same call is prompted and denied, and the prompt names the command - // line exactly as the caller passed it, which an approval saves as the process grant. + // In a plugin scope the same call is prompted and denied. The quoted executable is the + // permission target; its arguments are not part of the grant. python.run_as(PLUGIN, R"PY( create_process_outcome = attempt(lambda: _winapi.CreateProcess( None, COMMAND_LINE, None, None, False, 0, None, None, subprocess.STARTUPINFO())) )PY"); CHECK(python.str("create_process_outcome") == "denied"); - CHECK(describe(harness.prompts) == "_winapi.CreateProcess: " + python.str("COMMAND_LINE") + "\n"); + CHECK(describe(harness.prompts) == "_winapi.CreateProcess: " + python.str("DENIED_EXECUTABLE") + "\n"); } #endif From 1174b3900488dedc8ad1d54ba4d2f8329e52d601 Mon Sep 17 00:00:00 2001 From: Warren Green Date: Sat, 21 Nov 2026 08:59:12 -0500 Subject: [PATCH 26/36] Speed up slicing without changing the G-code of a fresh slice (#17335) Co-authored-by: Claude Opus 5.5 --- .../Clipper2Lib/src/clipper.engine.cpp | 19 +- docs/HLSD/polygon-clipping.md | 5 +- src/libslic3r/AABBTreeIndirect.hpp | 127 +++++--- src/libslic3r/CMakeLists.txt | 1 + src/libslic3r/ExPolygon.cpp | 16 + src/libslic3r/GCode.cpp | 28 +- src/libslic3r/GCode.hpp | 13 + src/libslic3r/GCode/ConflictChecker.cpp | 29 +- src/libslic3r/GCode/ConflictChecker.hpp | 2 +- src/libslic3r/GCode/SeamPlacer.cpp | 84 +++-- src/libslic3r/Layer.cpp | 3 + src/libslic3r/Model.cpp | 19 +- src/libslic3r/ParallelForFirstError.hpp | 46 +++ src/libslic3r/Print.cpp | 87 ++--- src/libslic3r/PrintBase.cpp | 6 +- src/libslic3r/PrintBase.hpp | 9 +- tests/fff_print/CMakeLists.txt | 1 + tests/fff_print/test_conflict_checker.cpp | 75 +++++ tests/fff_print/test_print.cpp | 307 ++++++++++++++++++ tests/fff_print/test_seam_placer.cpp | 34 ++ tests/libslic3r/CMakeLists.txt | 2 + tests/libslic3r/test_aabbindirect.cpp | 127 ++++++++ tests/libslic3r/test_expolygon.cpp | 65 ++++ tests/libslic3r/test_model.cpp | 20 ++ .../test_parallel_for_first_error.cpp | 64 ++++ 25 files changed, 1034 insertions(+), 155 deletions(-) create mode 100644 src/libslic3r/ParallelForFirstError.hpp create mode 100644 tests/fff_print/test_conflict_checker.cpp create mode 100644 tests/libslic3r/test_expolygon.cpp create mode 100644 tests/libslic3r/test_parallel_for_first_error.cpp diff --git a/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp b/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp index db1166d311..0666b23fb4 100644 --- a/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp +++ b/deps_src/clipper2/Clipper2Lib/src/clipper.engine.cpp @@ -817,9 +817,18 @@ namespace Clipper2Lib { std::stable_sort(minima_list_.begin(), minima_list_.end(), LocMinSorter()); //#594 minima_list_sorted_ = true; } - LocalMinimaList::const_reverse_iterator i; - for (i = minima_list_.rbegin(); i != minima_list_.rend(); ++i) - InsertScanline((*i)->vertex->pt.y); + // Orca: PopScanline() returns each pending y once, however many times it was inserted, so only the + // distinct ys of the local minima are queued. Sorted by descending y they already form a max-heap; + // inserting them one by one in ascending order made every insertion climb to the top of the heap. + std::vector minima_ys; + minima_ys.reserve(minima_list_.size()); + for (const LocalMinima_ptr& lm : minima_list_) + if (minima_ys.empty() || minima_ys.back() != lm->vertex->pt.y) + minima_ys.push_back(lm->vertex->pt.y); + if (scanline_list_.empty()) + scanline_list_ = std::priority_queue(std::less(), std::move(minima_ys)); + else + for (int64_t y : minima_ys) InsertScanline(y); current_locmin_iter_ = minima_list_.begin(); actives_ = nullptr; @@ -883,7 +892,9 @@ namespace Clipper2Lib { void ClipperBase::InsertScanline(int64_t y) { - scanline_list_.push(y); + // Orca: a y already at the top is popped together with this one anyway. + if (scanline_list_.empty() || scanline_list_.top() != y) + scanline_list_.push(y); } diff --git a/docs/HLSD/polygon-clipping.md b/docs/HLSD/polygon-clipping.md index afbc53aad7..ec8537bf4d 100644 --- a/docs/HLSD/polygon-clipping.md +++ b/docs/HLSD/polygon-clipping.md @@ -29,10 +29,10 @@ as for predictable geometry. ## Vendored Clipper2 -`deps_src/clipper2` builds the static target `Clipper2`. It carries five +`deps_src/clipper2` builds the static target `Clipper2`. It carries six changes to the upstream sources that must be carried over when Clipper2 is updated. The namespace switch sits at the top of every header and source, the -other four are marked with `Orca:` comments. +other five are marked with `Orca:` comments. | Change | Files | Why | | --- | --- | --- | @@ -40,6 +40,7 @@ other four are marked with `Orca:` comments. | Engine nodes from tbbmalloc | `clipper.engine.h`, `clipper.engine.cpp` | Vertices, active edges, output points and records, local minima and `PolyTree` nodes are allocated one by one. `CLIPPER2_NODE_ALLOCATOR` routes them through `scalable_malloc`, because the default heap does not scale when all slicing threads clip at once. | | Concave joins at the edge crossing | `clipper.offset.cpp` | For closed paths, a concave corner is joined at the crossing of the two offset edges when that point lies within half of both adjacent edges. The upstream 3-point loop makes inward offsets of dense curves very slow to union. | | Rounded arc steps | `clipper.offset.cpp` | Round joins use the rounded number of steps, not the ceiling, which keeps the vertex count of round offsets that the rest of the code is tuned for. | +| Distinct scan lines | `clipper.engine.cpp` | `Reset()` builds the scan line heap from the distinct y of the local minima in one pass, and `InsertScanline()` skips a y already at the top. Upstream inserts the minima one by one in ascending order, so each climbs to the top of the heap. Scan lines are popped in the same order either way. | | No intersection sort for edges in order | `clipper.engine.h`, `clipper.engine.cpp` | `AdjustCurrXAndCopyToSEL()` reports whether the active edges kept their order at the top of the scanbeam, and `BuildIntersectList()` returns before its merge sort when they did. Most scanbeams have no crossing, and the sort was a large part of every boolean on dense support layers. | ## ClipperUtils semantics diff --git a/src/libslic3r/AABBTreeIndirect.hpp b/src/libslic3r/AABBTreeIndirect.hpp index 5fd83e0be9..d3beacba2b 100644 --- a/src/libslic3r/AABBTreeIndirect.hpp +++ b/src/libslic3r/AABBTreeIndirect.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -397,51 +398,87 @@ namespace detail { return eps; } - template - static inline bool intersect_ray_recursive_first_hit( - RayIntersectorType &ray_intersector, - size_t node_idx, - Scalar min_t, - igl::Hit &hit) + // ray_box_intersect_invdir() for a ray whose direction signs are known at compile time: NegX etc. tell + // which slabs are entered through the max face. The comparisons select the same entry and exit parameters + // as the early returns of ray_box_intersect_invdir() and give the same answer for any input, NaN included, + // but without the unpredictable branches. + template + inline bool ray_box_intersect_invdir_signs( + const VectorType &origin, + const VectorType &inv_dir, + const Eigen::AlignedBox &box, + const Scalar t0, + const Scalar t1) { - const auto &node = ray_intersector.tree.node(node_idx); - assert(node.is_valid()); - - if (! ray_box_intersect_invdir(ray_intersector.origin, ray_intersector.invdir, node.bbox.template cast(), Scalar(0), min_t)) - return false; + const Scalar tx0 = (Scalar(NegX ? box.max().x() : box.min().x()) - origin.x()) * inv_dir.x(); + const Scalar tx1 = (Scalar(NegX ? box.min().x() : box.max().x()) - origin.x()) * inv_dir.x(); + const Scalar ty0 = (Scalar(NegY ? box.max().y() : box.min().y()) - origin.y()) * inv_dir.y(); + const Scalar ty1 = (Scalar(NegY ? box.min().y() : box.max().y()) - origin.y()) * inv_dir.y(); + const Scalar tz0 = (Scalar(NegZ ? box.max().z() : box.min().z()) - origin.z()) * inv_dir.z(); + const Scalar tz1 = (Scalar(NegZ ? box.min().z() : box.max().z()) - origin.z()) * inv_dir.z(); + const Scalar txy_min = ty0 > tx0 ? ty0 : tx0; + const Scalar txy_max = ty1 < tx1 ? ty1 : tx1; + const Scalar tmin = tz0 > txy_min ? tz0 : txy_min; + const Scalar tmax = tz1 < txy_max ? tz1 : txy_max; + return tmin <= tmax && tmin < t1 && tmax > t0; + } - if (node.is_leaf()) { - // shoot ray, record hit - auto face = ray_intersector.faces[node.idx]; - double t, u, v; - if (intersect_triangle( - ray_intersector.origin, ray_intersector.dir, - ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)], ray_intersector.vertices[face(2)], - t, u, v, ray_intersector.eps) - && t > 0.) { - hit = igl::Hit { int(node.idx), -1, float(u), float(v), float(t) }; - return true; - } else - return false; - } else { - // Left / right child node index. - size_t left = node_idx * 2 + 1; - size_t right = left + 1; - igl::Hit left_hit; - igl::Hit right_hit; - bool left_ret = intersect_ray_recursive_first_hit(ray_intersector, left, min_t, left_hit); - if (left_ret && left_hit.t < min_t) { - min_t = left_hit.t; - hit = left_hit; - } else - left_ret = false; - bool right_ret = intersect_ray_recursive_first_hit(ray_intersector, right, min_t, right_hit); - if (right_ret && right_hit.t < min_t) - hit = right_hit; - else - right_ret = false; - return left_ret || right_ret; - } + // The depth-first, left to right search for the first hit, the nearest hit found so far bounding the ray + // interval tested against the boxes. Iterative, with the ray direction signs resolved at compile time. + template + static inline bool intersect_ray_first_hit_signs(const RayIntersectorType &ray_intersector, igl::Hit &hit) + { + using Scalar = typename RayIntersectorType::VectorType::Scalar; + const auto &nodes = ray_intersector.tree.nodes(); + Scalar min_t = std::numeric_limits::infinity(); + bool found = false; + // Nodes waiting for their left sibling's subtree: at most one per level, plus the left sibling itself. + size_t stack[65]; + size_t stack_size = 0; + stack[stack_size ++] = 0; + while (stack_size > 0) { + const size_t node_idx = stack[-- stack_size]; + const auto &node = nodes[node_idx]; + assert(node.is_valid()); + if (! ray_box_intersect_invdir_signs(ray_intersector.origin, ray_intersector.invdir, node.bbox, Scalar(0), min_t)) + continue; + if (node.is_leaf()) { + auto face = ray_intersector.faces[node.idx]; + double t, u, v; + // A leaf at the root has no parent to reject a hit beyond min_t. + if (intersect_triangle( + ray_intersector.origin, ray_intersector.dir, + ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)], ray_intersector.vertices[face(2)], + t, u, v, ray_intersector.eps) + && t > 0. && (float(t) < min_t || node_idx == 0)) { + hit = igl::Hit { int(node.idx), -1, float(u), float(v), float(t) }; + min_t = hit.t; + found = true; + } + } else { + assert(stack_size + 2 <= std::size(stack)); + // Push the right child first, so that the left subtree is searched first. + stack[stack_size ++] = node_idx * 2 + 2; + stack[stack_size ++] = node_idx * 2 + 1; + } + } + return found; + } + + template + static inline bool intersect_ray_first_hit_dispatch(const RayIntersectorType &ray_intersector, igl::Hit &hit) + { + const auto &inv_dir = ray_intersector.invdir; + switch (int(inv_dir.x() < 0) | (int(inv_dir.y() < 0) << 1) | (int(inv_dir.z() < 0) << 2)) { + case 0: return intersect_ray_first_hit_signs(ray_intersector, hit); + case 1: return intersect_ray_first_hit_signs(ray_intersector, hit); + case 2: return intersect_ray_first_hit_signs(ray_intersector, hit); + case 3: return intersect_ray_first_hit_signs(ray_intersector, hit); + case 4: return intersect_ray_first_hit_signs(ray_intersector, hit); + case 5: return intersect_ray_first_hit_signs(ray_intersector, hit); + case 6: return intersect_ray_first_hit_signs(ray_intersector, hit); + default: return intersect_ray_first_hit_signs(ray_intersector, hit); + } } template @@ -741,14 +778,12 @@ inline bool intersect_ray_first_hit( // Epsilon for the ray-triangle intersection, it should be proportional to an average triangle edge length. const double eps = 0.000001) { - using Scalar = typename VectorType::Scalar; auto ray_intersector = detail::RayIntersector { vertices, faces, tree, origin, dir, VectorType(dir.cwiseInverse()), eps }; - return ! tree.empty() && detail::intersect_ray_recursive_first_hit( - ray_intersector, size_t(0), std::numeric_limits::infinity(), hit); + return ! tree.empty() && detail::intersect_ray_first_hit_dispatch(ray_intersector, hit); } // Find all intersections of a ray with indexed triangle set. diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index b18c3590ab..a81d08436c 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -396,6 +396,7 @@ set(lisbslic3r_sources Optimize/Optimizer.hpp Orient.cpp Orient.hpp + ParallelForFirstError.hpp ParallelResolve.hpp ParameterUtils.cpp ParameterUtils.hpp diff --git a/src/libslic3r/ExPolygon.cpp b/src/libslic3r/ExPolygon.cpp index 133bb8d279..dc1dfae862 100644 --- a/src/libslic3r/ExPolygon.cpp +++ b/src/libslic3r/ExPolygon.cpp @@ -92,6 +92,22 @@ bool ExPolygon::contains(const Polyline &polyline) const if (!bbox1.overlap(bbox2)) return false; + // A polyline reaching further than SCALED_EPSILON out of the bounding box of all the outlines runs + // outside of them all there, which the difference keeps: no need to compute it. This does not hold for + // a polyline of a single point, which the difference drops. + if (bbox2.min != bbox2.max) { + auto reaches_out = [&bbox2](BoundingBox outlines) { + outlines.offset(SCALED_EPSILON); + return !outlines.contains(bbox2.min) || !outlines.contains(bbox2.max); + }; + if (reaches_out(bbox1)) { + for (const Polygon &hole : this->holes) + bbox1.merge(get_extents(hole)); + if (reaches_out(bbox1)) + return false; + } + } + return diff_pl(polyline, *this).empty(); } diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 4b2d385e94..68396302b6 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -2854,6 +2854,7 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu // BBS m_curr_print = print; + m_overhang_layers_cache.valid = false; m_skirt_group_done.clear(); m_pending_start_gcode_position.reset(); m_exclusion_volume_travel_avoidance.init(print->config(), print->get_plate_origin()); @@ -10854,12 +10855,22 @@ bool GCode::needs_retraction(const Polyline &travel, ExtrusionRole role, LiftTyp std::pair z_range; z_range.second = m_layer ? m_layer->print_z : 0.f; z_range.first = std::max(0.f, z_range.second - protect_z); - std::vector layers_of_objects; - std::vector boundingBox_for_objects; - VecOfPoints objects_instances_shift; - std::vector idx_of_object_sorted = m_curr_print->layers_sorted_for_object(z_range.first, z_range.second, layers_of_objects, boundingBox_for_objects, objects_instances_shift); - - std::vector is_layers_of_objects_sorted(layers_of_objects.size(), false); + OverhangLayersCache &cache = m_overhang_layers_cache; + if (!cache.valid || cache.z_min != z_range.first || cache.z_max != z_range.second) { + cache.layers_of_objects.clear(); + cache.boundingBox_for_objects.clear(); + cache.idx_of_object_sorted = m_curr_print->layers_sorted_for_object(z_range.first, z_range.second, cache.layers_of_objects, + cache.boundingBox_for_objects, cache.objects_instances_shift); + for (LayerPtrs &layers : cache.layers_of_objects) + std::sort(layers.begin(), layers.end(), [](auto left, auto right) { return left->loverhangs_bbox.area() > right->loverhangs_bbox.area();}); + cache.z_min = z_range.first; + cache.z_max = z_range.second; + cache.valid = true; + } + const std::vector &layers_of_objects = cache.layers_of_objects; + const std::vector &boundingBox_for_objects = cache.boundingBox_for_objects; + const VecOfPoints &objects_instances_shift = cache.objects_instances_shift; + const std::vector &idx_of_object_sorted = cache.idx_of_object_sorted; for (size_t idx : idx_of_object_sorted) { for (const Point & instance_shift : objects_instances_shift[idx]) { @@ -10877,11 +10888,6 @@ bool GCode::needs_retraction(const Polyline &travel, ExtrusionRole role, LiftTyp if (intersection_pl(travel, temp).empty()) continue; - if (!is_layers_of_objects_sorted[idx]) { - std::sort(layers_of_objects[idx].begin(), layers_of_objects[idx].end(), [](auto left, auto right) { return left->loverhangs_bbox.area() > right->loverhangs_bbox.area();}); - is_layers_of_objects_sorted[idx] = true; - } - for (const auto& layer : layers_of_objects[idx]) { for (ExPolygon overhang : layer->loverhangs) { overhang.translate(instance_shift); diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index 316b18e6e2..c42c9ce3d6 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -932,6 +932,19 @@ protected: // BBS Print* m_curr_print = nullptr; + // The layers of every object below the layer being exported, which needs_retraction() searches for + // overhangs a travel crosses: collected once per z range rather than once per travel. + struct OverhangLayersCache + { + bool valid = false; + float z_min = 0.f; + float z_max = 0.f; + std::vector idx_of_object_sorted; + // Of each object, sorted by the area of their overhangs' bounding box, largest first. + std::vector layers_of_objects; + std::vector boundingBox_for_objects; + VecOfPoints objects_instances_shift; + } m_overhang_layers_cache; unsigned int m_toolchange_count; coordf_t m_nominal_z; // Mixed-color sublayer state. Non-zero only while emitting a mixed slot's sub-layer: diff --git a/src/libslic3r/GCode/ConflictChecker.cpp b/src/libslic3r/GCode/ConflictChecker.cpp index a5646d8800..72b054ecf5 100644 --- a/src/libslic3r/GCode/ConflictChecker.cpp +++ b/src/libslic3r/GCode/ConflictChecker.cpp @@ -18,8 +18,9 @@ #include #include -#include #include +#include +#include #include #include #include @@ -40,9 +41,10 @@ inline IndexPair point_map_grid_index(const Point &pt, int64_t xdist, int64_t yd inline bool nearly_equal(const Point &p1, const Point &p2) { return std::abs(p1.x() - p2.x()) < SCALED_EPSILON && std::abs(p1.y() - p2.y()) < SCALED_EPSILON; } -inline Grids line_rasterization(const Line &line, int64_t xdist = scale_(1), int64_t ydist = scale_(1)) +// The grid cells the line passes through, in order, into res. +inline void line_rasterization(const Line &line, Grids &res, int64_t xdist = scale_(1), int64_t ydist = scale_(1)) { - Grids res; + res.clear(); Point rayStart = line.a; Point rayEnd = line.b; IndexPair currentVoxel = point_map_grid_index(rayStart, xdist, ydist); @@ -99,9 +101,12 @@ inline Grids line_rasterization(const Line &line, int64_t xdist = scale_(1), int assert(0); } } - - return res; } + +struct IndexPairHash +{ + size_t operator()(const IndexPair &p) const { return std::hash()(p.first) ^ (std::hash()(p.second) * 0x9e3779b97f4a7c15ull); } +}; } // namespace RasterizationImpl void LinesBucketQueue::emplace_back_bucket(ExtrusionLayers &&els, const void *objPtr, Point offset) @@ -207,7 +212,7 @@ ObjectExtrusions getAllLayersExtrusionPathsFromObject(PrintObject *obj) for (auto layerPtr : obj->layers()) { auto perimeters = getExtrusionPathsFromLayer(layerPtr->regions()); - oe.perimeters.insert(oe.perimeters.end(), perimeters.begin(), perimeters.end()); + oe.perimeters.insert(oe.perimeters.end(), std::make_move_iterator(perimeters.begin()), std::make_move_iterator(perimeters.end())); } for (auto supportLayerPtr : obj->support_layers()) { oe.support.push_back(getExtrusionPathsFromSupportLayer(supportLayerPtr)); } @@ -218,18 +223,20 @@ ObjectExtrusions getAllLayersExtrusionPathsFromObject(PrintObject *obj) ConflictComputeOpt ConflictChecker::find_inter_of_lines(const LineWithIDs &lines) { using namespace RasterizationImpl; - std::map> indexToLine; + // Only looked up, never iterated, so the order of the cells does not matter. + std::unordered_map, IndexPairHash> indexToLine; + Grids indexes; for (int i = 0; i < lines.size(); ++i) { - const LineWithID &l1 = lines[i]; - auto indexes = line_rasterization(l1._line); + const LineWithID &l1 = lines[i]; + line_rasterization(l1._line, indexes); for (auto index : indexes) { - const auto &possibleIntersectIdxs = indexToLine[index]; + auto &possibleIntersectIdxs = indexToLine[index]; for (auto possibleIntersectIdx : possibleIntersectIdxs) { const LineWithID &l2 = lines[possibleIntersectIdx]; if (auto interRes = line_intersect(l1, l2); interRes.has_value()) { return interRes; } } - indexToLine[index].push_back(i); + possibleIntersectIdxs.push_back(i); } } return {}; diff --git a/src/libslic3r/GCode/ConflictChecker.hpp b/src/libslic3r/GCode/ConflictChecker.hpp index 85fabec585..e5c07a1c4a 100644 --- a/src/libslic3r/GCode/ConflictChecker.hpp +++ b/src/libslic3r/GCode/ConflictChecker.hpp @@ -71,7 +71,7 @@ public: Point _offset; public: - LinesBucket(ExtrusionLayers &&paths, const void* id, Point offset) : _piles(paths), _id(id), _offset(offset) {} + LinesBucket(ExtrusionLayers &&paths, const void* id, Point offset) : _piles(std::move(paths)), _id(id), _offset(offset) {} LinesBucket(LinesBucket &&) = default; std::pair curRange() const diff --git a/src/libslic3r/GCode/SeamPlacer.cpp b/src/libslic3r/GCode/SeamPlacer.cpp index ad3cc1db9c..5bcfc8b94b 100644 --- a/src/libslic3r/GCode/SeamPlacer.cpp +++ b/src/libslic3r/GCode/SeamPlacer.cpp @@ -11,6 +11,7 @@ #include "libslic3r/PrintBase.hpp" #include "PrintConfig.hpp" #include "libslic3r/libslic3r.h" +#include "libslic3r/ParallelForFirstError.hpp" #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/TriangleSelector.hpp" #include "tbb/parallel_for.h" @@ -390,20 +391,18 @@ struct GlobalModelInfo { } float calculate_point_visibility(const Vec3f &position) const { - std::vector points = find_nearby_points(mesh_samples_tree, position, mesh_samples_radius); - if (points.empty()) { - return 1.0f; - } - auto compute_dist_to_plane = [](const Vec3f &position, const Vec3f &plane_origin, const Vec3f &plane_normal) { Vec3f orig_to_point = position - plane_origin; return std::abs(orig_to_point.dot(plane_normal)); }; + // Accumulated in the order find_nearby_points() lists the samples, without collecting them first: + // this runs for every seam candidate. + bool any_sample = false; float total_weight = 0; float total_visibility = 0; - for (size_t i = 0; i < points.size(); ++i) { - size_t sample_idx = points[i]; + visit_nearby_points(mesh_samples_tree, position, mesh_samples_radius, [&](size_t sample_idx) { + any_sample = true; Vec3f sample_point = this->mesh_samples.positions[sample_idx]; Vec3f sample_normal = this->mesh_samples.normals[sample_idx]; @@ -412,10 +411,9 @@ struct GlobalModelInfo { weight += (mesh_samples_radius - (position - sample_point).norm()); total_visibility += weight * mesh_samples_visibility[sample_idx]; total_weight += weight; - } - - return total_visibility / total_weight; + }); + return any_sample ? total_visibility / total_weight : 1.0f; } #ifdef DEBUG_FILES @@ -1627,7 +1625,7 @@ Vec3f place_on_loop(const std::vector &points, size_t index, cons void SeamPlacer::gather_seam_candidates(const PrintObject *po, const SeamPlacerImpl::GlobalModelInfo &global_model_info, PreciseSeam::PreciseSeamWarnings* warnings) { using namespace SeamPlacerImpl; - PrintObjectSeamData &seam_data = m_seam_per_object.emplace(po, PrintObjectSeamData { }).first->second; + PrintObjectSeamData &seam_data = m_seam_per_object.at(po); seam_data.layers.resize(po->layer_count()); tbb::parallel_for(tbb::blocked_range(0, po->layers().size()), @@ -1660,7 +1658,7 @@ void SeamPlacer::gather_seam_candidates(const PrintObject *po, const SeamPlacerI void SeamPlacer::calculate_candidates_visibility(const PrintObject *po, const SeamPlacerImpl::GlobalModelInfo &global_model_info) { - std::vector &layers = m_seam_per_object[po].layers; + std::vector &layers = m_seam_per_object.at(po).layers; tbb::parallel_for(tbb::blocked_range(0, layers.size()), [&layers, &global_model_info](tbb::blocked_range r) { for (size_t layer_idx = r.begin(); layer_idx < r.end(); ++layer_idx) { @@ -1676,7 +1674,7 @@ void SeamPlacer::calculate_overhangs_and_layer_embedding(const PrintObject *po) using namespace SeamPlacerImpl; using PerimeterDistancer = AABBTreeLines::LinesDistancer; - std::vector &layers = m_seam_per_object[po].layers; + std::vector &layers = m_seam_per_object.at(po).layers; tbb::parallel_for(tbb::blocked_range(0, layers.size()), [po, &layers](tbb::blocked_range r) { std::unique_ptr prev_layer_distancer; @@ -1896,7 +1894,7 @@ void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl:: #endif //gather vector of all seams on the print_object - pair of layer_index and seam__index within that layer - const std::vector &layers = m_seam_per_object[po].layers; + const std::vector &layers = m_seam_per_object.at(po).layers; // Share the largest nozzle diameter between contour bounds and corner protection. double max_nozzle_diameter = 0.0; for (double diameter : po->print()->config().nozzle_diameter.values) @@ -2112,7 +2110,33 @@ void SeamPlacer::init(const Print &print, std::function throw_if_can // Warning flags for Precise Seam processing — shared across all objects PreciseSeam::PreciseSeamWarnings precise_seam_warnings; + // The objects get their seams independently of each other, so they are processed concurrently. Their seam data + // and the usage tracking of their Precise Seam modifiers are created first: the objects only look them up. + struct ObjectSeams { + const PrintObject *po; + PrintObjectSeamData *seam_data; + std::vector precise_seam_strong_volumes; + std::vector precise_seam_weak_volumes; + }; + std::vector objects; + objects.reserve(print.objects().size()); for (const PrintObject *po : print.objects()) { + ObjectSeams &object = objects.emplace_back(ObjectSeams{ po, &m_seam_per_object[po], {}, {} }); + PreciseSeam::init_precise_seam_data( + object.precise_seam_strong_volumes, + object.precise_seam_weak_volumes, + object.seam_data->has_precise_seam_strong_volumes, + po->model_object()); + // Workers only set the usage flags. Several print objects of one model object share volumes, and + // try_emplace keeps what earlier ones recorded. + for (const ModelVolume* vol : object.precise_seam_strong_volumes) + precise_seam_warnings.modifier_usage.try_emplace(vol); + for (const ModelVolume* vol : object.precise_seam_weak_volumes) + precise_seam_warnings.modifier_usage.try_emplace(vol); + } + + auto place_seams = [this, &throw_if_canceled_func, &precise_seam_warnings](ObjectSeams &object) { + const PrintObject *po = object.po; throw_if_canceled_func(); SeamPosition configured_seam_preference = po->config().seam_position.value; SeamComparator comparator { configured_seam_preference }; @@ -2120,23 +2144,14 @@ void SeamPlacer::init(const Print &print, std::function throw_if_can { GlobalModelInfo global_model_info { }; gather_enforcers_blockers(global_model_info, po); - PreciseSeam::init_precise_seam_data( - global_model_info.precise_seam_strong_volumes, - global_model_info.precise_seam_weak_volumes, - m_seam_per_object[po].has_precise_seam_strong_volumes, - po->model_object()); + global_model_info.precise_seam_strong_volumes = std::move(object.precise_seam_strong_volumes); + global_model_info.precise_seam_weak_volumes = std::move(object.precise_seam_weak_volumes); // Slice each Precise Seam modifier once per object; both consumers read the cache. for (const ModelVolume* vol : global_model_info.precise_seam_strong_volumes) global_model_info.precise_seam_slices[vol] = PreciseSeam::prepare_modifier_slices(po->slice_single_volume_regions(vol)); for (const ModelVolume* vol : global_model_info.precise_seam_weak_volumes) global_model_info.precise_seam_slices[vol] = PreciseSeam::prepare_modifier_slices(po->slice_single_volume_regions(vol)); - // Register usage tracking before the parallel phase; workers only set its flags. Several print - // objects of one model object share volumes, and try_emplace keeps what earlier ones recorded. - for (const ModelVolume* vol : global_model_info.precise_seam_strong_volumes) - precise_seam_warnings.modifier_usage.try_emplace(vol); - for (const ModelVolume* vol : global_model_info.precise_seam_weak_volumes) - precise_seam_warnings.modifier_usage.try_emplace(vol); throw_if_canceled_func(); if (configured_seam_preference == spAligned || configured_seam_preference == spNearest || configured_seam_preference == spAlignedBack) { @@ -2169,7 +2184,7 @@ void SeamPlacer::init(const Print &print, std::function throw_if_can BOOST_LOG_TRIVIAL(debug) << "SeamPlacer: pick_seam_point : start"; //pick seam point - std::vector &layers = m_seam_per_object[po].layers; + std::vector &layers = object.seam_data->layers; tbb::parallel_for(tbb::blocked_range(0, layers.size()), [&layers, configured_seam_preference, comparator](tbb::blocked_range r) { for (size_t layer_idx = r.begin(); layer_idx < r.end(); ++layer_idx) { @@ -2195,13 +2210,24 @@ void SeamPlacer::init(const Print &print, std::function throw_if_can } // Restore precise seam positions that were potentially modified - if (m_seam_per_object[po].has_precise_seam_strong_volumes) { - PreciseSeam::restore_precise_seam_positions(m_seam_per_object[po].layers); + if (object.seam_data->has_precise_seam_strong_volumes) { + PreciseSeam::restore_precise_seam_positions(object.seam_data->layers); } #ifdef DEBUG_FILES - debug_export_points(m_seam_per_object[po].layers, po->bounding_box(), comparator); + debug_export_points(object.seam_data->layers, po->bounding_box(), comparator); #endif + }; + + if (objects.size() == 1) + place_seams(objects.front()); + else if (objects.size() > 1) { + // One object at a time, its serial steps (mesh decimation, building the search trees, aligning the seams) + // keep most of the cores idle. A few objects at once overlap them with the others' parallel steps; no more, + // as each holds its sampled mesh until it is done. + constexpr size_t max_objects_at_once = 4; + const size_t objects_per_task = (objects.size() + max_objects_at_once - 1) / max_objects_at_once; + parallel_for_first_error(objects.size(), objects_per_task, [&objects, &place_seams](size_t i) { place_seams(objects[i]); }); } // Prepare one combined Precise Seam warning; G-code export issues it. Keep it single: separate diff --git a/src/libslic3r/Layer.cpp b/src/libslic3r/Layer.cpp index f3d4be36b7..c8f6873673 100644 --- a/src/libslic3r/Layer.cpp +++ b/src/libslic3r/Layer.cpp @@ -444,7 +444,10 @@ void Layer::make_perimeters() append(clipped, diff_ex(l->raw_slices, group_slices)); clipped = union_ex(clipped); if (layerms.size() == 1 && clipped.empty()) { // optimization + // The perimeter generator appends to these, so perimeters made again (other walls) start from none, as a first + // slice does. (*layerm)->fill_surfaces.surfaces.clear(); + (*layerm)->fill_no_overlap_expolygons.clear(); (*layerm)->make_perimeters((*layerm)->slices, {*layerm}, &(*layerm)->fill_surfaces, &(*layerm)->fill_no_overlap_expolygons); (*layerm)->fill_expolygons = to_expolygons((*layerm)->fill_surfaces.surfaces); } else { diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 0ef98d09bd..6ffd003143 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -72,6 +72,7 @@ #include #include #include +#include #include #include #include @@ -2885,11 +2886,19 @@ int ModelVolume::extruder_id() const bool ModelVolume::is_splittable() const { - // the call mesh.is_splittable() is expensive, so cache the value to calculate it only once - if (m_is_splittable == -1) - m_is_splittable = its_is_splittable(this->mesh().its); - - return m_is_splittable == 1; + // The call its_is_splittable() is expensive, so cache the value to calculate it only once. The PrintObjects made from + // one ModelObject ask at the same time while they prepare their infill, so the cache is read and written under a + // lock; the call itself runs outside it, and only callers that find the cache empty at the same time make it twice. + static std::mutex cache_mutex; + { + std::scoped_lock lock(cache_mutex); + if (m_is_splittable != -1) + return m_is_splittable == 1; + } + const int splittable = its_is_splittable(this->mesh().its) ? 1 : 0; + std::scoped_lock lock(cache_mutex); + m_is_splittable = splittable; + return splittable == 1; } // BBS diff --git a/src/libslic3r/ParallelForFirstError.hpp b/src/libslic3r/ParallelForFirstError.hpp new file mode 100644 index 0000000000..97d6a0f27b --- /dev/null +++ b/src/libslic3r/ParallelForFirstError.hpp @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Slic3r { + +// Calls process(i) for every i in [0, count) on the TBB threads, items_per_task consecutive items in each task, and +// throws what calling them in order would: the exception of the lowest i that threw. Items after it that have not +// started yet are skipped, as a loop stops at its first error. +// +// Each task runs isolated: while it waits in the parallel loops of its own items, its thread takes no other task of +// this loop. Otherwise it could start another item meanwhile, which holds up the waiting item until that one is +// done, keeps more items in memory at once than there are threads, and breaks code that keeps a lock or thread-local +// scratch across a parallel loop. +template +void parallel_for_first_error(size_t count, size_t items_per_task, Process &&process) +{ + std::vector errors(count); + std::atomic first_error { count }; + tbb::parallel_for(tbb::blocked_range(0, count, items_per_task), [&](const tbb::blocked_range &range) { + tbb::this_task_arena::isolate([&]() { + for (size_t i = range.begin(); i < range.end() && i < first_error.load(std::memory_order_relaxed); ++ i) + try { + process(i); + } catch (...) { + errors[i] = std::current_exception(); + size_t lowest = first_error.load(std::memory_order_relaxed); + while (i < lowest && ! first_error.compare_exchange_weak(lowest, i, std::memory_order_relaxed)) + ; + } + }); + }, tbb::simple_partitioner()); + for (const std::exception_ptr &error : errors) + if (error) + std::rethrow_exception(error); +} + +} // namespace Slic3r diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 8976986627..8fc2047331 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -68,6 +68,7 @@ #include "Geometry/ConvexHull.hpp" #include "I18N.hpp" #include "LifecycleEvents.hpp" +#include "ParallelForFirstError.hpp" #include "ShortestPath.hpp" #include "Thread.hpp" #include "Time.hpp" @@ -3602,16 +3603,37 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": total object counts %1% in current print, need to slice %2%")%m_objects.size()%need_slicing_objects.size(); BOOST_LOG_TRIVIAL(info) << "Starting the slicing process." << log_memory_info(); + // Runs a step on the objects `needs` selects and `skip` on the others. A step of an object reads that object and + // the print's configuration only, which the support step has always relied on, so the objects run the step + // together: one after another, each object's serial parts and slowest layers kept most of the cores idle. + // A slicing pipeline plugin runs its hook between the objects, so with one active they keep their order. + // Nothing enforces that rule. In particular, the PrintObjects made from one ModelObject, one per distinct instance + // transformation, share its ModelVolumes, whose lazily filled caches are not guarded: a step must not fill them + // (ModelVolume::is_splittable() is the exception, under a lock). + auto for_each_object_step = [this](auto &&needs, auto &&process, auto &&skip) { + std::vector objects; + for (PrintObject *obj : m_objects) + if (! needs(obj)) + skip(obj); + else if (m_pipeline_plugin_active) + process(obj); + else + objects.push_back(obj); + if (objects.size() == 1) + process(objects.front()); + else if (objects.size() > 1) + parallel_for_first_error(objects.size(), 1, [&process, &objects](size_t i) { process(objects[i]); }); + }; if (!use_cache) { // Fire the SlicingPipeline hook for `obj` iff it just (re)computed `pstep` this pass. auto hook_after = [this](PrintObject* obj, bool was_done, PrintObjectStep pstep, SlicingPipelineStepPlugin sstep) { if (m_pipeline_plugin_active && !was_done && obj->is_step_done(pstep)) run_pipeline_hook(sstep, obj); }; + auto needs_slicing = [&need_slicing_objects](PrintObject *obj) { return need_slicing_objects.count(obj) != 0; }; // SlicingPipeline: dedicated slice loop so the Slice boundary is hookable before perimeters. - for (PrintObject *obj : m_objects) { - if (need_slicing_objects.count(obj) != 0) { + for_each_object_step(needs_slicing, [&](PrintObject *obj) { const bool was_done = obj->is_step_done(posSlice); obj->slice(); hook_after(obj, was_done, posSlice, SlicingPipelineStepPlugin::posSlice); @@ -3626,32 +3648,25 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) if (m_pipeline_plugin_active && !was_done && obj->is_step_done(posSlice)) for (Layer *layer : obj->layers()) layer->backup_untyped_slices(); - } else { + }, [](PrintObject *obj) { if (obj->set_started(posSlice)) obj->set_done(posSlice); // shared/duplicate — no hook - } - } - for (PrintObject *obj : m_objects) { - if (need_slicing_objects.count(obj) != 0) { + }); + for_each_object_step(needs_slicing, [&](PrintObject *obj) { const bool was_done = obj->is_step_done(posPerimeters); obj->make_perimeters(); // slice() inside is a no-op: posSlice already DONE hook_after(obj, was_done, posPerimeters, SlicingPipelineStepPlugin::posPerimeters); - } else { + }, [](PrintObject *obj) { if (obj->set_started(posPerimeters)) obj->set_done(posPerimeters); - } - } - for (PrintObject *obj : m_objects) { - if (need_slicing_objects.count(obj) != 0) { + }); + for_each_object_step(needs_slicing, [&](PrintObject *obj) { const bool was_done = obj->is_step_done(posEstimateCurledExtrusions); obj->estimate_curled_extrusions(); hook_after(obj, was_done, posEstimateCurledExtrusions, SlicingPipelineStepPlugin::posEstimateCurledExtrusions); - } - else { + }, [](PrintObject *obj) { if (obj->set_started(posEstimateCurledExtrusions)) obj->set_done(posEstimateCurledExtrusions); - } - } - for (PrintObject *obj : m_objects) { - if (need_slicing_objects.count(obj) != 0) { + }); + for_each_object_step(needs_slicing, [&](PrintObject *obj) { // split prepare_infill (fill-surface prep) from infill (make_fills) so a // plugin can mutate fill surfaces at the PrepareInfill seam and have make_fills // consume them (unlike the Infill seam, which fires after the fills are already @@ -3663,25 +3678,20 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) const bool was_done = obj->is_step_done(posInfill); obj->infill(); hook_after(obj, was_done, posInfill, SlicingPipelineStepPlugin::posInfill); - } - else { + }, [](PrintObject *obj) { if (obj->set_started(posPrepareInfill)) obj->set_done(posPrepareInfill); if (obj->set_started(posInfill)) obj->set_done(posInfill); - } - } - for (PrintObject *obj : m_objects) { - if (need_slicing_objects.count(obj) != 0) { + }); + for_each_object_step(needs_slicing, [&](PrintObject *obj) { const bool was_done = obj->is_step_done(posIroning); obj->ironing(); hook_after(obj, was_done, posIroning, SlicingPipelineStepPlugin::posIroning); - } - else { + }, [](PrintObject *obj) { if (obj->set_started(posIroning)) obj->set_done(posIroning); - } - } + }); // Z-Contouring for (PrintObject *obj : m_objects) { @@ -3729,17 +3739,14 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) && m_objects[i]->is_step_done(posSupportMaterial)) run_pipeline_hook(SlicingPipelineStepPlugin::posSupportMaterial, m_objects[i]); - for (PrintObject* obj : m_objects) { - if (need_slicing_objects.count(obj) != 0) { + for_each_object_step(needs_slicing, [&](PrintObject *obj) { const bool was_done = obj->is_step_done(posDetectOverhangsForLift); obj->detect_overhangs_for_lift(); hook_after(obj, was_done, posDetectOverhangsForLift, SlicingPipelineStepPlugin::posDetectOverhangsForLift); - } - else { + }, [](PrintObject *obj) { if (obj->set_started(posDetectOverhangsForLift)) obj->set_done(posDetectOverhangsForLift); - } - } + }); } else { for (PrintObject *obj : m_objects) { @@ -4104,9 +4111,9 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) } } //BBS - for (PrintObject *obj : m_objects) { - if (((!use_cache)&&(need_slicing_objects.count(obj) != 0)) - || (use_cache &&(re_slicing_objects.count(obj) != 0))){ + for_each_object_step([&](PrintObject *obj) { + return (!use_cache && need_slicing_objects.count(obj) != 0) || (use_cache && re_slicing_objects.count(obj) != 0); + }, [&](PrintObject *obj) { const bool was_done = obj->is_step_done(posSimplifyPath); obj->simplify_extrusion_path(); // Unlike every other seam (all inside the `if (!use_cache)` block above), this loop is @@ -4114,16 +4121,14 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) // explicitly here to keep hooks from ever firing on cache-loaded (plugin-final) objects. if (!use_cache && m_pipeline_plugin_active && !was_done && obj->is_step_done(posSimplifyPath)) run_pipeline_hook(SlicingPipelineStepPlugin::posSimplifyPath, obj); - } - else { + }, [](PrintObject *obj) { if (obj->set_started(posSimplifyPath)) obj->set_done(posSimplifyPath); if (obj->set_started(posSimplifyInfill)) obj->set_done(posSimplifyInfill); if (obj->set_started(posSimplifySupportPath)) obj->set_done(posSimplifySupportPath); - } - } + }); // BBS bool has_adaptive_layer_height = false; diff --git a/src/libslic3r/PrintBase.cpp b/src/libslic3r/PrintBase.cpp index a749c27cf5..964355eba7 100644 --- a/src/libslic3r/PrintBase.cpp +++ b/src/libslic3r/PrintBase.cpp @@ -123,6 +123,7 @@ std::string PrintBase::output_filepath(const std::string &path, const std::strin //BBS: move set_status from hpp to cpp void PrintBase::set_status(int percent, const std::string &message, unsigned int flags, int warning_step) const { + std::scoped_lock lock(m_status_callback_mutex); if (m_status_callback) m_status_callback(SlicingStatus(percent, message, flags, warning_step)); else @@ -132,6 +133,7 @@ void PrintBase::set_status(int percent, const std::string &message, unsigned in void PrintBase::status_update_warnings(int step, PrintStateBase::WarningLevel warning_level, const std::string &message, const PrintObjectBase* print_object, PrintStateBase::SlicingNotificationType message_id) { + std::scoped_lock lock(m_status_callback_mutex); if (this->m_status_callback) { auto status = print_object ? SlicingStatus(*print_object, step, message, message_id, warning_level) : SlicingStatus(*this, step, message, message_id, warning_level); m_status_callback(status); @@ -145,9 +147,9 @@ void PrintBase::status_update_warnings(int step, PrintStateBase::WarningLevel wa const std::string& message, PrintObjectBase &object, PrintStateBase::SlicingNotificationType message_id) { //BBS: add object it into slicing status - if (this->m_status_callback) { + std::scoped_lock lock(m_status_callback_mutex); + if (this->m_status_callback) m_status_callback(SlicingStatus(object, step, message, message_id, warning_level)); - } else if (!message.empty()) BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(", PrintObject warning: %1%\n")% message.c_str(); } diff --git a/src/libslic3r/PrintBase.hpp b/src/libslic3r/PrintBase.hpp index b3d10bab77..392c0140dd 100644 --- a/src/libslic3r/PrintBase.hpp +++ b/src/libslic3r/PrintBase.hpp @@ -481,11 +481,11 @@ public: }; typedef std::function status_callback_type; // Default status console print out in the form of percent => message. - void set_status_default() { m_status_callback = nullptr; } + void set_status_default() { set_status_callback(nullptr); } // No status output or callback whatsoever, useful mostly for automatic tests. - void set_status_silent() { m_status_callback = [](const SlicingStatus&){}; } + void set_status_silent() { set_status_callback([](const SlicingStatus&){}); } // Register a custom status callback. - void set_status_callback(status_callback_type cb) { m_status_callback = cb; } + void set_status_callback(status_callback_type cb) { std::scoped_lock lock(m_status_callback_mutex); m_status_callback = std::move(cb); } // Calls a registered callback to update the status, or print out the default message. void set_status(int percent, const std::string &message, unsigned int flags = SlicingStatus::DEFAULT, int warning_step = -1) const; @@ -583,6 +583,9 @@ private: // The mutex will be used to guard the worker thread against entering a stage // while the data influencing the stage is modified. mutable std::mutex m_state_mutex; + // Held while the status callback runs or is replaced: the objects run their steps concurrently, a callback may keep + // state of its own, such as the warnings the command line collects, and the GUI replaces it while a slice runs. + mutable std::mutex m_status_callback_mutex; friend PrintTryCancel; }; diff --git a/tests/fff_print/CMakeLists.txt b/tests/fff_print/CMakeLists.txt index 1300e1be8d..9963006f01 100644 --- a/tests/fff_print/CMakeLists.txt +++ b/tests/fff_print/CMakeLists.txt @@ -6,6 +6,7 @@ add_executable(${_TEST_NAME}_tests test_adaptive_pressure_advance.cpp test_bridge.cpp test_calib.cpp + test_conflict_checker.cpp test_cooling.cpp test_extrusion_entity.cpp test_extrusion_processor.cpp diff --git a/tests/fff_print/test_conflict_checker.cpp b/tests/fff_print/test_conflict_checker.cpp new file mode 100644 index 0000000000..2bccd58ce5 --- /dev/null +++ b/tests/fff_print/test_conflict_checker.cpp @@ -0,0 +1,75 @@ +#include +#include + +#include "libslic3r/Config.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" + +#include +#include + +#include "test_helpers.hpp" + +using namespace Slic3r; +using namespace Slic3r::Test; + +namespace { + +// Two 10 mm cubes printed as separate objects, the second shifted along X by `offset`, at the +// positions given (not arranged apart). +ConflictResultOpt conflict_between_cubes(double offset) +{ + TriangleMesh first = make_cube(10., 10., 10.); + TriangleMesh second = make_cube(10., 10., 10.); + first.translate(50.f, 50.f, 0.f); + second.translate(float(50. + offset), 50.f, 0.f); + + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ { "layer_height", "0.2" }, { "initial_layer_print_height", "0.2" } }); + + Print print; + Model model; + init_print({ std::move(first), std::move(second) }, print, model, config, nullptr, false); + print.process(); + return print.get_conflict_result(); +} + +} // namespace + +TEST_CASE("Objects whose extrusions cross are reported as a path conflict", "[ConflictChecker]") +{ + // A 5 mm shift puts half of each cube inside the other, so their walls cross on every layer of the + // 10 mm high cubes. + const ConflictResultOpt conflict = conflict_between_cubes(5.); + REQUIRE(conflict.has_value()); + CHECK(conflict->_obj1 != conflict->_obj2); + CHECK(conflict->_height <= 10.); +} + +TEST_CASE("Objects apart from each other have no path conflict", "[ConflictChecker]") +{ + // 30 mm between the cube origins leaves a 20 mm gap between the 10 mm cubes. + CHECK_FALSE(conflict_between_cubes(30.).has_value()); +} + +TEST_CASE("Copies of an object printed over each other are reported as a path conflict", "[ConflictChecker]") +{ + // Two instances of one 10 mm cube: not arranged, both stay at the origin of the object; arranged, they are + // placed apart. + const bool arranged = GENERATE(false, true); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ { "layer_height", "0.2" }, { "initial_layer_print_height", "0.2" } }); + + TriangleMesh cube = make_cube(10., 10., 10.); + cube.translate(50.f, 50.f, 0.f); + Print print; + Model model; + std::vector meshes; + meshes.emplace_back(std::move(cube)); + init_print(std::move(meshes), print, model, config, nullptr, arranged, 2); + print.process(); + CHECK(print.get_conflict_result().has_value() == ! arranged); +} diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 2b6dbfcdc6..dd4eea8a93 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -36,6 +36,8 @@ #include "libslic3r/Support/BeltFloorContext.hpp" #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/ExtrusionEntity.hpp" +#include "libslic3r/ExtrusionEntityCollection.hpp" +#include "libslic3r/Point.hpp" #include "libslic3r/Polyline.hpp" #include #include @@ -56,11 +58,15 @@ #include #include #include +#include +#include +#include #include #include #include #include #include +#include #include #include #include @@ -69,6 +75,7 @@ #include "libslic3r/SurfaceCollection.hpp" #include "libslic3r/BoundingBox.hpp" #include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Geometry.hpp" using namespace Slic3r; using namespace Slic3r::Test; @@ -3517,6 +3524,128 @@ TEST_CASE("Height range settings follow a Z shrinkage change that comes with a m namespace { +// Four distinct objects: they run each slicing step together. +std::vector distinct_objects() +{ + std::vector meshes; + for (TestMesh m : { TestMesh::cube_with_hole, TestMesh::pyramid, TestMesh::sphere_50mm, TestMesh::overhang }) + meshes.emplace_back(Test::mesh(m)); + return meshes; +} + +// The moves of a G-code, without the export time in the header or the configuration block. The block also lists the +// filament maps slicing writes back, which the GUI passes to the next apply() and these tests do not. +std::string toolpaths(const std::string &gcode) +{ + std::istringstream in(gcode); + std::string out, line; + bool config = false; + while (std::getline(in, line)) { + if (line.rfind("; CONFIG_BLOCK_START", 0) == 0) + config = true; + else if (line.rfind("; CONFIG_BLOCK_END", 0) == 0) + config = false; + else if (! config && line.rfind("; generated by", 0) != 0) + out += line + '\n'; + } + return out; +} + +std::string fresh_slice_toolpaths(const DynamicPrintConfig &config) +{ + Print print; + Model model; + Test::init_print(distinct_objects(), print, model, config); + return toolpaths(Test::gcode(print)); +} + +// Copies of a model of a cube with a hole, one at each scale, sliced together. Each scale gets a PrintObject of its +// own, all of them made from the one ModelObject. With `only` set, the other copies stay in the model but do not +// print, so that copy's PrintObject is the only one and keeps the coordinates it has among the others. +void slice_copies_at_scales(const std::vector &scales, const DynamicPrintConfig &config, Model &model, Print &print, + std::optional only = std::nullopt) +{ + ModelObject *object = model.add_object(); + object->add_volume(Test::mesh(TestMesh::cube_with_hole)); + for (size_t i = 0; i < scales.size(); ++ i) { + ModelInstance *instance = object->add_instance(); + instance->set_scaling_factor(Vec3d(scales[i], scales[i], scales[i])); + instance->set_offset(Vec3d(40. + 30. * double(i), 100., 0.)); + instance->printable = ! only || *only == i; + } + object->ensure_on_bed(); + print.auto_assign_extruders(object); + print.apply(model, config); + print.set_status_silent(); + print.process(); +} + +// The perimeters and the infill of every layer of a PrintObject, in its own coordinates. +std::string layer_extrusions(const PrintObject &object) +{ + std::ostringstream out; + for (const Layer *layer : object.layers()) { + out << "layer " << layer->print_z << '\n'; + for (const LayerRegion *layerm : layer->regions()) + for (const ExtrusionEntityCollection *extrusions : { &layerm->perimeters, &layerm->fills }) + for (const ExtrusionEntity *extrusion : extrusions->flatten().entities) { + for (const Point &point : extrusion->as_polyline().points) + out << point.x() << ',' << point.y() << ' '; + out << '\n'; + } + } + return out.str(); +} + +// The project of an Assembly crash report: one object of a 27 mm cube and a cylinder of the same size lying along X, +// in an instance scaled 2x along X, on the bed. +ModelObject *add_cube_and_lying_cylinder(Model &model) +{ + ModelObject *object = model.add_object(); + object->add_volume(cube(27.))->set_offset(Vec3d(0., 18., 0.)); + ModelVolume *cylinder = object->add_volume(make_cylinder(13.5, 27.)); + cylinder->set_rotation(Vec3d(0., 0.5 * PI, 0.)); + cylinder->set_offset(Vec3d(0., -18., 0.)); + ModelInstance *instance = object->add_instance(); + instance->set_scaling_factor(Vec3d(2., 1., 1.)); + instance->set_offset(Vec3d(100., 100., 13.5)); + return object; +} + +// The Assembly tool's Parallel with the cube's top face picked first and an end face of the cylinder second, which +// GLGizmoMeasure::set_to_parallel() does by turning the cylinder until that end face points down. +// - Turning its whole world transformation about its origin, as set_to_parallel() does now, keeps the cylinder round +// and 54 mm long. It stands about its centre, 13.5 mm above the bed, so 13.5 mm of it goes below the bed. +// - Setting its rotation only, as the crash build's set_to_parallel() did, lets the instance's scaling stretch it +// along X instead: it stands 27 mm tall on the bed, an ellipse twice as wide as it is deep. +void turn_cylinder_end_face_down(ModelObject &object, const Vec3d &end_face_normal, bool whole_transformation) +{ + ModelVolume &cylinder = *object.volumes.back(); + const Transform3d instance = object.instances.front()->get_matrix(); + Transform3d world = instance * cylinder.get_matrix(); + Vec3d axis; + double angle; + Matrix3d rotation; + Geometry::rotation_from_two_vectors(end_face_normal, -Vec3d::UnitZ(), axis, angle, &rotation); + if (whole_transformation) { + world.linear() = rotation * world.linear().eval(); + cylinder.set_transformation(instance.inverse() * world); + } else { + const Transform3d turned = Transform3d(rotation) * Geometry::Transformation(world).get_rotation_matrix(); + const Transform3d instance_rotation = object.instances.front()->get_transformation().get_rotation_matrix(); + cylinder.set_rotation(Geometry::extract_euler_angles(instance_rotation.inverse() * turned)); + } + object.invalidate_bounding_box(); +} + +// The area of the islands of the lowest layer at or above z, in mm². +double island_area_at(const PrintObject &object, double z) +{ + const auto it = std::find_if(object.layers().begin(), object.layers().end(), [z](const Layer *layer) { return layer->print_z >= z; }); + REQUIRE(it != object.layers().end()); + return area((*it)->lslices) * SCALING_FACTOR * SCALING_FACTOR; +} + // 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) { @@ -3560,6 +3689,184 @@ DynamicPrintConfig machine_inventory_config() } // namespace +TEST_CASE("Re-processing several objects after a setting change gives the toolpaths of a fresh slice", "[Print]") +{ + // The settings invalidate the perimeters, the infill regions and everything after them, the infill, the ironing, + // or only the G-code export. + const auto [key, before, after] = GENERATE(table({ + { "wall_loops", "2", "3" }, + { "top_shell_layers", "3", "5" }, + { "sparse_infill_density", "15%", "40%" }, + { "sparse_infill_pattern", "grid", "gyroid" }, + { "ironing_type", "no ironing", "top" }, + { "seam_position", "aligned", "nearest" }, + { "outer_wall_speed", "60", "40" }, + })); + INFO(key << ": " << before << " -> " << after); + + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + // init_print() turns the G-code comments on, the second apply() has to keep them. + config.set_deserialize_strict({ { "gcode_comments", "1" }, { key, before } }); + Print print; + Model model; + Test::init_print(distinct_objects(), print, model, config); + REQUIRE(print.objects().size() == 4); + Test::gcode(print); + + config.set_deserialize_strict(key, after); + print.apply(model, config); + const std::string reprocessed = toolpaths(Test::gcode(print)); + + REQUIRE(! reprocessed.empty()); + CHECK(reprocessed == fresh_slice_toolpaths(config)); +} + +TEST_CASE("Slicing several objects cancelled from another thread and run again gives the toolpaths of a fresh slice", "[Print]") +{ + // As the GUI does it: the print is processed on a thread of its own, which the status updates reach from the + // threads processing the objects, and a cancel makes process() throw before the print is processed again. + const int cancel_at_update = GENERATE(1, 3, 6, 9); + INFO("cancelled at status update " << cancel_at_update); + + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ { "gcode_comments", "1" } }); + Print print; + Model model; + Test::init_print(distinct_objects(), print, model, config); + REQUIRE(print.objects().size() == 4); + + std::atomic updates { 0 }; + print.set_status_callback([&print, &updates, cancel_at_update](const PrintBase::SlicingStatus &) { + if (++ updates == cancel_at_update) + print.cancel(); + }); + bool canceled = false; + bool other_error = false; + std::thread background([&print, &canceled, &other_error] { + try { + print.process(); + } catch (const CanceledException &) { + canceled = true; + } catch (...) { + other_error = true; + } + }); + background.join(); + CHECK(canceled); + CHECK_FALSE(other_error); + + print.restart(); + const std::string resumed = toolpaths(Test::gcode(print)); + REQUIRE(! resumed.empty()); + CHECK(resumed == fresh_slice_toolpaths(config)); +} + +TEST_CASE("Slicing several objects calls the status callback one status at a time", "[Print]") +{ + // The objects run their steps concurrently, while a callback such as the command line's appends the warnings + // to a vector of its own. + Print print; + Model model; + Test::init_print(distinct_objects(), print, model, DynamicPrintConfig::full_print_config()); + REQUIRE(print.objects().size() == 4); + + std::atomic calls { 0 }; + std::atomic running { 0 }; + std::atomic overlapped { false }; + print.set_status_callback([&calls, &running, &overlapped](const PrintBase::SlicingStatus &) { + ++ calls; + if (++ running > 1) + overlapped = true; + // Stay in the callback long enough for the other objects to report meanwhile. + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + -- running; + }); + print.process(); + + REQUIRE(calls > 1); + CHECK_FALSE(overlapped); +} + +TEST_CASE("Slicing copies of one object at different scales gives each copy the layers it gets alone", "[Print]") +{ + // The PrintObjects of the copies share the volumes of their ModelObject and run each slicing step together, while + // a copy that is the only one printing runs its steps by itself. + const std::vector scales { 1., 0.9, 0.8, 0.7 }; + const DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + Model model; + Print print; + slice_copies_at_scales(scales, config, model, print); + REQUIRE(print.objects().size() == scales.size()); + + for (size_t i = 0; i < scales.size(); ++ i) { + const double scale = scales[i]; + INFO("scale " << scale); + Model alone_model; + Print alone; + slice_copies_at_scales(scales, config, alone_model, alone, i); + REQUIRE(alone.objects().size() == 1); + const auto copy = std::find_if(print.objects().begin(), print.objects().end(), [scale](const PrintObject *object) { + return std::abs(object->instances().front().model_instance->get_scaling_factor().x() - scale) < EPSILON; + }); + REQUIRE(copy != print.objects().end()); + // The copy has walls, so the layers compare extrusions and not only their heights. + REQUIRE(std::any_of((*copy)->layers().begin(), (*copy)->layers().end(), [](const Layer *layer) { + return ! layer->regions().empty() && ! layer->regions().front()->perimeters.empty(); + })); + CHECK(layer_extrusions(**copy) == layer_extrusions(*alone.objects().front())); + } +} + +TEST_CASE("Slicing after the Assembly tool's Parallel turns a part of a scaled object gives the toolpaths of a fresh slice", "[Print]") +{ + // The steps of a crash report: Parallel turns the cylinder, and the GUI applies and validates the changed model. + // The GUI processes the print only while the Preview is open, so it may have been processed before or not. The + // crash build set the cylinder's rotation only, and either end face can be the one picked. + const bool whole_transformation = GENERATE(false, true); + const double end_face = GENERATE(1., -1.); + const bool processed_before = GENERATE(false, true); + INFO((whole_transformation ? "whole transformation" : "rotation only") << ", end face normal " << end_face << " * X, " + << (processed_before ? "processed" : "not processed") << " before"); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + // validate() wants the extruder position reset at each layer for the default relative extrusion. + { "layer_change_gcode", "G92 E0" }, + }); + Model model; + ModelObject *object = add_cube_and_lying_cylinder(model); + Print print; + print.apply(model, config); + REQUIRE_THAT(print.validate().string, Catch::Matchers::Equals(std::string())); + if (processed_before) + Test::gcode(print); + + turn_cylinder_end_face_down(*object, end_face * Vec3d::UnitX(), whole_transformation); + print.apply(model, config); + CHECK_THAT(print.validate().string, Catch::Matchers::Equals(std::string())); + const std::string sliced = toolpaths(Test::gcode(print)); + + // Only what is above the bed prints. Up to the cube's top at 27 mm, that is its 54 x 27 mm and the cylinder's + // cross-section: the round cylinder's circle of radius 13.5 mm, alone above the cube up to 40.5 mm, or the stretched + // cylinder's ellipse, twice as wide, which ends at 27 mm. + REQUIRE(print.objects().size() == 1); + const PrintObject &print_object = *print.objects().front(); + REQUIRE(! print_object.layers().empty()); + const double cylinder_area = whole_transformation ? PI * 13.5 * 13.5 : PI * 27. * 13.5; + CHECK_THAT(print_object.layers().back()->print_z, Catch::Matchers::WithinAbs(whole_transformation ? 40.5 : 27., 0.2)); + CHECK_THAT(island_area_at(print_object, 13.5), Catch::Matchers::WithinRel(54. * 27. + cylinder_area, 0.01)); + if (whole_transformation) + CHECK_THAT(island_area_at(print_object, 34.), Catch::Matchers::WithinRel(cylinder_area, 0.01)); + + Model fresh_model; + turn_cylinder_end_face_down(*add_cube_and_lying_cylinder(fresh_model), end_face * Vec3d::UnitX(), whole_transformation); + Print fresh; + fresh.apply(fresh_model, config); + REQUIRE(! sliced.empty()); + CHECK(sliced == toolpaths(Test::gcode(fresh))); +} + // 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. diff --git a/tests/fff_print/test_seam_placer.cpp b/tests/fff_print/test_seam_placer.cpp index 594b461a25..4a6f1d6699 100644 --- a/tests/fff_print/test_seam_placer.cpp +++ b/tests/fff_print/test_seam_placer.cpp @@ -1538,3 +1538,37 @@ TEST_CASE("Seam extraction preserves unknown boundary roles for open extrusion p REQUIRE(perimeters.size() == 1); CHECK(perimeters.front().contour_reliable == !open); } + +TEST_CASE("Seams are picked on every loop of every object when init() places several objects at once", "[SeamPlacer]") +{ + // Random seams are picked by the workers of each object alone, and they finalize every loop. Sixteen objects make + // four tasks of four objects each. + const size_t object_count = 16; + std::vector meshes; + for (size_t i = 0; i < object_count; ++ i) + meshes.emplace_back(its_make_cube(10, 10, 1)); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict("seam_position", "random"); // Random needs no visibility ray tracing. + Model model; + Print print; + Test::init_print(std::move(meshes), print, model, config); + REQUIRE(print.objects().size() == object_count); + print.process(); + + SeamPlacer placer; + placer.init(print, [] {}); + + size_t loops = 0, picked = 0; + for (const PrintObject *object : print.objects()) { + const std::vector &layers = placer.m_seam_per_object.at(object).layers; + REQUIRE(layers.size() == object->layers().size()); + for (const PrintObjectSeamData::LayerSeams &layer : layers) + for (const SeamPlacerImpl::Perimeter &perimeter : layer.perimeters) { + ++ loops; + if (perimeter.finalized) + ++ picked; + } + } + REQUIRE(loops >= object_count); + CHECK(picked == loops); +} diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index e2f39a622f..7255e5d305 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -37,6 +37,7 @@ add_executable(${_TEST_NAME}_tests test_drc.cpp test_gcodereader.cpp test_toolordering_nozzle_group.cpp + test_parallel_for_first_error.cpp test_parallel_resolve.cpp test_preset_bundle_loading.cpp test_preset_collection.cpp @@ -47,6 +48,7 @@ add_executable(${_TEST_NAME}_tests test_preset_options.cpp test_edge_grid.cpp test_elephant_foot_compensation.cpp + test_expolygon.cpp test_exclusion_volumes.cpp test_fill_corner_smoothing.cpp test_filament_mixer.cpp diff --git a/tests/libslic3r/test_aabbindirect.cpp b/tests/libslic3r/test_aabbindirect.cpp index 852583fa47..a4787f362a 100644 --- a/tests/libslic3r/test_aabbindirect.cpp +++ b/tests/libslic3r/test_aabbindirect.cpp @@ -1,13 +1,18 @@ #include #include #include +#include #include #include #include #include +#include +#include +#include #include #include "libslic3r/Point.hpp" +#include "libslic3r/libslic3r.h" using namespace Slic3r; @@ -63,3 +68,125 @@ TEST_CASE("Building a tree over a box, ray caster and closest query", "[AABBIndi REQUIRE(closest_point.y() == Catch::Approx(0.5)); REQUIRE(closest_point.z() == Catch::Approx(1.)); } + +namespace { + +// The depth-first, left to right traversal intersect_ray_first_hit() used before it visited the nearest +// child first. The ordered traversal must return the very same hit. +template +bool reference_first_hit(const RayIntersectorType &ray_intersector, size_t node_idx, Scalar min_t, igl::Hit &hit) +{ + const auto &node = ray_intersector.tree.node(node_idx); + if (! AABBTreeIndirect::detail::ray_box_intersect_invdir(ray_intersector.origin, ray_intersector.invdir, + node.bbox.template cast(), Scalar(0), min_t)) + return false; + if (node.is_leaf()) { + auto face = ray_intersector.faces[node.idx]; + double t, u, v; + if (AABBTreeIndirect::detail::intersect_triangle(ray_intersector.origin, ray_intersector.dir, + ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)], + ray_intersector.vertices[face(2)], t, u, v, ray_intersector.eps) && + t > 0.) { + hit = igl::Hit{int(node.idx), -1, float(u), float(v), float(t)}; + return true; + } + return false; + } + igl::Hit left_hit; + igl::Hit right_hit; + bool left_ret = reference_first_hit(ray_intersector, node_idx * 2 + 1, min_t, left_hit); + if (left_ret && left_hit.t < min_t) { + min_t = left_hit.t; + hit = left_hit; + } else + left_ret = false; + bool right_ret = reference_first_hit(ray_intersector, node_idx * 2 + 2, min_t, right_hit); + if (right_ret && right_hit.t < min_t) + hit = right_hit; + else + right_ret = false; + return left_ret || right_ret; +} + +// Unit cube faces split into an n x n grid of triangles: many coplanar triangles sharing edges, so rays +// through edges and vertices hit several triangles at the same distance. +indexed_triangle_set grid_cube(int n) +{ + indexed_triangle_set its; + for (int axis = 0; axis < 3; ++axis) + for (int side = 0; side < 2; ++side) + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + auto vertex = [&](int a, int b) { + Vec3f p; + p[axis] = float(side); + p[(axis + 1) % 3] = float(a) / n; + p[(axis + 2) % 3] = float(b) / n; + its.vertices.emplace_back(p); + return int(its.vertices.size()) - 1; + }; + int v0 = vertex(i, j), v1 = vertex(i + 1, j), v2 = vertex(i + 1, j + 1), v3 = vertex(i, j + 1); + its.indices.emplace_back(v0, v1, v2); + its.indices.emplace_back(v0, v2, v3); + } + return its; +} + +} // namespace + +TEST_CASE("First ray hit matches the depth-first search", "[AABBIndirect]") +{ + std::mt19937 rng(42); + std::uniform_real_distribution coord(-1.5, 2.5); + std::uniform_real_distribution unit(-1., 1.); + + indexed_triangle_set soup; + for (int i = 0; i < 300; ++i) { + Vec3f a(coord(rng), coord(rng), coord(rng)); + int base = int(soup.vertices.size()); + soup.vertices.emplace_back(a); + soup.vertices.emplace_back(a + Vec3f(unit(rng), unit(rng), unit(rng)) * 0.5f); + soup.vertices.emplace_back(a + Vec3f(unit(rng), unit(rng), unit(rng)) * 0.5f); + soup.indices.emplace_back(base, base + 1, base + 2); + } + const indexed_triangle_set mesh = GENERATE_COPY(grid_cube(8), its_make_sphere(1., PI / 20.), soup); + + const auto tree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(mesh.vertices, mesh.indices); + REQUIRE(! tree.empty()); + + // Directions with zero components make the inverse direction infinite. Origins on the grid, aimed + // along the axes or the diagonals, put the rays through shared edges and vertices. + std::vector> rays; + const Vec3d axis_dirs[] = {Vec3d::UnitX(), -Vec3d::UnitX(), Vec3d::UnitY(), -Vec3d::UnitY(), Vec3d::UnitZ(), -Vec3d::UnitZ(), + Vec3d(1., 1., 0.).normalized(), Vec3d(1., 1., 1.).normalized(), Vec3d(-1., 0., 1.).normalized()}; + for (int i = -2; i <= 10; ++i) + for (int j = -2; j <= 10; ++j) + for (const Vec3d &dir : axis_dirs) + rays.emplace_back(Vec3d(i / 8., j / 8., -1.) - dir * 2., dir); + // Random rays aimed at random mesh vertices, so that most of them hit. + std::uniform_int_distribution vertex_idx(0, mesh.vertices.size() - 1); + for (int i = 0; i < 20000; ++i) { + const Vec3d origin(coord(rng), coord(rng), coord(rng)); + const Vec3d target = mesh.vertices[vertex_idx(rng)].cast() + Vec3d(unit(rng), unit(rng), unit(rng)) * 0.01; + if ((target - origin).squaredNorm() > 1e-6) + rays.emplace_back(origin, (target - origin).normalized()); + } + + size_t hits = 0; + size_t mismatches = 0; + for (const auto &[origin, dir] : rays) { + igl::Hit hit{-1, -1, 0.f, 0.f, 0.f}; + const bool found = AABBTreeIndirect::intersect_ray_first_hit(mesh.vertices, mesh.indices, tree, origin, dir, hit); + + const auto ray_intersector = AABBTreeIndirect::detail::RayIntersector, Vec3d>{ + mesh.vertices, mesh.indices, tree, origin, dir, Vec3d(dir.cwiseInverse()), 0.000001}; + igl::Hit expected{-1, -1, 0.f, 0.f, 0.f}; + const bool expected_found = reference_first_hit(ray_intersector, size_t(0), std::numeric_limits::infinity(), expected); + + hits += found; + if (found != expected_found || (found && (hit.id != expected.id || hit.t != expected.t || hit.u != expected.u || hit.v != expected.v))) + ++mismatches; + } + CHECK(hits > rays.size() / 2); + CHECK(mismatches == 0); +} diff --git a/tests/libslic3r/test_expolygon.cpp b/tests/libslic3r/test_expolygon.cpp new file mode 100644 index 0000000000..516c96f17b --- /dev/null +++ b/tests/libslic3r/test_expolygon.cpp @@ -0,0 +1,65 @@ +#include + +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/Polyline.hpp" +#include "libslic3r/libslic3r.h" + +#include +#include + +using namespace Slic3r; + +namespace { + +Polygon square(double x0, double y0, double size) +{ + return Polygon{ Point::new_scale(x0, y0), Point::new_scale(x0 + size, y0), Point::new_scale(x0 + size, y0 + size), + Point::new_scale(x0, y0 + size) }; +} + +Polyline polyline(std::initializer_list points) +{ + Polyline out; + for (const Vec2d &p : points) + out.points.emplace_back(Point::new_scale(p.x(), p.y())); + return out; +} + +// A 10 mm square with a 2 mm square hole at its center. +ExPolygon square_with_hole() +{ + ExPolygon expoly(square(0., 0., 10.)); + Polygon hole = square(4., 4., 2.); + hole.reverse(); + expoly.holes.emplace_back(std::move(hole)); + return expoly; +} + +} // namespace + +TEST_CASE("A polyline running inside an expolygon is contained in it", "[ExPolygon]") +{ + const ExPolygon expoly = square_with_hole(); + CHECK(expoly.contains(polyline({ { 1., 1. }, { 9., 1. }, { 9., 9. } }))); +} + +TEST_CASE("A polyline leaving an expolygon is not contained in it", "[ExPolygon]") +{ + const ExPolygon expoly = square_with_hole(); + // Out through the contour, far beyond the bounding box and just past it. + CHECK_FALSE(expoly.contains(polyline({ { 1., 1. }, { 20., 1. } }))); + CHECK_FALSE(expoly.contains(polyline({ { 1., 1. }, { 10.01, 1. } }))); + // Across the hole. + CHECK_FALSE(expoly.contains(polyline({ { 1., 5. }, { 9., 5. } }))); +} + +TEST_CASE("A polyline within the bounding box but outside of a concave expolygon is not contained in it", "[ExPolygon]") +{ + // An L shape: the 10 mm square without its top right 5 mm quarter. + const ExPolygon l_shape(Polygon{ Point::new_scale(0., 0.), Point::new_scale(10., 0.), Point::new_scale(10., 5.), + Point::new_scale(5., 5.), Point::new_scale(5., 10.), Point::new_scale(0., 10.) }); + CHECK_FALSE(l_shape.contains(polyline({ { 1., 1. }, { 9., 1. }, { 9., 9. } }))); + CHECK(l_shape.contains(polyline({ { 1., 1. }, { 9., 1. }, { 4., 4. }, { 1., 9. } }))); +} diff --git a/tests/libslic3r/test_model.cpp b/tests/libslic3r/test_model.cpp index 9c3b9f0f35..8b0fcff8a9 100644 --- a/tests/libslic3r/test_model.cpp +++ b/tests/libslic3r/test_model.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include "libslic3r/TriangleMesh.hpp" @@ -135,6 +136,25 @@ TEST_CASE("Splitting a part drops pieces enclosing no volume and keeps the part } } +TEST_CASE("A part asked from several threads at once whether it can be split answers the same for all", "[Model]") +{ + // The PrintObjects made from one ModelObject prepare their infill at the same time, and each asks the object's first + // part whether it can be split, which fills a cache in the part. Without the lock around the cache the answers + // still agree on most runs: ThreadSanitizer is what reports the race. + Model model; + ModelObject *object = model.add_object(); + const ModelVolume *volume = object->add_volume(flat_triangle_then_cubes({0., 30.}), ModelVolumeType::MODEL_PART, false); + + std::vector answers(8, 0); + std::vector threads; + for (size_t i = 0; i < answers.size(); ++ i) + threads.emplace_back([volume, &answers, i] { answers[i] = volume->is_splittable() ? 1 : 0; }); + for (std::thread &thread : threads) + thread.join(); + + CHECK(std::all_of(answers.begin(), answers.end(), [](char answer) { return answer == 1; })); +} + TEST_CASE("Splitting a part with a single solid piece keeps just that piece", "[Model]") { Model model; diff --git a/tests/libslic3r/test_parallel_for_first_error.cpp b/tests/libslic3r/test_parallel_for_first_error.cpp new file mode 100644 index 0000000000..1cba2bd0dd --- /dev/null +++ b/tests/libslic3r/test_parallel_for_first_error.cpp @@ -0,0 +1,64 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "libslic3r/ParallelForFirstError.hpp" + +using namespace Slic3r; + +TEST_CASE("parallel_for_first_error throws the error of the lowest item that threw, after every item below it ran", "[ParallelForFirstError]") +{ + // Items 9 and 3 throw. A loop over the items stops at item 3, so its error is the one thrown, and the items before + // it all run. Each item is written by one task only, and read after the loop. + const size_t items_per_task = GENERATE(size_t(1), size_t(4)); + INFO(items_per_task << " items per task"); + const size_t count = 64; + std::vector ran(count, 0); + std::string thrown; + try { + parallel_for_first_error(count, items_per_task, [&ran](size_t i) { + ran[i] = 1; + if (i == 3 || i == 9) + throw std::runtime_error("item " + std::to_string(i)); + }); + } catch (const std::runtime_error &error) { + thrown = error.what(); + } + CHECK(thrown == "item 3"); + for (size_t i = 0; i <= 3; ++ i) + CHECK(ran[i] == 1); +} + +TEST_CASE("parallel_for_first_error starts no item on a thread that waits in another item's parallel loop", "[ParallelForFirstError]") +{ + // Each item runs a parallel loop of its own. A thread waiting for its item's loop could otherwise take another + // item meanwhile, which would then run nested in the first one on that thread. + static thread_local int items_on_thread = 0; + std::atomic nested { false }; + parallel_for_first_error(64, 1, [&nested](size_t) { + if (items_on_thread > 0) + nested = true; + ++ items_on_thread; + tbb::parallel_for(tbb::blocked_range(0, 256), [](const tbb::blocked_range &range) { + double sum = 0.; + for (size_t i = range.begin(); i < range.end(); ++ i) + for (int k = 1; k < 2000; ++ k) + sum += std::sqrt(double(i * size_t(k))); + // Keeps the work from being optimized away. + if (sum < 0.) + throw std::logic_error("negative sum"); + }); + -- items_on_thread; + }); + CHECK_FALSE(nested); +} From 3bc32c8b04d3b0fee7c2a0e72fe16a10fd972fb1 Mon Sep 17 00:00:00 2001 From: AsTechEvolves Date: Sat, 21 Nov 2026 08:35:49 -0600 Subject: [PATCH 27/36] Send dialog no longer blocks non-Bambu printers whose model name differs from the model id (#17519) BUG - save the preset's model id, not its name, as a non-Bambu printer's type and repair saved entries in GUI_App::select_machine --- src/slic3r/GUI/GUI_App.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 506a550713..46cf29cc39 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -4511,6 +4511,11 @@ void GUI_App::select_machine(const std::string& agent_id) } } + // Orca: the print dialog blocks a printer whose type differs from the preset's model id, so the + // type must be that id, not the model name. A model no vendor profile lists has no id; the + // dialog accepts any printer then, and the name stays. + const std::string model_id = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle); + // If machine doesn't exist, create it first. The Orca agent never connects, so an entry saved // under it holds no binding; re-insert it for the active agent, whose machine list can't see // it otherwise. Entries bound by any other agent stay with that agent. @@ -4520,7 +4525,7 @@ void GUI_App::select_machine(const std::string& agent_id) // We use dev_id as dev_ip to store the address (host:port) machine.dev_ip = dev_id; machine.dev_name = dev_id; - machine.printer_type = preset.config.opt_string("printer_model"); + machine.printer_type = model_id.empty() ? preset.config.opt_string("printer_model") : model_id; existing = m_device_manager->insert_local_device( machine, "lan", "free", "", access_code); @@ -4534,6 +4539,11 @@ void GUI_App::select_machine(const std::string& agent_id) (!existing->has_access_right() || existing->get_access_code() != access_code)) { existing->set_access_code(access_code); } + // Entries saved before held the model name; this printer's preset gives the id to repair them. + if (!model_id.empty() && existing->printer_agent_id == agent_id && existing->printer_type != model_id) { + existing->printer_type = model_id; + DeviceManager::update_local_machine(*existing, app_config); + } existing->local_use_ssl = boost::istarts_with(print_host, "https://"); select_dev(dev_id); } From f78db404e9d0613eab1a31169c9418a8eb467f6e Mon Sep 17 00:00:00 2001 From: yw4z Date: Sat, 21 Nov 2026 17:39:29 +0300 Subject: [PATCH 28/36] Fix: uninitialized Pressure Advance value in G-code preview (#17746) `GCodeProcessor::m_pressure_advance` was not set in `reset()`, so G-code without a pressure advance command showed a random PA value in the preview. It is now reset to 0 with the other per-move state, and a test checks that a reset processor does not keep the previous G-code's value. --- src/libslic3r/GCode/GCodeProcessor.cpp | 1 + tests/fff_print/test_gcodeprocessor.cpp | 30 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index c49a20efa3..baf2bb46b9 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -3779,6 +3779,7 @@ void GCodeProcessor::reset() m_travel_dist = 0.0f; m_fan_speed = 0.0f; m_z_offset = 0.0f; + m_pressure_advance = 0.0f; m_extrusion_role = erNone; diff --git a/tests/fff_print/test_gcodeprocessor.cpp b/tests/fff_print/test_gcodeprocessor.cpp index 0c2b43c689..6b951f1428 100644 --- a/tests/fff_print/test_gcodeprocessor.cpp +++ b/tests/fff_print/test_gcodeprocessor.cpp @@ -828,6 +828,36 @@ TEST_CASE("Inner walls of an exported sphere are not tagged", "[GCodeProcessor][ CHECK(layers.size() == seams.size()); } +TEST_CASE("A reset processor does not keep the previous G-code's pressure advance", "[GCodeProcessor][Regression]") +{ + FullPrintConfig config; + config.gcode_flavor.value = gcfMarlinFirmware; + GCodeProcessor processor; + // Streams G-code through the same processor, resetting it first as a reused one is. + const auto process = [&](const std::string &gcode) { + processor.reset(); + processor.initialize("stream.gcode"); + processor.initialize_result_moves(); + processor.apply_config(config); + processor.process_buffer(gcode); + processor.finalize(false); + return processor.result().moves; + }; + const auto is_extrusion = [](const GCodeProcessorResult::MoveVertex &move) { return move.type == EMoveType::Extrude; }; + const std::string square = "M83\nG90\nG1 X10 Y10 Z0.2 F12000\nG1 X50 Y10 E2 F3000\nG1 X50 Y50 E2\nG1 X10 Y50 E2\nG1 X10 Y10 E2\n"; + + const std::vector with_pa = process("M900 K0.05\n" + square); + REQUIRE(std::any_of(with_pa.begin(), with_pa.end(), is_extrusion)); + for (const GCodeProcessorResult::MoveVertex &move : with_pa) + if (is_extrusion(move)) + CHECK_THAT(move.pressure_advance, Catch::Matchers::WithinAbs(0.05, 1e-6)); + + const std::vector without_pa = process(square); + REQUIRE(std::any_of(without_pa.begin(), without_pa.end(), is_extrusion)); + for (const GCodeProcessorResult::MoveVertex &move : without_pa) + CHECK(move.pressure_advance == 0.0f); +} + namespace { // A printer with `nozzles` nozzles over a 200 mm square bed: nozzle `filament_1_nozzle` reaches only From bbf3836832d8d8945d1b6e388f7919c6383d2808 Mon Sep 17 00:00:00 2001 From: TheLegendTubaGuy <95944177+thelegendtubaguy@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:48:06 -0600 Subject: [PATCH 29/36] Fall back to the Centauri Carbon check for other Elegoo Link printers (#17587) Since 2.4.0, Elegoo Link only tried OctoPrint for presets whose printer_model doesn't start with "Elegoo Centauri", so a Centauri Carbon on a custom preset failed Test and upload with a 404. Those presets now try OctoPrint first and fall back to the Centauri Carbon check and upload, as 2.3.2 did. When both checks fail, Test and upload report the OctoPrint error. Elegoo Link now calls OctoPrint's upload after its own check, so `/api/version` is requested only once. Centauri Carbon and Centauri Carbon 2 presets are unchanged. Fixes #17570 --- src/slic3r/Utils/ElegooLink.cpp | 44 ++++++++++++++++----------------- src/slic3r/Utils/ElegooLink.hpp | 1 - src/slic3r/Utils/OctoPrint.cpp | 20 +++++++++++---- src/slic3r/Utils/OctoPrint.hpp | 4 +++ 4 files changed, 41 insertions(+), 28 deletions(-) diff --git a/src/slic3r/Utils/ElegooLink.cpp b/src/slic3r/Utils/ElegooLink.cpp index bb83dca2f5..1dca897baa 100644 --- a/src/slic3r/Utils/ElegooLink.cpp +++ b/src/slic3r/Utils/ElegooLink.cpp @@ -464,8 +464,17 @@ namespace Slic3r { } bool ElegooLink::test(wxString &curl_msg) const{ switch (classify_printer_model(m_printerModel)) { - case ElegooPrinterType::Other: - return OctoPrint::test(curl_msg); + case ElegooPrinterType::Other: { + if (OctoPrint::test(curl_msg)) + return true; + // A custom preset can have any printer_model, so an SDCP printer may land here too. + // If that check fails as well, keep the OctoPrint error for the user. + wxString sdcp_msg; + if (!elegoo_test(sdcp_msg)) + return false; + curl_msg = sdcp_msg; + return true; + } case ElegooPrinterType::CC2: return elegoo_cc2_test(curl_msg); case ElegooPrinterType::CC: @@ -556,19 +565,6 @@ namespace Slic3r { return res; } - bool ElegooLink::test_with_resolved_ip(wxString& msg) const - { - switch (classify_printer_model(m_printerModel)) { - case ElegooPrinterType::Other: - return OctoPrint::test_with_resolved_ip(msg); - case ElegooPrinterType::CC2: - return elegoo_cc2_test_with_resolved_ip(msg); - case ElegooPrinterType::CC: - return elegoo_test_with_resolved_ip(msg); - } - return false; - } - bool ElegooLink::elegoo_cc2_test_with_resolved_ip(wxString& msg) const { const char* name = get_name(); @@ -623,11 +619,13 @@ namespace Slic3r { { const auto printer_type = classify_printer_model(m_printerModel); - if (printer_type == ElegooPrinterType::Other) - return OctoPrint::upload_inner_with_resolved_ip(std::move(upload_data), prorgess_fn, error_fn, info_fn, resolved_addr); - info_fn(L"resolve", boost::nowide::widen(resolved_addr.to_string())); + // Other may be an SDCP printer: fall back to SDCP, but report the OctoPrint error if that fails too. + wxString octoprint_msg = GUI::from_u8(resolved_addr.to_string()); + if (printer_type == ElegooPrinterType::Other && OctoPrint::test_with_resolved_ip(octoprint_msg)) + return upload_after_test_with_resolved_ip(std::move(upload_data), prorgess_fn, error_fn, info_fn, resolved_addr); + if (printer_type == ElegooPrinterType::CC2) { wxString cc2_msg = GUI::from_u8(resolved_addr.to_string()); if (!elegoo_cc2_test_with_resolved_ip(cc2_msg)) { @@ -642,7 +640,7 @@ namespace Slic3r { wxString legacy_msg = GUI::from_u8(resolved_addr.to_string()); if (!elegoo_test_with_resolved_ip(legacy_msg)) { - error_fn(std::move(legacy_msg)); + error_fn(std::move(printer_type == ElegooPrinterType::Other ? octoprint_msg : legacy_msg)); return false; } @@ -658,8 +656,10 @@ namespace Slic3r { { const auto printer_type = classify_printer_model(m_printerModel); - if (printer_type == ElegooPrinterType::Other) - return OctoPrint::upload_inner_with_host(std::move(upload_data), prorgess_fn, error_fn, info_fn); + // Other may be an SDCP printer: fall back to SDCP, but report the OctoPrint error if that fails too. + wxString octoprint_msg; + if (printer_type == ElegooPrinterType::Other && OctoPrint::test(octoprint_msg)) + return upload_after_test_with_host(std::move(upload_data), prorgess_fn, error_fn, info_fn, octoprint_msg); if (printer_type == ElegooPrinterType::CC2) { wxString cc2_msg; @@ -688,7 +688,7 @@ namespace Slic3r { wxString legacy_msg; if(!elegoo_test(legacy_msg)){ - error_fn(std::move(legacy_msg)); + error_fn(std::move(printer_type == ElegooPrinterType::Other ? octoprint_msg : legacy_msg)); return false; } diff --git a/src/slic3r/Utils/ElegooLink.hpp b/src/slic3r/Utils/ElegooLink.hpp index 1cd471caf7..7a654bedbd 100644 --- a/src/slic3r/Utils/ElegooLink.hpp +++ b/src/slic3r/Utils/ElegooLink.hpp @@ -42,7 +42,6 @@ protected: virtual bool upload_inner_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn) const override; #ifdef WIN32 - virtual bool test_with_resolved_ip(wxString& curl_msg) const override; bool elegoo_test_with_resolved_ip(wxString& curl_msg) const; #endif private: diff --git a/src/slic3r/Utils/OctoPrint.cpp b/src/slic3r/Utils/OctoPrint.cpp index 8fb511d193..516f894c6b 100644 --- a/src/slic3r/Utils/OctoPrint.cpp +++ b/src/slic3r/Utils/OctoPrint.cpp @@ -348,6 +348,11 @@ bool OctoPrint::upload_inner_with_resolved_ip(PrintHostUpload upload_data, Progr return false; } + return upload_after_test_with_resolved_ip(std::move(upload_data), prorgess_fn, error_fn, info_fn, resolved_addr); +} + +bool OctoPrint::upload_after_test_with_resolved_ip(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const boost::asio::ip::address& resolved_addr) const +{ const char* name = get_name(); const auto upload_filename = upload_data.upload_path.filename(); const auto upload_parent_path = upload_data.upload_path.parent_path(); @@ -408,11 +413,6 @@ bool OctoPrint::upload_inner_with_resolved_ip(PrintHostUpload upload_data, Progr bool OctoPrint::upload_inner_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn) const { - const char* name = get_name(); - - const auto upload_filename = upload_data.upload_path.filename(); - const auto upload_parent_path = upload_data.upload_path.parent_path(); - // If test fails, test_msg_or_host_ip contains the error message. // Otherwise on Windows it contains the resolved IP address of the host. wxString test_msg_or_host_ip; @@ -421,6 +421,16 @@ bool OctoPrint::upload_inner_with_host(PrintHostUpload upload_data, ProgressFn p return false; } + return upload_after_test_with_host(std::move(upload_data), prorgess_fn, error_fn, info_fn, test_msg_or_host_ip); +} + +bool OctoPrint::upload_after_test_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const wxString& test_msg_or_host_ip) const +{ + const char* name = get_name(); + + const auto upload_filename = upload_data.upload_path.filename(); + const auto upload_parent_path = upload_data.upload_path.parent_path(); + std::string url; bool res = true; diff --git a/src/slic3r/Utils/OctoPrint.hpp b/src/slic3r/Utils/OctoPrint.hpp index 06ecc197df..4ceff6aace 100644 --- a/src/slic3r/Utils/OctoPrint.hpp +++ b/src/slic3r/Utils/OctoPrint.hpp @@ -39,9 +39,13 @@ public: protected: #ifdef WIN32 virtual bool upload_inner_with_resolved_ip(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const boost::asio::ip::address& resolved_addr) const; + // Upload half of upload_inner_with_resolved_ip(), for callers that already ran the test. + bool upload_after_test_with_resolved_ip(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const boost::asio::ip::address& resolved_addr) const; #endif virtual bool validate_version_text(const boost::optional &version_text) const; virtual bool upload_inner_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn) const; + // Upload half of upload_inner_with_host(), for callers that already ran test(). + bool upload_after_test_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const wxString& test_msg_or_host_ip) const; std::string m_host; std::string m_apikey; From 65a350a0cedca1e00cea3472d5471cc00acf3408 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:21:15 +0800 Subject: [PATCH 30/36] Stop Print Plate Aborting When a Multi-Nozzle Printer Has No Physical Extruder Map (#17664) A multi-nozzle printer whose profile never sets physical_extruder_map, such as the Snapmaker U1, carries the single-entry default {0}. PartPlate::get_physical_extruder_by_filament_id indexed it by logical extruder, so Print plate read past its end for any plate that used filament 2 or later, and the Flatpak aborted there. PartPlate's lookup, the printer sync in Plater and the three calibration setups in CalibUtils now read the map through effective_physical_extruder_map. It returns the profile's map when its length matches the nozzle count and the identity otherwise, so printers that ship a full map get the same values as before. The helper moves unchanged from IMEXHelpers to PrintConfig and PresetBundle, and its tests move to test_config.cpp. The G-code paths are unchanged. --- src/libslic3r/IMEXHelpers.cpp | 25 ------------ src/libslic3r/IMEXHelpers.hpp | 24 +++--------- src/libslic3r/PresetBundle.cpp | 9 +++++ src/libslic3r/PresetBundle.hpp | 6 +++ src/libslic3r/PrintConfig.cpp | 14 +++++++ src/libslic3r/PrintConfig.hpp | 15 +++++++ src/slic3r/GUI/PartPlate.cpp | 15 ++++--- src/slic3r/GUI/Plater.cpp | 10 ++--- src/slic3r/Utils/CalibUtils.cpp | 12 ++++-- tests/libslic3r/test_config.cpp | 47 ++++++++++++++++++++++ tests/libslic3r/test_imex_helpers.cpp | 41 -------------------- tests/slic3rutils/CMakeLists.txt | 1 + tests/slic3rutils/test_part_plate.cpp | 56 +++++++++++++++++++++++++++ 13 files changed, 175 insertions(+), 100 deletions(-) create mode 100644 tests/slic3rutils/test_part_plate.cpp diff --git a/src/libslic3r/IMEXHelpers.cpp b/src/libslic3r/IMEXHelpers.cpp index f9638bb0e5..8824eb630d 100644 --- a/src/libslic3r/IMEXHelpers.cpp +++ b/src/libslic3r/IMEXHelpers.cpp @@ -4,7 +4,6 @@ #include #include #include -#include #include #include #include @@ -25,7 +24,6 @@ #include "Polygon.hpp" #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/I18N.hpp" -#include "libslic3r/PresetBundle.hpp" #include "libslic3r/PrintConfig.hpp" // Mark string for localization and translate. @@ -49,29 +47,6 @@ void strip_whitespace(std::string& token) } } // namespace -ConfigOptionInts effective_physical_extruder_map(const ConfigOptionInts* explicit_pem, int nozzle_count) -{ - // One entry per logical extruder, so a profile has authored a map only when its length - // matches. The single-element PrintConfig default does not, and is replaced rather than - // treated as a one-extruder machine. - if (explicit_pem && nozzle_count > 0 && (int) explicit_pem->values.size() == nozzle_count) - return *explicit_pem; - - ConfigOptionInts derived; - derived.values.resize(std::max(nozzle_count, 1)); - std::iota(derived.values.begin(), derived.values.end(), 0); - return derived; -} - -ConfigOptionInts effective_physical_extruder_map(const PresetBundle& pb) -{ - const ConfigOptionInts* explicit_pem = pb.project_config.option("physical_extruder_map"); - if (!explicit_pem || explicit_pem->values.size() < 2) - explicit_pem = pb.printers.get_edited_preset().config.option("physical_extruder_map"); - const auto* nozzles = pb.printers.get_edited_preset().config.option("nozzle_diameter"); - return effective_physical_extruder_map(explicit_pem, nozzles ? (int) nozzles->values.size() : 0); -} - int imex_pem_tool_for(int filament_id, const std::string& parallel_mode, const ConfigOptionInts& pem) { const bool imex_parallel = !parallel_mode.empty() && parallel_mode != kImexPrimaryMode; diff --git a/src/libslic3r/IMEXHelpers.hpp b/src/libslic3r/IMEXHelpers.hpp index bc3d7b0bc9..d11b653ded 100644 --- a/src/libslic3r/IMEXHelpers.hpp +++ b/src/libslic3r/IMEXHelpers.hpp @@ -17,8 +17,6 @@ namespace Slic3r { -class PresetBundle; - // Reserved sentinel name for the always-present, non-deletable Primary mode in // `imex_mode_names`. Comparison with this constant indicates "no parallel printing // in effect" — IMEX zone visualization, ghost rendering, secondary-tool PA / temp @@ -162,19 +160,8 @@ std::vector imex_plate_mode_choices(const ConfigBase& cfg); // route through one of the helpers below. // ============================================================================= -// physical_extruder_map has one entry per LOGICAL extruder -- the index space of -// nozzle_diameter -- with each value a physical extruder index. It is NOT derivable from -// printer_extruder_id, which is indexed by variant slot (one entry per extruder+variant pair): -// an X1 Carbon has one nozzle and printer_extruder_id {1,1}, an H2D two nozzles and {1,1,2,2,2}. -// -// A profile has authored a map only when its length matches nozzle_count; otherwise the identity -// is returned, which is the same default upstream applies (see Plater.cpp's extruder_map). -ConfigOptionInts effective_physical_extruder_map(const ConfigOptionInts* explicit_pem, int nozzle_count); - -// GUI overload: resolves the effective pem from a live PresetBundle using the project_config -// → printer preset fallback. Use this instead of open-coding the lookup at ghost-color, -// tooltip, click-gate and cache-key call sites so they all agree with what the slicer sees. -ConfigOptionInts effective_physical_extruder_map(const PresetBundle& pb); +// effective_physical_extruder_map() lives in PrintConfig.hpp and PresetBundle.hpp: the map is a setting of +// every multi-nozzle printer, not only IMEX ones. // Returns the physical extruder index to emit as a per-tool qualifier (PA / temperature) // for the given filament slot, or -1 when the current IMEX state does not warrant a @@ -189,14 +176,15 @@ int imex_pem_tool_for(int filament_id, const std::string& parallel_mode, const C // so it does not depend on a parallel mode being active the way imex_pem_tool_for does. // // Gated on is_imex because physical_extruder_map carries two readings in this tree: the -// BBL paths index it by extruder id (GCode.cpp:3295, WipeTower.cpp:1353), the IMEX paths +// BBL paths index it by extruder id (match_physical_extruder_for_each_filament in +// GCode::_do_export, WipeTowerWriter::format_line_M104/M109), the IMEX paths // by filament id. Those coincide only when the filament and nozzle counts match, so an // ungated mapping would impose the IMEX reading on profiles that mean the other one -- // fdm_bbl_3dp_002_common ships a non-identity [1,0] and is spared today only because // single_extruder_multi_material suppresses the T qualifier entirely. // // Out-of-range ids pass through unchanged, the same rule GCodeProcessor's preheat rewrite -// uses (GCode/GCodeProcessor.cpp:1407), so a printer whose map is the registered +// uses (GCodeProcessor::run_post_process), so a printer whose map is the registered // single-entry default is unaffected. int imex_physical_heater_for(bool is_imex, const ConfigOptionInts& pem, int logical_id); @@ -386,7 +374,7 @@ template T imex_cfg_enum(const ConfigBase& cfg, const std::string& key) { // Matched by type, not by the coEnum tag. Every ConfigOptionEnum reports coEnum, so the - // type() comparison that option() (Config.hpp:2656) and the int/float accessors rely on + // type() comparison that ConfigBase::option() and the int/float accessors rely on // cannot tell one enum type from another: it would accept a ConfigOptionEnum and // static_cast it to this T. ConfigOptionEnum and ConfigOptionEnum are unrelated // siblings (both derive from ConfigOptionSingle), so a dynamic_cast rejects the mismatch. diff --git a/src/libslic3r/PresetBundle.cpp b/src/libslic3r/PresetBundle.cpp index a1e1483ec1..bbc636ebf4 100644 --- a/src/libslic3r/PresetBundle.cpp +++ b/src/libslic3r/PresetBundle.cpp @@ -9374,4 +9374,13 @@ bool PresetBundle::install_vendor_cache(const std::string& cache_path, const std } } +ConfigOptionInts effective_physical_extruder_map(const PresetBundle& pb) +{ + const ConfigOptionInts* explicit_pem = pb.project_config.option("physical_extruder_map"); + if (!explicit_pem || explicit_pem->values.size() < 2) + explicit_pem = pb.printers.get_edited_preset().config.option("physical_extruder_map"); + const auto* nozzles = pb.printers.get_edited_preset().config.option("nozzle_diameter"); + return effective_physical_extruder_map(explicit_pem, nozzles ? (int) nozzles->values.size() : 0); +} + } // namespace Slic3r diff --git a/src/libslic3r/PresetBundle.hpp b/src/libslic3r/PresetBundle.hpp index 5a660e839f..68d2d8930b 100644 --- a/src/libslic3r/PresetBundle.hpp +++ b/src/libslic3r/PresetBundle.hpp @@ -969,6 +969,12 @@ private: ENABLE_ENUM_BITMASK_OPERATORS(PresetBundle::LoadConfigBundleAttribute) +// GUI overload of effective_physical_extruder_map() (PrintConfig.hpp): resolves the effective pem +// from a live PresetBundle using the project_config → printer preset fallback. Use this instead of +// open-coding the lookup at ghost-color, tooltip, click-gate and cache-key call sites so they all +// agree with what the slicer sees. +ConfigOptionInts effective_physical_extruder_map(const PresetBundle& pb); + } // namespace Slic3r #endif /* slic3r_PresetBundle_hpp_ */ diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index ba03678d1b..204830d3af 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -154,6 +154,20 @@ double nozzle_diameter_for_filament(const PrintConfig& config, int filament_id, return config.nozzle_diameter.get_at(extruder - 1); } +ConfigOptionInts effective_physical_extruder_map(const ConfigOptionInts* explicit_pem, int nozzle_count) +{ + // One entry per logical extruder, so a profile has authored a map only when its length + // matches. The single-element PrintConfig default does not, and is replaced rather than + // treated as a one-extruder machine. + if (explicit_pem && nozzle_count > 0 && (int) explicit_pem->values.size() == nozzle_count) + return *explicit_pem; + + ConfigOptionInts derived; + derived.values.resize(std::max(nozzle_count, 1)); + std::iota(derived.values.begin(), derived.values.end(), 0); + return derived; +} + // Orca: input shaping values types by flavor std::vector get_shaper_type_values_for_flavor(GCodeFlavor flavor) diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 45aa2f5d41..b82266f61d 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -2821,6 +2821,21 @@ size_t get_extruder_index(const GCodeConfig& config, unsigned int filament_id); double nozzle_diameter_for_filament(const PrintConfig& config, int filament_id, bool is_bbl_printer); +// physical_extruder_map has one entry per LOGICAL extruder -- the index space of +// nozzle_diameter -- with each value a physical extruder index. It is NOT derivable from +// printer_extruder_id, which is indexed by variant slot (one entry per extruder+variant pair): +// an X1 Carbon has one nozzle and printer_extruder_id {1,1}, an H2D two nozzles and {1,1,2,2,2}. +// +// The setting belongs to every printer, not only IMEX ones: the single-element default is what +// any multi-nozzle profile that never sets it (a Snapmaker U1, say) carries, so reading it raw by +// logical extruder runs past its end. GUI and device-side readers go through this helper (or its +// PresetBundle overload in PresetBundle.hpp); the non-IMEX G-code paths read the raw value on +// purpose (see the is_imex gate in PrintApply.cpp). +// +// A profile has authored a map only when its length matches nozzle_count; otherwise the identity +// is returned, the default upstream's printer sync starts from before it applies an authored map. +ConfigOptionInts effective_physical_extruder_map(const ConfigOptionInts* explicit_pem, int nozzle_count); + } // namespace Slic3r // Serialization through the Cereal library diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index 53f41ac073..6de7d0c94d 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -3451,19 +3451,22 @@ std::vector PartPlate::get_extruders_without_support(bool conside_custom_gc int PartPlate::get_physical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const { const std::vector& filament_map = get_real_filament_maps(g_config); - if (filament_map.size() < idx) + if (idx <= 0 || idx > static_cast(filament_map.size())) { return -1; } - const auto the_map = g_config.option("physical_extruder_map"); - if (!the_map) + // A multi-nozzle printer whose profile never sets physical_extruder_map carries the + // single-element default, so the raw option cannot be indexed by logical extruder. + const auto* nozzles = g_config.option("nozzle_diameter"); + const ConfigOptionInts pem = effective_physical_extruder_map(g_config.option("physical_extruder_map"), + nozzles ? static_cast(nozzles->values.size()) : 0); + const int zero_base_logical_idx = filament_map[idx - 1] - 1; + if (zero_base_logical_idx < 0 || zero_base_logical_idx >= static_cast(pem.values.size())) { return -1; } - - int zero_base_logical_idx = filament_map[idx - 1] - 1; - return the_map->values[zero_base_logical_idx]; + return pem.values[zero_base_logical_idx]; } int PartPlate::get_logical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index bc8334f7c4..03c2bd36ef 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -2396,13 +2396,9 @@ bool Sidebar::priv::sync_extruder_list(bool &only_external_material, bool is_man BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << __LINE__ << " go on sync_extruder_list"; const Preset &cur_preset = preset_bundle->printers.get_selected_preset(); int extruder_nums = preset_bundle->get_printer_extruder_count(); - std::vector extruder_map(extruder_nums); - std::iota(extruder_map.begin(), extruder_map.end(), 0); - const ConfigOptionInts *physical_extruder_map = cur_preset.config.option("physical_extruder_map"); - if (physical_extruder_map != nullptr) { - assert(physical_extruder_map->values.size() == extruder_nums); - extruder_map = physical_extruder_map->values; - } + // A multi-nozzle profile that never sets physical_extruder_map carries the single-element default. + const std::vector extruder_map = + effective_physical_extruder_map(cur_preset.config.option("physical_extruder_map"), extruder_nums).values; assert(obj->GetExtderSystem()->GetTotalExtderCount() == extruder_nums); // Multi-nozzle: resolve the nozzle option (pops MultiNozzleSyncDialog when is_manual). No-op for every diff --git a/src/slic3r/Utils/CalibUtils.cpp b/src/slic3r/Utils/CalibUtils.cpp index e2eaf98558..2da4e04691 100644 --- a/src/slic3r/Utils/CalibUtils.cpp +++ b/src/slic3r/Utils/CalibUtils.cpp @@ -367,7 +367,9 @@ static void init_multi_extruder_params_for_cali(DynamicPrintConfig& config, cons nozzle_volume_types.clear(); nozzle_volume_types.resize(extruder_count, (int)calib_info.nozzle_volume_type); - std::vector physical_extruder_maps = dynamic_cast(config.option("physical_extruder_map", true))->values; + // One entry per nozzle even when the profile never set the map (the single-element default). + const std::vector physical_extruder_maps = + effective_physical_extruder_map(config.option("physical_extruder_map", true), extruder_count).values; int extruder_id = calib_info.extruder_id; for (size_t index = 0; index < extruder_count; ++index) { if (physical_extruder_maps[index] == extruder_id) @@ -969,7 +971,8 @@ void CalibUtils::set_for_auto_pa_model_and_config(const std::vector & nozzle_flush_dataset.resize(extruder_count, 0); int filament_nums = calib_infos.size(); - std::vector physical_extruder_maps = dynamic_cast(full_config.option("physical_extruder_map", true))->values; + const std::vector physical_extruder_maps = + effective_physical_extruder_map(full_config.option("physical_extruder_map", true), extruder_count).values; for (size_t filament_index = 0; filament_index < calib_infos.size(); ++filament_index) { CalibInfo calib_info = calib_infos[filament_index]; int extruder_id = calib_info.extruder_id; @@ -1055,7 +1058,10 @@ bool CalibUtils::calib_generic_auto_pa_cali(const std::vector &calib_ std::vector filament_presets; std::vector filament_map; filament_map.resize(calib_infos.size()); - std::vector physical_extruder_maps = dynamic_cast(printer_config.option("physical_extruder_map", true))->values; + const auto* nozzle_diameters = printer_config.option("nozzle_diameter"); + const int nozzle_count = nozzle_diameters ? static_cast(nozzle_diameters->values.size()) : 0; + const std::vector physical_extruder_maps = + effective_physical_extruder_map(printer_config.option("physical_extruder_map", true), nozzle_count).values; for (size_t i = 0; i < calib_infos.size(); ++i) { CalibInfo calib_info = calib_infos[i]; calib_info.filament_prest->config.set_key_value("curr_bed_type", new ConfigOptionEnum(calib_info.bed_type)); diff --git a/tests/libslic3r/test_config.cpp b/tests/libslic3r/test_config.cpp index 7c9f3c5d9b..6b8c676013 100644 --- a/tests/libslic3r/test_config.cpp +++ b/tests/libslic3r/test_config.cpp @@ -2029,3 +2029,50 @@ TEST_CASE("The print speed table keeps a bed outline when the extruders share no CHECK(outline.min == Point(0, 0)); CHECK(outline.max == Point(scaled(350.), scaled(350.))); } + +static ConfigOptionInts make_pem(std::vector v) { + ConfigOptionInts o; + o.values = std::move(v); + return o; +} + +TEST_CASE("effective_physical_extruder_map - authored map wins", "[Config][PhysicalExtruderMap]") { + // An AFC manifold on a 7-extruder machine: logical 0-3 all feed physical 0. Not derivable, + // so it must be honoured verbatim. + auto explicit_pem = make_pem({0, 0, 0, 0, 1, 2, 3}); + auto out = effective_physical_extruder_map(&explicit_pem, 7); + REQUIRE(out.values == std::vector{0, 0, 0, 0, 1, 2, 3}); +} + +TEST_CASE("effective_physical_extruder_map - a permutation is honoured", "[Config][PhysicalExtruderMap]") { + // Shipping BBL dual-nozzle profiles author {1,0}: a slicer/firmware numbering swap, not a + // sharing map. Deriving over it would silently renumber both extruders. + auto explicit_pem = make_pem({1, 0}); + auto out = effective_physical_extruder_map(&explicit_pem, 2); + REQUIRE(out.values == std::vector{1, 0}); +} + +TEST_CASE("effective_physical_extruder_map - unauthored derives the identity", "[Config][PhysicalExtruderMap]") { + // The PrintConfig default is a single element, which is not an authored map on a 2-extruder + // machine. Identity is what upstream itself falls back to. + auto default_pem = make_pem({0}); + auto out = effective_physical_extruder_map(&default_pem, 2); + REQUIRE(out.values == std::vector{0, 1}); +} + +TEST_CASE("effective_physical_extruder_map - result is always one entry per extruder", "[Config][PhysicalExtruderMap]") { + // The defining property: consumers index this map by logical extruder and size their own + // arrays from nozzle_diameter, so a shorter map is an out-of-bounds read in several of them. + for (int n : { 1, 2, 4, 7 }) { + DYNAMIC_SECTION("nozzle count " << n) { + REQUIRE((int) effective_physical_extruder_map(nullptr, n).values.size() == n); + auto stale = make_pem({0}); // wrong length: must not be mistaken for authored + REQUIRE((int) effective_physical_extruder_map(&stale, n).values.size() == n); + } + } +} + +TEST_CASE("effective_physical_extruder_map - degenerate nozzle count still yields a usable map", "[Config][PhysicalExtruderMap]") { + // Never hand back an empty map: several consumers index it as a raw vector. + REQUIRE(effective_physical_extruder_map(nullptr, 0).values == std::vector{0}); +} diff --git a/tests/libslic3r/test_imex_helpers.cpp b/tests/libslic3r/test_imex_helpers.cpp index 10240d7232..99b180ed48 100644 --- a/tests/libslic3r/test_imex_helpers.cpp +++ b/tests/libslic3r/test_imex_helpers.cpp @@ -30,47 +30,6 @@ static ConfigOptionInts make_pem(std::vector v) { return o; } -TEST_CASE("effective_physical_extruder_map - authored map wins", "[IMEX]") { - // An AFC manifold on a 7-extruder machine: logical 0-3 all feed physical 0. Not derivable, - // so it must be honoured verbatim. - auto explicit_pem = make_pem({0, 0, 0, 0, 1, 2, 3}); - auto out = effective_physical_extruder_map(&explicit_pem, 7); - REQUIRE(out.values == std::vector{0, 0, 0, 0, 1, 2, 3}); -} - -TEST_CASE("effective_physical_extruder_map - a permutation is honoured", "[IMEX]") { - // Shipping BBL dual-nozzle profiles author {1,0}: a slicer/firmware numbering swap, not a - // sharing map. Deriving over it would silently renumber both extruders. - auto explicit_pem = make_pem({1, 0}); - auto out = effective_physical_extruder_map(&explicit_pem, 2); - REQUIRE(out.values == std::vector{1, 0}); -} - -TEST_CASE("effective_physical_extruder_map - unauthored derives the identity", "[IMEX]") { - // The PrintConfig default is a single element, which is not an authored map on a 2-extruder - // machine. Identity is what upstream itself falls back to. - auto default_pem = make_pem({0}); - auto out = effective_physical_extruder_map(&default_pem, 2); - REQUIRE(out.values == std::vector{0, 1}); -} - -TEST_CASE("effective_physical_extruder_map - result is always one entry per extruder", "[IMEX]") { - // The defining property: consumers index this map by logical extruder and size their own - // arrays from nozzle_diameter, so a shorter map is an out-of-bounds read in several of them. - for (int n : { 1, 2, 4, 7 }) { - DYNAMIC_SECTION("nozzle count " << n) { - REQUIRE((int) effective_physical_extruder_map(nullptr, n).values.size() == n); - auto stale = make_pem({0}); // wrong length: must not be mistaken for authored - REQUIRE((int) effective_physical_extruder_map(&stale, n).values.size() == n); - } - } -} - -TEST_CASE("effective_physical_extruder_map - degenerate nozzle count still yields a usable map", "[IMEX]") { - // Never hand back an empty map: several consumers index it as a raw vector. - REQUIRE(effective_physical_extruder_map(nullptr, 0).values == std::vector{0}); -} - TEST_CASE("effective_physical_extruder_map - IDEX ghost-color regression guard", "[IMEX]") { // Dual extruder, no authored map. Before the GUI fix this produced a black ghost on T1 // because first_filament_for_physical_head({0}, 1) == -1. diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 36db245c61..300344c158 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -26,6 +26,7 @@ add_executable(${_TEST_NAME}_tests test_device_progress.cpp test_device_manager_integration.cpp test_web_media_controller.cpp + test_part_plate.cpp test_scene_raycaster.cpp test_scene_benchmark.cpp test_lazy.cpp diff --git a/tests/slic3rutils/test_part_plate.cpp b/tests/slic3rutils/test_part_plate.cpp new file mode 100644 index 0000000000..bcf368aaae --- /dev/null +++ b/tests/slic3rutils/test_part_plate.cpp @@ -0,0 +1,56 @@ +#include +#include + +#include +#include + +#include "libslic3r/Config.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "slic3r/GUI/PartPlate.hpp" + +using namespace Slic3r; +using namespace Slic3r::GUI; + +namespace { +DynamicPrintConfig nozzle_config(std::vector nozzle_diameters, + std::vector filament_map, + std::vector physical_extruder_map) +{ + DynamicPrintConfig config; + config.set_key_value("nozzle_diameter", new ConfigOptionFloats(std::move(nozzle_diameters))); + config.set_key_value("filament_map", new ConfigOptionInts(std::move(filament_map))); + config.set_key_value("physical_extruder_map", new ConfigOptionInts(std::move(physical_extruder_map))); + return config; +} +} // namespace + +TEST_CASE("A multi-nozzle printer without its own physical extruder map puts each filament on its own nozzle", "[PartPlate]") +{ + // Four nozzles, filament n on nozzle n, and the single-entry physical_extruder_map default. + const DynamicPrintConfig config = nozzle_config({0.4, 0.4, 0.4, 0.4}, {1, 2, 3, 4}, {0}); + const PartPlate plate; + + const int filament_id = GENERATE(1, 2, 3, 4); + CHECK(plate.get_physical_extruder_by_filament_id(config, filament_id) == filament_id - 1); +} + +TEST_CASE("A physical extruder map the profile sets decides the physical nozzle", "[PartPlate]") +{ + // Two nozzles whose physical order is the reverse of the logical one, as on a two-nozzle Bambu printer. + const DynamicPrintConfig config = nozzle_config({0.4, 0.4}, {1, 2}, {1, 0}); + const PartPlate plate; + + CHECK(plate.get_physical_extruder_by_filament_id(config, 1) == 1); + CHECK(plate.get_physical_extruder_by_filament_id(config, 2) == 0); +} + +TEST_CASE("A filament with no extruder to map to has no physical nozzle", "[PartPlate]") +{ + // Filament 2 is mapped to a fifth extruder the printer does not have; filament 0 and 3 do not exist. + const DynamicPrintConfig config = nozzle_config({0.4, 0.4, 0.4, 0.4}, {1, 5}, {0}); + const PartPlate plate; + + CHECK(plate.get_physical_extruder_by_filament_id(config, 2) == -1); + CHECK(plate.get_physical_extruder_by_filament_id(config, 0) == -1); + CHECK(plate.get_physical_extruder_by_filament_id(config, 3) == -1); +} From 4a45621b572db8e71ff8495662ec7bb218ed8874 Mon Sep 17 00:00:00 2001 From: Arthur Porto <227830219+Art-Porto@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:31:18 -0300 Subject: [PATCH 31/36] Start a Creality print from the path the printer lists the upload at (#17633) Upload and Print picked the start command's folder from the model that /info reports, and every unlisted model got /mnt/UDISK. A Nebula Pad reports the printer it is fitted to, such as "Ender-3 V2 Neo", and keeps its G-code under /usr/data, so its firmware ignored the start. Before the start, the host now asks the printer for its G-code file list (reqGcodeFile), as Creality Print does, and starts the upload from the path listed for it. K1-family firmware answers retGcodeFileInfo and K2-family firmware retGcodeFileInfo2. A list without the upload is asked for again until files_reply passes. When the printer doesn't list the upload, the model table decides as before, and it now includes "Ender-3 V2 Neo". --- src/slic3r/Utils/CrealityPrint.cpp | 206 +++++++++++++++++++--- src/slic3r/Utils/CrealityPrint.hpp | 7 +- tests/slic3rutils/test_creality_print.cpp | 147 ++++++++++++++- 3 files changed, 324 insertions(+), 36 deletions(-) diff --git a/src/slic3r/Utils/CrealityPrint.cpp b/src/slic3r/Utils/CrealityPrint.cpp index bd50cf949d..ed4ea54e92 100644 --- a/src/slic3r/Utils/CrealityPrint.cpp +++ b/src/slic3r/Utils/CrealityPrint.cpp @@ -27,6 +27,8 @@ #include #include +#include +#include #include #include #include @@ -162,7 +164,11 @@ bool CrealityPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn, auto http = Http::post(url); // std::move(url)); set_auth(http); - if (!supports_multi_color_print()) + // Multi-color models get no folder with the upload, so they keep it right under printer_data/gcodes. + const bool multi_color = supports_multi_color_print(); + const auto remote_path = multi_color || upload_parent_path.empty() ? safe_upload_filename : + (upload_parent_path / safe_upload_filename).generic_string(); + if (!multi_color) http.form_add("path", upload_parent_path.string()); http.form_add_file("file", upload_data.source_path.string(), safe_upload_filename) @@ -171,7 +177,7 @@ bool CrealityPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn, if (upload_data.post_action == PrintHostPostUploadAction::StartPrint) { wxString errormsg; - if (!start_print(errormsg, safe_upload_filename, upload_data.extended_info)) { + if (!start_print(errormsg, remote_path, upload_data.extended_info)) { error_fn(std::move(errormsg)); res = false; } @@ -278,24 +284,15 @@ static int reported_cfs_connect(const std::string& msg) return cfs_connect == 1 ? 1 : -1; } -// Sends the CFS slot query and returns the reply, or nothing when none arrives in time. -// 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. -// A status reporting no CFS connected cuts the wait to no_cfs_reply from then, and sets *no_cfs if no reply follows: a SPARKX i7 -// reports no CFS connected for its CFS Lite and still sends the slots. -static std::string ws_query_slots(net::io_context& ioc, - websocket::stream& ws, - std::chrono::milliseconds slots_reply, - std::chrono::milliseconds cfs_reply, - std::chrono::milliseconds no_cfs_reply, - bool* no_cfs) +// Reads the printer's messages until one holds key and returns it, or returns nothing once deadline passes or on_other, which gets +// every other message, returns false. The deadline also ends the read when the printer keeps sending heartbeats or status updates. +template +static std::string ws_await_reply(net::io_context& ioc, + websocket::stream& ws, + const std::chrono::steady_clock::time_point& deadline, + const char* key, + OnOther&& on_other) { - const auto sent = std::chrono::steady_clock::now(); - auto deadline = sent + slots_reply; - bool reported_no_cfs = false; - 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); @@ -310,8 +307,32 @@ static std::string ws_query_slots(net::io_context& ioc, ws_write(ioc, ws, "ok"); continue; } - if (msg.find("boxsInfo") != std::string::npos) + if (msg.find(key) != std::string::npos) return msg; + if (!on_other(msg)) + break; + } + return {}; +} + +// Sends the CFS slot query and returns the reply, or nothing when none arrives in time. +// 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. +// A status reporting no CFS connected cuts the wait to no_cfs_reply from then, and sets *no_cfs if no reply follows: a SPARKX i7 +// reports no CFS connected for its CFS Lite and still sends the slots. +static std::string ws_query_slots(net::io_context& ioc, + websocket::stream& ws, + std::chrono::milliseconds slots_reply, + std::chrono::milliseconds cfs_reply, + std::chrono::milliseconds no_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}}}}); + + bool reported_no_cfs = false; + const std::string reply = ws_await_reply(ioc, ws, deadline, "boxsInfo", [&](const std::string& msg) { const int cfs_connect = reported_cfs_connect(msg); if (cfs_connect == 0 && !reported_no_cfs) { reported_no_cfs = true; @@ -323,15 +344,94 @@ static std::string ws_query_slots(net::io_context& ioc, deadline = sent + std::max(slots_reply, cfs_reply); beast::get_lowest_layer(ws).expires_at(deadline); } - } + return true; + }); + if (!reply.empty()) + return reply; if (reported_no_cfs) { BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer reports no CFS connected"; if (no_cfs) *no_cfs = true; - return {}; + } else + BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a 'boxsInfo' response"; + return reply; +} + +// The full path a reply to reqGcodeFile lists remote_path at, an empty string when it does not list it, or nothing when the reply +// is no list this code reads. K2-family firmware answers retGcodeFileInfo2, a list of files with their path. K1-family firmware +// answers retGcodeFileInfo, whose fileInfo holds "folder:name:size:..." entries separated by ';'. +static std::optional listed_gcode_path(const std::string& reply_text, const std::string& remote_path) +{ + const json reply = json::parse(reply_text, nullptr, false); + if (!reply.is_object()) + return std::nullopt; + const std::string under_gcodes = "/printer_data/gcodes/" + remote_path; + + if (const auto files = reply.find("retGcodeFileInfo2"); files != reply.end() && files->is_array()) { + for (const json& file : *files) + if (file.is_object() && file.contains("path") && file.at("path").is_string() && + boost::algorithm::ends_with(file.at("path").get(), under_gcodes)) + return file.at("path").get(); + return std::string(); + } + + const auto info = reply.find("retGcodeFileInfo"); + if (info == reply.end() || !info->is_object() || !info->contains("fileInfo") || !info->at("fileInfo").is_string()) + return std::nullopt; + // Finds the name between its folder and its size, so a name holding ';' or ':' is found too. + const std::string file_info = info->at("fileInfo").get(); + const std::string name = remote_path.substr(remote_path.rfind('/') + 1); + const std::string field = ':' + name + ':'; + for (size_t at = file_info.find(field); at != std::string::npos; at = file_info.find(field, at + 1)) { + const size_t entry = file_info.rfind(';', at); + const size_t begin = entry == std::string::npos ? 0 : entry + 1; + const std::string path = file_info.substr(begin, at - begin) + '/' + name; + if (boost::algorithm::ends_with(path, under_gcodes)) + return path; + } + return std::string(); +} + +namespace { +// What the printer's G-code file list says about an upload. +struct GcodeListing +{ + enum class Result { NoReply, Unreadable, NotListed, Listed } result = Result::NoReply; + std::string path; // The full path the upload is listed at +}; +} // namespace + +// Asks for the G-code file list until it lists remote_path or files_reply passes. A printer can answer before it has indexed a +// file just uploaded, so a list without the upload is asked for again after files_retry. +static GcodeListing ws_find_listed_gcode(net::io_context& ioc, + websocket::stream& ws, + std::chrono::milliseconds files_reply, + std::chrono::milliseconds files_retry, + const std::string& remote_path) +{ + const auto deadline = std::chrono::steady_clock::now() + files_reply; + GcodeListing listing; + for (;;) { + beast::get_lowest_layer(ws).expires_at(deadline); + ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"reqGcodeFile", 1}}}}); + const std::string reply = ws_await_reply(ioc, ws, deadline, "retGcodeFileInfo", [](const std::string&) { return true; }); + if (reply.empty()) + return listing; + const std::optional path = listed_gcode_path(reply, remote_path); + if (!path) { + listing.result = GcodeListing::Result::Unreadable; + return listing; + } + if (!path->empty()) { + listing.result = GcodeListing::Result::Listed; + listing.path = *path; + return listing; + } + listing.result = GcodeListing::Result::NotListed; + if (std::chrono::steady_clock::now() + files_retry >= deadline) + return listing; + std::this_thread::sleep_for(files_retry); } - BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a 'boxsInfo' response"; - return {}; } // The K1 SE closes its side after a reply and K1-family printers after a start command, so a close error is not a failure. @@ -341,7 +441,8 @@ static void ws_close(net::io_context& ioc, websocket::stream& run_until_done(ioc, [&](auto&& handler) { ws.async_close(websocket::close_code::normal, handler); }); } -// Add a model by its /info value once its firmware is known to keep gcodes under /usr/data; every other model uses /mnt/UDISK. +// The folder for a printer that lists no G-code file. Add a model by its /info value once its firmware is known to keep gcodes +// under /usr/data; every other model uses /mnt/UDISK. static bool stores_gcode_in_usr_data(const std::string& model) { static const std::unordered_set usr_data_models = { @@ -351,6 +452,7 @@ static bool stores_gcode_in_usr_data(const std::string& model) "F004", // Ender-5 Max "F005", // Ender-3 V3 KE "F016", // K2 SE + "Ender-3 V2 Neo", // Nebula Pad on an Ender-3 V2 Neo "K1", "K1 Max", "K1 Max_CFS-C", @@ -440,6 +542,45 @@ std::string CrealityPrint::query_boxes_info(bool* no_cfs) const } } +// Uses a connection of its own, since the K1 SE closes its side after a reply. A failed connection is not caught: the start would +// fail the same way, and trying again would double the wait. +std::string CrealityPrint::query_listed_gcode(const std::string& remote_path) const +{ + net::io_context ioc; + websocket::stream ws{ioc}; + ws_connect(ioc, ws, m_host, ws_settings.port, ws_settings.connect); + + GcodeListing listing; + try { + listing = ws_find_listed_gcode(ioc, ws, ws_settings.files_reply, ws_settings.files_retry, remote_path); + } catch (std::exception const& e) { + BOOST_LOG_TRIVIAL(error) << "CrealityPrint: Failed to query the G-code file list: " << e.what(); + return {}; + } + switch (listing.result) { + case GcodeListing::Result::Listed: + BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer lists " << remote_path << " at " << listing.path; + break; + case GcodeListing::Result::NotListed: + BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: The printer's G-code file list does not include " << remote_path; + break; + case GcodeListing::Result::Unreadable: + BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: The printer's G-code file list has no format this host reads"; + break; + case GcodeListing::Result::NoReply: + BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for the G-code file list"; + break; + } + + // A printer that sent no list may not answer a close either, so its connection is dropped without one. + if (listing.result == GcodeListing::Result::NoReply) { + beast::error_code ec; + beast::get_lowest_layer(ws).socket().close(ec); + } else + ws_close(ioc, ws, ws_settings.close); + return listing.path; +} + CrealityPrinterInfo CrealityPrint::read_printer_info() const { CrealityPrinterInfo info; @@ -528,14 +669,21 @@ std::vector CrealityPrint::start_print_commands(bool return commands; } -bool CrealityPrint::start_print(wxString &msg, const std::string &filename, const std::map& extended_info) const +bool CrealityPrint::start_print(wxString &msg, const std::string &remote_path, const std::map& extended_info) const { try { // Runs before the WebSocket opens and its reply deadline starts, since it can query the // printer over HTTP. It also fills m_model. - const bool multi_color = supports_multi_color_print(); - const std::string data_root = stores_gcode_in_usr_data(m_model) ? "/usr/data" : "/mnt/UDISK"; - const std::string gcode_path = data_root + "/printer_data/gcodes/" + filename; + const bool multi_color = supports_multi_color_print(); + // Starts the file at the path the printer lists it at, as Creality Print does, since the + // folder depends on the printer's board and not on its model. The model decides only when + // the printer does not list the upload. + std::string gcode_path = query_listed_gcode(remote_path); + if (gcode_path.empty()) { + const std::string data_root = stores_gcode_in_usr_data(m_model) ? "/usr/data" : "/mnt/UDISK"; + gcode_path = data_root + "/printer_data/gcodes/" + remote_path.substr(remote_path.rfind('/') + 1); + BOOST_LOG_TRIVIAL(info) << "CrealityPrint: Using " << data_root << " for model " << m_model; + } net::io_context ioc; websocket::stream ws{ioc}; diff --git a/src/slic3r/Utils/CrealityPrint.hpp b/src/slic3r/Utils/CrealityPrint.hpp index 77b62f925d..69f74046fc 100644 --- a/src/slic3r/Utils/CrealityPrint.hpp +++ b/src/slic3r/Utils/CrealityPrint.hpp @@ -70,6 +70,8 @@ protected: 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 no_cfs_reply{std::chrono::seconds(2)}; // The CFS slot query once a status reports no CFS connected + std::chrono::milliseconds files_reply{std::chrono::seconds(3)}; // The G-code file list query before a start, asked again within it + std::chrono::milliseconds files_retry{std::chrono::milliseconds(500)}; // The pause before asking again for a list without the upload std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake } ws_settings; @@ -83,7 +85,10 @@ private: mutable std::string m_model; std::string make_url(const std::string& path) const; - bool start_print(wxString& msg, const std::string& filename, const std::map& extended_info) const; + // remote_path is where the upload went under printer_data/gcodes. + bool start_print(wxString& msg, const std::string& remote_path, const std::map& extended_info) const; + // The full path the printer lists remote_path at, or nothing when it does not list it. Throws when the printer cannot be reached. + std::string query_listed_gcode(const std::string& remote_path) 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. diff --git a/tests/slic3rutils/test_creality_print.cpp b/tests/slic3rutils/test_creality_print.cpp index afcca252a9..9ccd76c6fc 100644 --- a/tests/slic3rutils/test_creality_print.cpp +++ b/tests/slic3rutils/test_creality_print.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -73,11 +74,13 @@ struct Message std::string payload; }; -// Serves the printer's HTTP API and its websocket on one port. +// Serves the printer's HTTP API and its websocket on one port. With file_lists, each G-code file list query gets the next one, +// and the last one once they run out. class FakeCrealityPrinter { public: - FakeCrealityPrinter(Behavior behavior, std::string model) : m_behavior(behavior), m_model(std::move(model)) + FakeCrealityPrinter(Behavior behavior, std::string model, std::vector file_lists = {}) + : m_behavior(behavior), m_model(std::move(model)), m_file_lists(std::move(file_lists)) { m_accept_thread = std::thread([this] { accept_loop(); }); } @@ -110,6 +113,12 @@ public: return m_http_requests; } + int websocket_requests() + { + std::lock_guard lock(m_mutex); + return m_websocket_requests; + } + // Hangs up every connection that is waiting. void release() { @@ -144,6 +153,10 @@ private: serve_http(socket, request); return; } + { + std::lock_guard lock(m_mutex); + ++m_websocket_requests; + } if (m_behavior == Behavior::SilentBeforeHandshake) { wait_for_release(); return; @@ -171,6 +184,15 @@ private: m_messages.push_back({ws.got_text(), payload}); } const std::string slots = R"({"boxsInfo":{"materialBoxs":[]}})"; + if (!m_file_lists.empty() && payload.find("reqGcodeFile") != std::string::npos) { + std::string file_list; + { + std::lock_guard lock(m_mutex); + file_list = m_file_lists[std::min(m_file_list_replies++, m_file_lists.size() - 1)]; + } + ws.write(net::buffer(file_list), ec); + continue; + } if (first && m_behavior == Behavior::ReportsNoCfs) { ws.write(net::buffer(std::string(R"({"cfsConnect":0,"nozzleTemp":"25.000000"})")), ec); wait_for_release(); @@ -236,6 +258,7 @@ private: const Behavior m_behavior; const std::string m_model; + const std::vector m_file_lists; net::io_context m_accept_ioc; tcp::acceptor m_acceptor{m_accept_ioc, {net::ip::make_address("127.0.0.1"), 0}}; std::atomic m_stopping{false}; @@ -245,6 +268,8 @@ private: std::condition_variable m_changed; std::vector m_messages; int m_http_requests = 0; + int m_websocket_requests = 0; + std::size_t m_file_list_replies = 0; bool m_released = false; }; @@ -276,6 +301,7 @@ std::unique_ptr make_host(const FakeCrealityPrinter& printer, std::chr host->ws_settings.reply = deadline; host->ws_settings.slots_reply = deadline; host->ws_settings.no_cfs_reply = deadline; + host->ws_settings.files_reply = deadline; host->ws_settings.close = deadline; return host; } @@ -294,18 +320,39 @@ template bool finishes_within(FakeCrealityPrinter& printer, std::chr return in_time; } -bool upload_and_print(const CrealityPrint& host, wxString& error, const std::map& extended_info = {}) +bool upload_and_print(const CrealityPrint& host, + wxString& error, + const std::map& extended_info = {}, + const std::string& upload_path = "test.gcode") { const ScopedTemporaryFile source(".gcode"); std::ofstream(source.string()) << "G28\n"; PrintHostUpload upload; upload.source_path = source.path(); - upload.upload_path = "test.gcode"; + upload.upload_path = upload_path; upload.post_action = PrintHostPostUploadAction::StartPrint; upload.extended_info = extended_info; return host.upload(upload, [](Http::Progress, bool&) {}, [&](wxString message) { error = message; }, [](wxString, wxString) {}); } +bool is_file_list_query(const Message& message) { return message.payload.find("reqGcodeFile") != std::string::npos; } + +int file_list_queries(FakeCrealityPrinter& printer) +{ + const std::vector messages = printer.messages(); + return static_cast(std::count_if(messages.begin(), messages.end(), is_file_list_query)); +} + +// The start commands, without the G-code file list query and the heartbeat acknowledgement sent on its connection. +std::vector start_messages(FakeCrealityPrinter& printer) +{ + std::vector messages = printer.messages(); + messages.erase(std::remove_if(messages.begin(), messages.end(), + [](const Message& message) { return is_file_list_query(message) || message.payload == "ok"; }), + messages.end()); + return messages; +} + } // namespace TEST_CASE("Querying the CFS slots gives a silent printer no more than its deadlines", "[CrealityPrint]") @@ -510,11 +557,14 @@ TEST_CASE("Starting a print gives a silent printer no more than its deadlines", CHECK(result == started); CHECK(error.empty() == started); CHECK(error.StartsWith("Connection timed out") == !started); + // A printer that never completes the handshake for the G-code file list query gets no second connection for the start. + CHECK(printer.websocket_requests() == (started ? 2 : 1)); } TEST_CASE("Starting a print sends each command with the G-code path in a text frame", "[CrealityPrint]") { - // F008 is a multi-color model and F018 a plain one. K1C, F005 (Ender-3 V3 KE) and F016 (K2 SE) keep their G-code under /usr/data. + // The printer never answers the G-code file list query, so the model decides the folder. F008 is a multi-color model and F018 + // a plain one. K1C, F005 (Ender-3 V3 KE), F016 (K2 SE) and a Nebula Pad on an Ender-3 V2 Neo keep their G-code under /usr/data. // Only a mapping onto CFS slots starts a multi-color print; a printer that listed no slots starts plainly. const std::map cfs_mapping = {{"enableSelfTest", "0"}, {"colorMatch_0", "T1A\tPLA\t#FF0000\t1\t0"}}; const auto [model, extended_info, commands, gcode] = GENERATE_REF(table, std::vector, std::string>({ @@ -522,6 +572,7 @@ TEST_CASE("Starting a print sends each command with the G-code path in a text fr {"F008", {}, {"opGcodeFile"}, "printprt:/mnt/UDISK/printer_data/gcodes/test.gcode"}, {"F018", {}, {"opGcodeFile"}, "printprt:/mnt/UDISK/printer_data/gcodes/test.gcode"}, {"F005", {}, {"opGcodeFile"}, "printprt:/usr/data/printer_data/gcodes/test.gcode"}, + {"Ender-3 V2 Neo", {}, {"opGcodeFile"}, "printprt:/usr/data/printer_data/gcodes/test.gcode"}, {"F016", cfs_mapping, {"colorMatch", "multiColorPrint"}, "/usr/data/printer_data/gcodes/test.gcode"}, {"K1C", cfs_mapping, {"colorMatch", "multiColorPrint"}, "/usr/data/printer_data/gcodes/test.gcode"}, {"K1C", {}, {"opGcodeFile"}, "printprt:/usr/data/printer_data/gcodes/test.gcode"}, @@ -530,11 +581,12 @@ TEST_CASE("Starting a print sends each command with the G-code path in a text fr FakeCrealityPrinter printer(Behavior::Answers, model); const auto host = make_host(printer, 5s); + host->ws_settings.files_reply = 200ms; wxString error; CHECK(upload_and_print(*host, error, extended_info)); CHECK(error.empty()); - const std::vector messages = printer.messages(); + const std::vector messages = start_messages(printer); REQUIRE(messages.size() == commands.size()); for (std::size_t i = 0; i < messages.size(); ++i) { CAPTURE(i); @@ -545,6 +597,89 @@ TEST_CASE("Starting a print sends each command with the G-code path in a text fr } } +TEST_CASE("Starting a print uses the path the printer lists the upload at", "[CrealityPrint]") +{ + // K1-family firmware lists "folder:name:size:..." entries, escaping its slashes, and K2-family firmware files with their path. + // The listed path decides over the model, which would give F018 and the unlisted F099 /mnt/UDISK and K1C /usr/data. Only the + // upload counts: another file, a list without files, or a list in a format this host does not read leave the folder to the + // model. A name holding ';' and a file in a subfolder are still found. A name that is not UTF-8 makes the printer's text frame + // invalid, so the whole list is lost and the model decides, but the print still starts. + const std::string k1_upload = R"({"retGcodeFileInfo":{"totalNum":1,"fileInfo":"\/usr\/data\/printer_data\/gcodes:test.gcode:63301:0.240000:1794188820:109:\/tmp\/test.png;"}})"; + const std::string k1_other = R"({"retGcodeFileInfo":{"totalNum":1,"fileInfo":"/usr/data/printer_data/gcodes:other.gcode:63301:0.240000:1794188820:109:/tmp/other.png;"}})"; + const std::string k1_semicolon = R"({"retGcodeFileInfo":{"totalNum":2,"fileInfo":"/usr/data/printer_data/gcodes:other.gcode:63301:0.240000:1794188820:109:/tmp/other.png;)" + R"(/usr/data/printer_data/gcodes:a;b.gcode:63301:0.240000:1794188820:109:/tmp/a;b.png;"}})"; + const std::string k1_subfolder = R"({"retGcodeFileInfo":{"totalNum":2,"fileInfo":"/usr/data/printer_data/gcodes:test.gcode:63301:0.240000:1794188820:109:/tmp/test.png;)" + R"(/usr/data/printer_data/gcodes/parts:test.gcode:63301:0.240000:1794188820:109:/tmp/test.png;"}})"; + const std::string k2_upload = R"({"retGcodeFileInfo2":[{"name":"test.gcode","path":"/mnt/UDISK/printer_data/gcodes/test.gcode","type":8}]})"; + const std::string k2_both = R"({"retGcodeFileInfo2":[{"name":"other.gcode","path":"/usr/data/printer_data/gcodes/other.gcode","type":8},)" + R"({"name":"test.gcode","path":"/mnt/UDISK/printer_data/gcodes/test.gcode","type":8}]})"; + const std::string k2_not_utf8 = R"({"retGcodeFileInfo2":[{"name":"x.gcode","path":"/mnt/UDISK/printer_data/gcodes/)" "\xff" R"(.gcode","type":8},)" + R"({"name":"test.gcode","path":"/mnt/UDISK/printer_data/gcodes/test.gcode","type":8}]})"; + const std::string no_files = R"({"retGcodeFileInfo2":[]})"; + const std::string no_folders = R"({"retGcodeFileInfo3":{"fileInfo":"test.gcode:63301:1794188820;"}})"; + const auto [model, upload_path, file_list, gcode] = GENERATE_REF(table({ + {"F099", "test.gcode", k1_upload, "/usr/data/printer_data/gcodes/test.gcode"}, + {"F018", "test.gcode", k1_other, "/mnt/UDISK/printer_data/gcodes/test.gcode"}, + {"F018", "a;b.gcode", k1_semicolon, "/usr/data/printer_data/gcodes/a;b.gcode"}, + {"F018", "parts/test.gcode", k1_subfolder, "/usr/data/printer_data/gcodes/parts/test.gcode"}, + {"K1C", "test.gcode", k2_upload, "/mnt/UDISK/printer_data/gcodes/test.gcode"}, + {"K1C", "test.gcode", k2_both, "/mnt/UDISK/printer_data/gcodes/test.gcode"}, + {"K1C", "test.gcode", k2_not_utf8, "/usr/data/printer_data/gcodes/test.gcode"}, + {"F005", "test.gcode", no_files, "/usr/data/printer_data/gcodes/test.gcode"}, + {"F018", "test.gcode", no_files, "/mnt/UDISK/printer_data/gcodes/test.gcode"}, + {"F018", "test.gcode", no_folders, "/mnt/UDISK/printer_data/gcodes/test.gcode"}, + })); + CAPTURE(model, upload_path, file_list); + + FakeCrealityPrinter printer(Behavior::Answers, model, {file_list}); + const auto host = make_host(printer, 5s); + host->ws_settings.files_reply = 300ms; + host->ws_settings.files_retry = 50ms; + wxString error; + + CHECK(upload_and_print(*host, error, {}, upload_path)); + CHECK(error.empty()); + const std::vector messages = printer.messages(); + REQUIRE_FALSE(messages.empty()); + CHECK(is_file_list_query(messages[0])); + CHECK(messages[0].text); + const std::vector start = start_messages(printer); + REQUIRE(start.size() == 1); + const nlohmann::json params = nlohmann::json::parse(start[0].payload).at("params"); + CHECK(params.at("opGcodeFile") == "printprt:" + gcode); +} + +TEST_CASE("Starting a print asks again for a file list that does not list the upload yet", "[CrealityPrint]") +{ + // The first list comes before the printer has indexed the upload. K1C's model alone would give /usr/data. + const std::string no_files = R"({"retGcodeFileInfo2":[]})"; + const std::string k2_upload = R"({"retGcodeFileInfo2":[{"name":"test.gcode","path":"/mnt/UDISK/printer_data/gcodes/test.gcode","type":8}]})"; + FakeCrealityPrinter printer(Behavior::Answers, "K1C", {no_files, k2_upload}); + const auto host = make_host(printer, 5s); + host->ws_settings.files_retry = 50ms; + wxString error; + + CHECK(upload_and_print(*host, error)); + CHECK(error.empty()); + CHECK(file_list_queries(printer) == 2); + const std::vector start = start_messages(printer); + REQUIRE(start.size() == 1); + CHECK(nlohmann::json::parse(start[0].payload).at("params").at("opGcodeFile") == "printprt:/mnt/UDISK/printer_data/gcodes/test.gcode"); +} + +TEST_CASE("Starting a print asks once for a file list in a format this host does not read", "[CrealityPrint]") +{ + const std::string no_folders = R"({"retGcodeFileInfo3":{"fileInfo":"test.gcode:63301:1794188820;"}})"; + FakeCrealityPrinter printer(Behavior::Answers, "F018", {no_folders}); + const auto host = make_host(printer, 5s); + host->ws_settings.files_retry = 50ms; + wxString error; + + CHECK(upload_and_print(*host, error)); + CHECK(error.empty()); + CHECK(file_list_queries(printer) == 1); +} + namespace { const std::string gcode_path = "/usr/data/printer_data/gcodes/part.gcode"; From 97e2d0a6e687317efb871a3a142402ee8240286b Mon Sep 17 00:00:00 2001 From: Surfoo Date: Sat, 21 Nov 2026 17:05:50 +0100 Subject: [PATCH 32/36] Notebook: don't hide a page that is also the page being selected #17189 (#17739) Prepare and Preview share one page window, the Plater. On every switch between them, wx hid that window and showed it again right away. On GNOME Wayland this unmapped and remapped the GL canvases and triggered a mutter subsurface bug, which left a frozen copy of the Prepare view at the top-left of the window (#17189). Notebook no longer hides the page that is being selected, and switches between other tabs are unchanged. --- src/slic3r/GUI/Notebook.hpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/Notebook.hpp b/src/slic3r/GUI/Notebook.hpp index b7774c84e0..c301b06cfe 100644 --- a/src/slic3r/GUI/Notebook.hpp +++ b/src/slic3r/GUI/Notebook.hpp @@ -490,17 +490,28 @@ protected: page->SetSize(GetPageRect()); } + virtual int DoSetSelection(size_t n, int flags = 0) override + { + m_target_page = GetPage(n); + const int ret = wxBookCtrlBase::DoSetSelection(n, flags); + m_target_page = nullptr; + return ret; + } + virtual void DoShowPage(wxWindow * page, bool show) override { if (show) page->ShowWithEffect(m_showEffect, m_showTimeout); - else + // Tabs may share one page window (Prepare/Preview -> m_plater). Hiding it just to re-show it + // unmaps and remaps its GL canvases, which triggers a mutter subsurface bug on Wayland. + else if (page != m_target_page) page->HideWithEffect(m_hideEffect, m_hideTimeout); } private: void Init(); + wxWindow* m_target_page{nullptr}; // page being selected; DoShowPage must not hide it std::vector m_pageNames; // index-parallel to wxBookCtrlBase::m_pages wxShowEffect m_showEffect, From fad7f8163efe2ab3d1869be66baa5484a119aad8 Mon Sep 17 00:00:00 2001 From: Arthur Porto <227830219+Art-Porto@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:40:03 -0300 Subject: [PATCH 33/36] Park the K1, K1C and K1 SE CFS-C filament change inside their 220 mm beds (#17765) The change filament G-code of the three CFS-C profiles moved to X0 Y245, the park of the K1 Max's 300 mm bed. Use X42 Y180, as the other 220 mm K-series profiles and Creality Print's K1C CFS profile do. Fixes #17677 --- resources/profiles/Creality.json | 2 +- .../Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json | 2 +- .../Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json | 2 +- .../profiles/Creality/machine/Creality K1_CFS-C 0.4 nozzle.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/resources/profiles/Creality.json b/resources/profiles/Creality.json index 43799aebdc..fb4d1e89e9 100644 --- a/resources/profiles/Creality.json +++ b/resources/profiles/Creality.json @@ -1,6 +1,6 @@ { "name": "Creality", - "version": "02.03.02.89", + "version": "02.03.02.90", "force_update": "0", "description": "Creality configurations", "machine_model_list": [ diff --git a/resources/profiles/Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json b/resources/profiles/Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json index 3b24a21259..47b18546cb 100644 --- a/resources/profiles/Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json +++ b/resources/profiles/Creality/machine/Creality K1 SE_CFS-C 0.4 nozzle.json @@ -14,7 +14,7 @@ "bed_mesh_probe_distance": "50,50", "before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n", "best_object_pos": "0.5,0.5", - "change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X0 Y245 F30000\nG1 Z{z_after_toolchange} F600", + "change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X42 Y180 F30000\nG1 Z{z_after_toolchange} F600", "cooling_tube_length": "0", "cooling_tube_retraction": "0", "creality_flush_time": "119", diff --git a/resources/profiles/Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json b/resources/profiles/Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json index 7cb41ca271..8d355bb182 100644 --- a/resources/profiles/Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json +++ b/resources/profiles/Creality/machine/Creality K1C_CFS-C 0.4 nozzle.json @@ -14,7 +14,7 @@ "bed_mesh_probe_distance": "50,50", "before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n", "best_object_pos": "0.5,0.5", - "change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X0 Y245 F30000\nG1 Z{z_after_toolchange} F600", + "change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X42 Y180 F30000\nG1 Z{z_after_toolchange} F600", "cooling_tube_length": "0", "cooling_tube_retraction": "0", "creality_flush_time": "119", diff --git a/resources/profiles/Creality/machine/Creality K1_CFS-C 0.4 nozzle.json b/resources/profiles/Creality/machine/Creality K1_CFS-C 0.4 nozzle.json index f53f11a029..48c1170eba 100644 --- a/resources/profiles/Creality/machine/Creality K1_CFS-C 0.4 nozzle.json +++ b/resources/profiles/Creality/machine/Creality K1_CFS-C 0.4 nozzle.json @@ -14,7 +14,7 @@ "bed_mesh_probe_distance": "50,50", "before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n", "best_object_pos": "0.5,0.5", - "change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X0 Y245 F30000\nG1 Z{z_after_toolchange} F600", + "change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X42 Y180 F30000\nG1 Z{z_after_toolchange} F600", "cooling_tube_length": "0", "cooling_tube_retraction": "0", "creality_flush_time": "119", From 5bf1571bb8908134c54c323d3f6f259821f48aee Mon Sep 17 00:00:00 2001 From: Kiss Lorand <50251547+kisslorand@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:48:14 +0200 Subject: [PATCH 34/36] Fix Move gizmo crash when using Object coordinates with multiple instances (#17642) Selecting several instances of one object with the Move gizmo in Object coordinates, by clicking them or with Ctrl+A, made get_selected_single_intance() index the instance list with -1 and crash. It now returns nullptr when the selection has no single instance, and the gizmo uses the first volume's instance transform instead. --- src/slic3r/GUI/Selection.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/Selection.cpp b/src/slic3r/GUI/Selection.cpp index e51eb396c9..1007d3cce6 100644 --- a/src/slic3r/GUI/Selection.cpp +++ b/src/slic3r/GUI/Selection.cpp @@ -469,10 +469,14 @@ ModelObject *Selection::get_selected_single_object(int &out_object_idx) const const ModelInstance *Selection::get_selected_single_intance() const { + const int instance_idx = get_instance_idx(); + if (instance_idx < 0) + return nullptr; + int object_idx; auto mo = get_selected_single_object(object_idx); if (mo) { - return mo->instances[get_instance_idx()]; + return mo->instances[instance_idx]; } return nullptr; } From f2eb53ebaac719b67f882af4c67264ca7887cd16 Mon Sep 17 00:00:00 2001 From: rblumen <141589963+rblumen@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:00:03 -0500 Subject: [PATCH 35/36] Keep the cloud login dialog on screen and make it resizable (#17721) The Orca Cloud and Bambu Cloud login dialog had a fixed size of 650x840 DIP. At 150% scaling on a 1080p screen it was taller than the work area, so its title bar was off screen and it could not be moved or closed. The size is now clamped to the work area of the display the main window is on, and after centering the dialog is moved to stay inside that area. The dialog is also resizable, and the webview fills it when it is resized. --- src/slic3r/GUI/WebUserLoginDialog.cpp | 31 ++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/slic3r/GUI/WebUserLoginDialog.cpp b/src/slic3r/GUI/WebUserLoginDialog.cpp index de236addd5..6af5d05548 100644 --- a/src/slic3r/GUI/WebUserLoginDialog.cpp +++ b/src/slic3r/GUI/WebUserLoginDialog.cpp @@ -19,6 +19,7 @@ #include "slic3r/Utils/NetworkAgent.hpp" #include "libslic3r_version.h" +#include #include #include #include @@ -31,6 +32,9 @@ #include #include #include +#include +#include +#include #include #include @@ -108,7 +112,8 @@ int ZUserLogin::ensure_loopback_port() } ZUserLogin::ZUserLogin(std::shared_ptr cloud_agent) - : wxDialog((wxWindow*) (wxGetApp().mainframe), wxID_ANY, "OrcaSlicer"), m_cloud_agent(cloud_agent) + : wxDialog((wxWindow*) (wxGetApp().mainframe), wxID_ANY, "OrcaSlicer", wxDefaultPosition, wxDefaultSize, + wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), m_cloud_agent(cloud_agent) { SetBackgroundColour(*wxWHITE); @@ -183,6 +188,13 @@ ZUserLogin::ZUserLogin(std::shared_ptr cloud_agent) m_browser->Hide(); m_browser->SetSize(0, 0); + // The webview fills the dialog, so it follows the dialog when the user resizes it. + // Plain SetSizer: the webview is still hidden and 0x0 here, so fitting would collapse the dialog; + // the size is set explicitly below. + auto* browser_sizer = new wxBoxSizer(wxVERTICAL); + browser_sizer->Add(m_browser, 1, wxEXPAND); + SetSizer(browser_sizer); + // Connect the webview events Bind(wxEVT_WEBVIEW_NAVIGATING, &ZUserLogin::OnNavigationRequest, this, m_browser->GetId()); Bind(wxEVT_WEBVIEW_NAVIGATED, &ZUserLogin::OnNavigationComplete, this, m_browser->GetId()); @@ -196,10 +208,23 @@ ZUserLogin::ZUserLogin(std::shared_ptr cloud_agent) // UI SetTitle(_L("Login")); // Set a more sensible size for web browsing - wxSize pSize = FromDIP(wxSize(650, 840)); - SetSize(pSize); + // The preferred size can exceed the work area (e.g. 840 DIP at 150% on a 1080p screen), + // which would push the title bar off screen, so clamp it to the display the dialog is on. + const wxRect work_area = wxDisplay(GetParent()).GetClientArea(); + const int margin = FromDIP(20); + const wxSize max_size(std::max(1, work_area.GetWidth() - margin), std::max(1, work_area.GetHeight() - margin)); + + const wxSize pSize = FromDIP(wxSize(650, 840)); + SetMinSize(wxSize(std::min(FromDIP(400), max_size.GetWidth()), std::min(FromDIP(400), max_size.GetHeight()))); + SetSize(wxSize(std::min(pSize.GetWidth(), max_size.GetWidth()), std::min(pSize.GetHeight(), max_size.GetHeight()))); CentreOnParent(); + + // Keep the whole dialog, title bar included, inside the work area. + wxRect rect = GetRect(); + rect.x = std::max(work_area.GetLeft(), std::min(rect.x, work_area.GetRight() + 1 - rect.width)); + rect.y = std::max(work_area.GetTop(), std::min(rect.y, work_area.GetBottom() + 1 - rect.height)); + Move(rect.GetPosition()); } wxGetApp().UpdateDlgDarkUI(this); } From a8a597c6d5084d4c749ea2a4e44025d69a304b5a Mon Sep 17 00:00:00 2001 From: Alexander Vander Kelen Date: Sat, 21 Nov 2026 13:01:33 -0600 Subject: [PATCH 36/36] Fix LAN Bambu printer losing its connection when the cloud server connects (#17769) The server-connected handler selects the agent's current machine again every time the cloud server connects. For a LAN printer this makes the Bambu network plug-in unsubscribe the device, which drops the LAN session that selecting the printer opened. A connect still in flight fails with "called UnSubscribeDevice". One that already succeeded stays down with no connect result, so the printer shows as connected while every command fails with -4 and Print fails with -4030. Since #17086, OrcaSlicer connects the last LAN Bambu printer at startup, so a LAN user hits this on most starts. A cloud reconnect later in a session drops the session the same way. The selection is a cloud subscription, so a LAN printer does not need it. Move the re-select into DeviceManager::reselect_cloud_machine(), which skips a LAN-mode printer and behaves as before for any other machine. Fixes #17766 --- src/slic3r/GUI/DeviceCore/DevManager.cpp | 17 +++++++++ src/slic3r/GUI/DeviceCore/DevManager.h | 3 ++ src/slic3r/GUI/GUI_App.cpp | 6 ++- .../test_device_manager_integration.cpp | 38 +++++++++++++++++++ 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/slic3r/GUI/DeviceCore/DevManager.cpp b/src/slic3r/GUI/DeviceCore/DevManager.cpp index be59142997..52e238fd1a 100644 --- a/src/slic3r/GUI/DeviceCore/DevManager.cpp +++ b/src/slic3r/GUI/DeviceCore/DevManager.cpp @@ -865,6 +865,23 @@ namespace Slic3r m_agent->add_subscribe(subscribe_list_cache); } + void DeviceManager::reselect_cloud_machine() + { + if (!m_agent) + return; + + // The selection is a cloud subscription, and a LAN printer has none. Selecting one makes the + // Bambu network plugin unsubscribe the device, which drops the LAN session that connected it: + // a connect still in flight fails, and one that already succeeded stays down with no connect + // result to say so. + const std::string dev_id = m_agent->get_user_selected_machine(); + const MachineObject* obj = get_my_machine(dev_id); + if (obj && obj->is_lan_mode_printer()) + return; + + m_agent->set_user_selected_machine(dev_id); + } + std::map DeviceManager::get_my_machine_list(const std::string& agent_id) { std::map result; diff --git a/src/slic3r/GUI/DeviceCore/DevManager.h b/src/slic3r/GUI/DeviceCore/DevManager.h index 820c594685..0f30568d16 100644 --- a/src/slic3r/GUI/DeviceCore/DevManager.h +++ b/src/slic3r/GUI/DeviceCore/DevManager.h @@ -104,6 +104,9 @@ public: void add_user_subscribe(); void del_user_subscribe(); void subscribe_device_list(std::vector dev_list); + // Selects the agent's selected machine again, which subscribes a cloud printer once the cloud + // server has connected. A LAN printer is left as it is. + void reselect_cloud_machine(); /* my machine*/ MachineObject* get_my_machine(std::string dev_id); diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 46cf29cc39..3257f9bbaa 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -2341,12 +2341,14 @@ void GUI_App::init_networking_callbacks() if (provider != this->get_printer_cloud_provider()) { return; } - m_agent->set_user_selected_machine(m_agent->get_user_selected_machine()); + if (m_device_manager) + m_device_manager->reselect_cloud_machine(); if (this->is_enable_multi_machine()) { auto evt = new wxCommandEvent(EVT_UPDATE_MACHINE_LIST); wxQueueEvent(this, evt); } - m_agent->set_user_selected_machine(m_agent->get_user_selected_machine()); + if (m_device_manager) + m_device_manager->reselect_cloud_machine(); if (m_agent->is_user_login(provider)) { /*disconnect lan*/ diff --git a/tests/slic3rutils/test_device_manager_integration.cpp b/tests/slic3rutils/test_device_manager_integration.cpp index 2994ca6793..d64b141317 100644 --- a/tests/slic3rutils/test_device_manager_integration.cpp +++ b/tests/slic3rutils/test_device_manager_integration.cpp @@ -70,9 +70,16 @@ public: return 0; } + int set_user_selected_machine(std::string dev_id) override + { + ++selections; + return OrcaPrinterAgent::set_user_selected_machine(std::move(dev_id)); + } + std::string published_device; json published_message; std::string connected_ca_file; + int selections{0}; private: AgentInfo m_info; @@ -277,6 +284,37 @@ TEST_CASE("Logging out cancels a pending last-machine restore", "[DeviceManager] CHECK_FALSE(manager.has_pending_last_machine_restore()); } +TEST_CASE("A cloud server connection selects a cloud printer again but leaves a LAN printer alone", "[DeviceManager][integration]") +{ + ScopedAppConfig app_config; + auto agent = std::make_shared("integration-agent"); + NetworkAgent network(nullptr, agent); + network.set_printer_agent(agent); + DeviceManager manager(&network, false, &app_config.config); + + BBLocalMachine machine; + machine.dev_id = "integration-lan-device"; + machine.dev_name = "Integration LAN device"; + machine.dev_ip = "192.0.2.10"; + machine.printer_type = "C11"; + REQUIRE(manager.insert_local_device(machine, "lan", "free", "", "access-code") != nullptr); + manager.parse_user_print_info(machine_list_response(ORCA_CLOUD_PROVIDER, "integration-agent", + network.get_user_machine_list_generation(), "Cloud printer")); + REQUIRE(manager.get_user_machinelist().count("integration-device") == 1); + + // The agent names the LAN printer once it is connected, as the Bambu network plugin does. + agent->set_user_selected_machine(machine.dev_id); + agent->selections = 0; + manager.reselect_cloud_machine(); + CHECK(agent->selections == 0); + + agent->set_user_selected_machine("integration-device"); + agent->selections = 0; + manager.reselect_cloud_machine(); + CHECK(agent->selections == 1); + CHECK(agent->get_user_selected_machine() == "integration-device"); +} + TEST_CASE("A CA file stays with the agent that saved it when a device is rebound", "[DeviceManager][integration]") { ScopedAppConfig app_config;