diff --git a/docs/HLSD/resource-printer-assets.md b/docs/HLSD/resource-printer-assets.md new file mode 100644 index 0000000000..218ea77f5d --- /dev/null +++ b/docs/HLSD/resource-printer-assets.md @@ -0,0 +1,98 @@ +# Resource Printer Assets — High Level Design + +## Purpose and scope + +A resource printer asset pack is a plugin that ships bed models (`.stl`) and bed textures +(`.png`, `.svg`). A printer preset refers to a pack file by a portable reference instead of an +absolute path, so a shared preset keeps its custom bed on another machine. + +Packs hold files only. They never run code at use time and never modify a preset. + +The type is independent of the resource texture type (`resource-texture`). It has its own +capability, registry, loader branch and tests, so either can be changed or removed without the +other. + +## Capability + +| Orca Cloud type | Capability id | Python base class | Directory method | +|---|---|---|---| +| `resource-printer-assets` | `resource-printer-asset` | `orca.resource_printer_asset.ResourcePrinterAssetPluginCapabilityBase` | `get_asset_dir()` | + +Orca Cloud builds the wheel from the uploaded files, so the author writes no Python. The loader +calls `get_asset_dir()` once per capability under the GIL and caches the result. + +## Loading and validation + +`collect_printer_asset_files` lists the folder: + +- it must be set, exist, and be inside the plugin folder; +- only regular files directly in it (no recursion), with extension `.stl`, `.png` or `.svg` + (any case), each inside the plugin folder after symlink resolution; +- the file name must be one a reference can hold (see References), so a file the Bed Shape + dialog cannot offer never takes a slot; +- the list is sorted, then capped at 16, so every file system keeps the same files. + +A Python error or a rejected folder leaves the capability loaded with no files. It never fails +the plugin load. + +## Registry + +`PluginPrinterAssets` tracks every loaded and enabled `resource-printer-asset` capability. An +entry stores strings only (never a Python object, which would outlive the interpreter): ids, +paths and the validated file list. The folder is listed once, when the pack loads, and a file +added later appears after the plugin reloads. Its lifecycle functions return whether the set of +packs changed, so the bed is redrawn only then. + +The Bed Shape dialog lists `.stl` files for the model and `.png`/`.svg` files for the texture, +chosen by extension. + +## References + +`bed_custom_model` and `bed_custom_texture` store `orcacloud-asset//` +(`libslic3r/PrinterAssetRef.hpp`). `` is the Orca Cloud plugin uuid, or the plugin +key for a pack installed by hand. `` uses `A–Z a–z 0–9 . _ -`, at most 128 characters, and +is not a Windows device name (`CON`, `NUL`, `COM1`, ...). A reference has no colon or backslash, +so it is the same on every OS. + +`resolve` matches the file name against the validated list, so a reference cannot leave the +pack. A slicer without the pack resolves nothing and draws the vendor bed, the same as a foreign +absolute path. + +## Printer manifest + +The hidden option `printer_asset_plugins` names the packs the bed files come from. It is +plugin-backed with type `resource-printer-asset`, so the printer preset manifest +(`printer_plugins`) lists them and the missing-plugin notice offers the install. A before-save +hook re-derives the option on every printer preset save. A pack that is not installed here keeps +the name and the manifest entry already in the saved preset, even when a loaded plugin has a +capability of the same name. The notice never blocks slicing. + +A preset saved as a diff against its parent writes a manifest derived from its whole resolved +config, not from the diff, so references inherited from the parent stay listed. + +A printer preset written before `printer_plugins` existed holds its references under the process +preset's `plugins` key. Loading moves them into `printer_plugins` before the unknown-key check, +for a parentless preset and for one that inherits a parent (merged with the parent's manifest), +so an upgrade keeps the notice for a plugin this machine lacks. + +The G-code config block writes `printer_asset_plugins` and `printer_plugins` only when they are +not empty, so a printer without packs keeps an unchanged block and a printer created from the +G-code keeps its manifest. + +## Constraints + +- Windows `MAX_PATH`: installed files sit under a long `orca_plugins` path, so Orca Cloud caps + asset file names at 64 characters. The slicer logs a file it cannot read. +- Orca Cloud caps a pack at 8 files; the slicer allows 16. +- Pack files are read-only. +- Orca Cloud validates uploaded content (STL structure, PNG size, SVG active content). The + slicer re-checks only the folder layout and extensions. +- A file's use follows its extension. A pack cannot give one extension two uses. +- A plugin is expected to provide one `resource-printer-asset` capability, because a reference names + the plugin, not the capability. With several, the name recorded for a loaded pack is the capability + whose folder holds the file; for a pack that is not loaded it comes from the saved manifest. +- A cloud plugin id is compared without regard to case; the reference stores it in lower case. +- A reference to a hand-installed pack uses the plugin key. It resolves only on a machine that has + that key, and its manifest entry has no uuid, so no other machine is offered the install. +- Keeping a cloud plugin as a local one replaces its uuid with the plugin key, so references that + name the uuid stop resolving. diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index 0a75b38502..678cc291ee 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -421,6 +421,7 @@ set(lisbslic3r_sources PresetBundle.cpp PresetBundle.hpp PrinterBedAssets.hpp + PrinterAssetRef.hpp PresetCacheFormat.cpp PresetCacheFormat.hpp Preset.cpp diff --git a/src/libslic3r/Config.cpp b/src/libslic3r/Config.cpp index 3e71ee8a23..8687d2b947 100644 --- a/src/libslic3r/Config.cpp +++ b/src/libslic3r/Config.cpp @@ -1554,7 +1554,7 @@ void ConfigBase::save_to_json(const std::string &file, const std::string &name, BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ":" <<__LINE__ << boost::format(", saved config to %1%\n")%file; } -void ConfigBase::save_to_json(std::ostream &os, const std::string &name, const std::string &from, const std::string &version, bool replace_invalid_utf8) const +void ConfigBase::save_to_json(std::ostream &os, const std::string &name, const std::string &from, const std::string &version, bool replace_invalid_utf8, const ConfigBase *manifest_source) const { json j; //record the headers @@ -1589,18 +1589,20 @@ void ConfigBase::save_to_json(std::ostream &os, const std::string &name, const s } } - // Serialize the top-level "plugins" manifest: the individual plugin-backed options keep bare + // Serialize the top-level plugin manifest: the individual plugin-backed options keep bare // capability names; the full "name;uuid;capability" references are derived here (same helper as // update_plugin_manifest). Only with a resolver (GUI); without one (CLI/headless) leave whatever - // the "plugins" option already serialized above, so a round-trip never drops the manifest. A value - // the resolver cannot map is omitted; unresolved_plugin_capabilities() reports it so a GUI save - // entry point can prompt before writing. + // the manifest option already serialized above, so a round-trip never drops the manifest. A value + // the resolver cannot map keeps its existing manifest entry; one with no entry is omitted, and + // unresolved_plugin_capabilities() reports it so a GUI save entry point can prompt before writing. if (resolve_capability_fn) { - std::vector unique_refs = this->collect_plugin_manifest(); + const ConfigBase &source = manifest_source != nullptr ? *manifest_source : *this; + const std::string manifest_key = source.plugin_manifest_key(); + std::vector unique_refs = source.collect_plugin_manifest(); if (unique_refs.empty()) - j.erase("plugins"); + j.erase(manifest_key); else - j["plugins"] = unique_refs; + j[manifest_key] = unique_refs; } os << j.dump(1, '\t', false, replace_invalid_utf8 ? json::error_handler_t::replace : json::error_handler_t::strict) << std::endl; @@ -1657,6 +1659,20 @@ void ConfigBase::for_each_plugin_capability(const std::functionoption(this->plugin_manifest_key())) + for (const std::string& entry : manifest->values) + if (const auto ref = parse_capability_ref(entry); ref && ref->capability_name == capability_name) + return entry; + return {}; +} + std::vector ConfigBase::collect_plugin_manifest() const { std::vector refs; @@ -1664,10 +1680,10 @@ std::vector ConfigBase::collect_plugin_manifest() const return refs; // Resolve each capability value and append its full reference, dropping duplicates (preserving - // insertion order). A value that resolves nowhere has no reference to write, so it is skipped; - // unresolved_plugin_capabilities() reports those values so a GUI save can prompt. - this->for_each_plugin_capability([&refs](const std::string& /* opt_key */, const std::string& plugin_type, const std::string& capability_name) { - std::string ref = resolve_capability_fn(capability_name, plugin_type); + // insertion order). A value with no reference to write is skipped; unresolved_plugin_capabilities() + // reports those values so a GUI save can prompt. + this->for_each_plugin_capability([this, &refs](const std::string& /* opt_key */, const std::string& plugin_type, const std::string& capability_name) { + std::string ref = this->plugin_reference(capability_name, plugin_type); if (!ref.empty() && std::find(refs.begin(), refs.end(), ref) == refs.end()) refs.emplace_back(std::move(ref)); }); @@ -1682,10 +1698,10 @@ std::vector ConfigBase::unresolved_plugin_capabiliti if (!resolve_capability_fn) return unresolved; - // Same walk and same resolver call as collect_plugin_manifest: a value is reported here exactly + // Same walk and same reference lookup as collect_plugin_manifest: a value is reported here exactly // when the serializer would omit it. - this->for_each_plugin_capability([&unresolved](const std::string& opt_key, const std::string& plugin_type, const std::string& capability_name) { - if (!resolve_capability_fn(capability_name, plugin_type).empty()) + this->for_each_plugin_capability([this, &unresolved](const std::string& opt_key, const std::string& plugin_type, const std::string& capability_name) { + if (!this->plugin_reference(capability_name, plugin_type).empty()) return; const auto matches = [&opt_key, &capability_name](const UnresolvedPluginCapability& entry) { return entry.opt_key == opt_key && entry.capability_name == capability_name; @@ -1698,14 +1714,23 @@ std::vector ConfigBase::unresolved_plugin_capabiliti void ConfigBase::update_plugin_manifest() { - // Writes the derived manifest back into this config's "plugins" option (save_to_json writes the + // Writes the derived manifest back into this config's manifest option (save_to_json writes the // same manifest into a JSON document instead), so an in-memory backend config carries a resolved // manifest even when the source preset was never serialized (picked-but-unsaved). Without a // resolver (CLI/headless) leave whatever manifest was loaded from disk untouched. if (!resolve_capability_fn) return; - if (auto* manifest = this->option("plugins", true)) - manifest->values = this->collect_plugin_manifest(); + std::vector refs = this->collect_plugin_manifest(); + if (auto* manifest = this->option(this->plugin_manifest_key(), true)) + manifest->values = std::move(refs); +} + +std::string ConfigBase::plugin_manifest_key() const +{ + // A printer preset config holds "printer_plugins" but not the process preset's "plugins": the full + // print config applies the printer preset after the process preset, so a shared key would replace + // the process manifest. A full config holds both and keeps the combined manifest in "plugins". + return this->option("printer_plugins") != nullptr && this->option("plugins") == nullptr ? "printer_plugins" : "plugins"; } DynamicConfig::DynamicConfig(const ConfigBase& rhs, const t_config_option_keys& keys) diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp index b2a79331bd..1cb5aa5527 100644 --- a/src/libslic3r/Config.hpp +++ b/src/libslic3r/Config.hpp @@ -2554,9 +2554,9 @@ public: std::string gui_flags; // Capability type of a plugin-backed option, e.g. "slicing-pipeline" / "printer-connection" // (empty for ordinary options). GUIType::plugin_picker filters the plugin list by it, and it - // resolves the option's "plugins" manifest reference; see is_plugin_backed(). + // resolves the option's manifest reference; see is_plugin_backed(). std::string plugin_type; - // Whether this option holds plugin capability name(s) that feed the "plugins" manifest -- true + // Whether this option holds plugin capability name(s) that feed the plugin manifest -- true // iff it declares a plugin_type. Setting plugin_type is the only step needed to add one. bool is_plugin_backed() const { return !plugin_type.empty(); } // Label of the GUI input field. @@ -2726,10 +2726,10 @@ public: // A plugin-backed option value that the registered capability resolver cannot map to a plugin -// reference, i.e. a capability whose plugin is not available here. save_to_json() and -// update_plugin_manifest() cannot derive a reference for such a value and omit it, so a GUI save -// entry point queries this first and lets the user decide before writing a preset that loses the -// reference. See ConfigBase::unresolved_plugin_capabilities(). +// reference, i.e. a capability whose plugin is not available here, and that the manifest holds no +// entry for either. save_to_json() and update_plugin_manifest() cannot derive a reference for such a +// value and omit it, so a GUI save entry point queries this first and lets the user decide before +// writing a preset that loses the reference. See ConfigBase::unresolved_plugin_capabilities(). struct UnresolvedPluginCapability { // Option holding the capability name, e.g. "printer_agent". @@ -2890,24 +2890,32 @@ public: void save_to_json(const std::string &file, const std::string &name, const std::string &from, const std::string &version) const; // Same document, written to a stream. Invalid UTF-8 in a string value throws nlohmann's type_error unless // replace_invalid_utf8 is set, which writes U+FFFD instead (for callers such as stdout with no handler). - void save_to_json(std::ostream &os, const std::string &name, const std::string &from, const std::string &version, bool replace_invalid_utf8 = false) const; + // A non-null manifest_source supplies the plugin manifest key and the references derived from it. A + // document written as a diff against a parent holds only the options this preset changes, so deriving + // the manifest from it would drop the references the preset inherits. + void save_to_json(std::ostream &os, const std::string &name, const std::string &from, const std::string &version, + bool replace_invalid_utf8 = false, const ConfigBase *manifest_source = nullptr) const; - // Rebuild the in-memory "plugins" manifest (the "name;uuid;capability" references the plugin + // Rebuild the in-memory plugin manifest (the "name;uuid;capability" references the plugin // dispatchers consume) from the plugin-backed options via the registered resolver. save_to_json() // derives the same manifest, but only when a preset is written to disk; a config assembled in // memory for the backend (PresetBundle::full_config -> Print::apply) must refresh it here or a // picked-but-unsaved plugin never resolves at slice/export time. A capability the resolver cannot - // map is omitted from the derived manifest; unresolved_plugin_capabilities() reports those - // values. No-op without a resolver. + // map keeps its existing manifest entry; one with no entry is omitted, and + // unresolved_plugin_capabilities() reports it. No-op without a resolver. void update_plugin_manifest(); - // The plugin-backed option values the registered resolver cannot map to a plugin reference -- - // exactly the values save_to_json()/update_plugin_manifest() omit from the manifest. GUI save + // The plugin-backed option values for which save_to_json()/update_plugin_manifest() would write no + // reference -- the resolver cannot map them and the manifest holds no entry for them. GUI save // entry points call this before writing a preset so the user can be warned that the reference // will be lost. Returns empty without a resolver (CLI/headless), where the manifest is left as // loaded and nothing is lost. std::vector unresolved_plugin_capabilities() const; + // The key holding this config's plugin manifest: "printer_plugins" for a printer preset config, + // "plugins" for every other config. The single definition of that rule. + std::string plugin_manifest_key() const; + // Set all the nullable values to nils. void null_nullables(); @@ -2917,11 +2925,14 @@ private: // Set a configuration value from a string. bool set_deserialize_raw(const t_config_option_key& opt_key_src, const std::string& value, ConfigSubstitutionContext& substitutions, bool append); // Collect the de-duplicated "name;uuid;capability" plugin references derived from this config's - // plugin-backed options via the resolver. Shared by save_to_json (serializes them into the JSON - // manifest) and update_plugin_manifest (writes them back into the "plugins" option). Order is - // preserved and values that do not resolve are dropped; returns empty without a resolver + // plugin-backed options via plugin_reference. Shared by save_to_json (serializes them into the JSON + // manifest) and update_plugin_manifest (writes them back into the manifest option). Order is + // preserved and values with no reference are dropped; returns empty without a resolver // (CLI/headless). std::vector collect_plugin_manifest() const; + // The reference for one capability value: the resolver's, else the entry the manifest already + // holds for it. Empty when neither has one. + std::string plugin_reference(const std::string& capability_name, const std::string& plugin_type) const; // Calls fn(opt_key, plugin_type, capability_name) for every non-empty capability name held by a // plugin-backed option of this config, in key order. A single walk feeds both the serializer // (collect_plugin_manifest) and unresolved_plugin_capabilities, so they cannot disagree on which diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 49b112c00d..5821910ad2 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -8411,9 +8411,17 @@ void GCode::append_full_config(const Print &print, std::string &str) auto is_banned = [](const std::string &key) { return banned_keys.find(key) != banned_keys.end(); }; + // printer_asset_plugins and printer_plugins default to empty and are written only when set, so a + // printer without packs keeps its block unchanged. Both are read back by PresetBundle::config_from_gcode. + auto is_empty_plugin_list = [&cfg](const std::string &key) { + if (key != "printer_asset_plugins" && key != "printer_plugins") + return false; + const ConfigOption *opt = cfg.option(key); + return opt->type() == coStrings && static_cast(opt)->values.empty(); + }; std::ostringstream ss; for (const std::string& key : cfg.keys()) { - if (!is_banned(key) && !cfg.option(key)->is_nil()) { + if (!is_banned(key) && !cfg.option(key)->is_nil() && !is_empty_plugin_list(key)) { if (key == "wipe_tower_x" || key == "wipe_tower_y") { ss << std::fixed << std::setprecision(3) << "; " << key << " = " << dynamic_cast(cfg.option(key))->get_at(print.get_plate_index()) << "\n"; } diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index e85efa6643..dd38ff8cbc 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -601,12 +601,70 @@ void Preset::normalize(DynamicPrintConfig &config) handle_legacy_sla(config); } +// Append the references that are not present yet, keeping the order. +static void append_plugin_refs(std::vector &refs, const std::vector &added) +{ + for (const std::string &ref : added) + if (std::find(refs.begin(), refs.end(), ref) == refs.end()) + refs.push_back(ref); +} + +// A printer preset written before the printer manifest key existed stores its plugin references under +// the process preset's key, "plugins". That key is not a printer option, so loading would report and +// strip the references; rename them here instead, before the validation below. Only a printer config +// has the target key, so the caller checks that first: a print or filament config carries "plugins" +// as its own manifest and must keep it. +// Returns true when they were moved, so the validation does not report the key it renamed. +static bool migrate_legacy_printer_plugin_manifest(DynamicPrintConfig &config) +{ + const auto *legacy = config.option("plugins"); + auto *manifest = config.option("printer_plugins"); + if (legacy == nullptr || manifest == nullptr) + return false; + // Merge, not replace: a child preset's file holds only the references it added, while the parent's + // manifest already sits in the config this one was built from. + append_plugin_refs(manifest->values, legacy->values); + config.erase("plugins"); + return true; +} + +// A child preset's file may hold the plugin references it adds under the process preset's "plugins" +// (written before the printer manifest key existed). That key is not a printer option, so a merge +// against the parent drops it; the caller takes the values out before the merge and appends them after. +static std::vector take_legacy_printer_plugin_manifest(DynamicPrintConfig &config, Preset::Type type) +{ + if (type != Preset::TYPE_PRINTER) + return {}; + auto *legacy = config.option("plugins"); + if (legacy == nullptr) + return {}; + std::vector refs = std::move(legacy->values); + config.erase("plugins"); + return refs; +} + +// Merge, not replace: a child file holds only the references it added, while the parent's manifest +// already sits in the config the child was built from. +static void merge_legacy_printer_plugin_manifest(DynamicPrintConfig &config, const std::vector &refs) +{ + if (refs.empty()) + return; + if (auto *manifest = config.option("printer_plugins", true)) + append_plugin_refs(manifest->values, refs); +} + std::string Preset::remove_invalid_keys(DynamicPrintConfig &config, const DynamicPrintConfig &default_config, const DynamicPrintConfig *added) { + // Only a printer config has "printer_plugins" in its defaults; a print or filament config that + // happens to carry both keys must keep "plugins", its own manifest. + const bool migrated_plugins = default_config.has("printer_plugins") && migrate_legacy_printer_plugin_manifest(config); + std::string incorrect_keys; for (const std::string &key : (added != nullptr ? *added : config).keys()) if (! default_config.has(key)) { + if (migrated_plugins && key == "plugins") + continue; if (incorrect_keys.empty()) incorrect_keys = key; else { @@ -854,7 +912,10 @@ bool Preset::save(DynamicPrintConfig* parent_config) } std::ostringstream json; - to_save->save_to_json(json, bare_name, from_str, this->version.to_string()); + // A diff holds only the options this preset changes, so the manifest is derived from the full config: + // it also holds the references the preset inherits from its parent. + const ConfigBase *manifest_source = parent_config != nullptr ? &this->config : nullptr; + to_save->save_to_json(json, bare_name, from_str, this->version.to_string(), false, manifest_source); InstanceLock instance_lock(user_presets_lock_path()); boost::filesystem::create_directories(fs::path(this->file).parent_path()); @@ -885,8 +946,10 @@ void Preset::reload(Preset const &parent) try { InstanceLock instance_lock(user_presets_lock_path()); ConfigSubstitutions config_substitutions = config.load_from_json(file, substitution_rule, key_values, reason); + const std::vector legacy_plugin_refs = take_legacy_printer_plugin_manifest(config, this->type); this->config = parent.config; this->config.apply(std::move(config)); + merge_legacy_printer_plugin_manifest(this->config, legacy_plugin_refs); } catch (const std::exception &err) { BOOST_LOG_TRIVIAL(error) << boost::format("Failed loading the user-config file: %1%. Reason: %2%") % file % err.what(); } @@ -1619,7 +1682,7 @@ static std::vector s_Preset_machine_limits_options { static std::vector s_Preset_printer_options { "printer_technology", - "printable_area", "extruder_printable_area", "support_parallel_printheads", "parallel_printheads_count", "parallel_printheads_bed_exclude_areas", "bed_exclude_area","bed_custom_texture", "bed_custom_model", "build_plate_tilt_x", "build_plate_tilt_y", "belt_printer", "belt_printer_infinite_y", + "printable_area", "extruder_printable_area", "support_parallel_printheads", "parallel_printheads_count", "parallel_printheads_bed_exclude_areas", "bed_exclude_area","bed_custom_texture", "bed_custom_model", "printer_asset_plugins", "printer_plugins", "build_plate_tilt_x", "build_plate_tilt_y", "belt_printer", "belt_printer_infinite_y", "belt_slice_rotation", "belt_slice_rotation_angle", "gcode_remap_x", "gcode_remap_y", "gcode_remap_z", "belt_frame_tilt_decouple", "belt_frame_tilt_angle", @@ -1940,11 +2003,13 @@ PresetCollection::UserPresetLoad PresetCollection::resolve_user_preset( } const Preset& default_preset = this->default_preset_for(config); if (inherit_preset) { + const std::vector legacy_plugin_refs = take_legacy_printer_plugin_manifest(config, m_type); preset.config = inherit_preset->config; preset.filament_id = inherit_preset->filament_id; extend_parent_extruders_to_child(preset.config, config, m_type); extend_default_config_length(config, false, {}); preset.config.update_diff_values_to_child_config(config, extruder_id_name, extruder_variant_name, *key_set1, *key_set2); + merge_legacy_printer_plugin_manifest(preset.config, legacy_plugin_refs); pad_printer_variant_vectors(preset.config); } else { @@ -2347,11 +2412,13 @@ void PresetCollection::load_project_embedded_presets(std::vector& proje } const Preset& default_preset = this->default_preset_for(config); if (inherit_preset) { + const std::vector legacy_plugin_refs = take_legacy_printer_plugin_manifest(config, m_type); preset->config = inherit_preset->config; preset->filament_id = inherit_preset->filament_id; extend_parent_extruders_to_child(preset->config, config, m_type); extend_default_config_length(config, false, {}); preset->config.update_diff_values_to_child_config(config, extruder_id_name, extruder_variant_name, *key_set1, *key_set2); + merge_legacy_printer_plugin_manifest(preset->config, legacy_plugin_refs); } else if (inherits_value.empty() && m_type == Preset::TYPE_FILAMENT && config.has("filament_extruder_variant")) { @@ -2765,8 +2832,11 @@ bool PresetCollection::load_user_preset(std::string name, std::map legacy_plugin_refs = take_legacy_printer_plugin_manifest(cloud_config, m_type); new_config.update_diff_values_to_child_config(cloud_config, extruder_id_name, extruder_variant_name, *key_set1, *key_set2); + merge_legacy_printer_plugin_manifest(new_config, legacy_plugin_refs); + } else{ new_config.apply(std::move(cloud_config)); extend_default_config_length(new_config, true, default_preset.config); @@ -3468,9 +3538,13 @@ std::map> PresetCollection::get_filamen } //BBS: add project embedded preset logic +PresetCollection::BeforeSaveFn PresetCollection::s_before_save_fn; + void PresetCollection::save_current_preset(const std::string &new_name, bool detach, bool save_to_project, Preset* _curr_preset) { Preset curr_preset = _curr_preset ? *_curr_preset : m_edited_preset; + if (s_before_save_fn) + s_before_save_fn(m_type, curr_preset.config, this->get_selected_preset().config); //BBS: add lock logic for sync preset in background std::string final_inherits; lock(); diff --git a/src/libslic3r/Preset.hpp b/src/libslic3r/Preset.hpp index a8bc07a7a6..8ebd9e42e9 100644 --- a/src/libslic3r/Preset.hpp +++ b/src/libslic3r/Preset.hpp @@ -705,6 +705,11 @@ public: // All presets are marked as not modified and the new preset is activated. //BBS: add project embedded preset logic void save_current_preset(const std::string &new_name, bool detach = false, bool save_to_project = false, Preset* _curr_preset = nullptr); + // Runs on the config save_current_preset is about to store, with the selected (saved) preset's + // config for context, so values derived from others stay in step whichever dialog saves. The GUI + // installs it (plugin_hooks::install); without one, configs are saved as they are. + using BeforeSaveFn = std::function; + static void set_before_save_fn(BeforeSaveFn fn) { s_before_save_fn = std::move(fn); } // Insert a standalone user preset holding the full resolved config (no inheritance, // no vendor links): the libslic3r equivalent of "Detach from parent". Takes a // resolved config, clears parent/vendor/alias metadata, stamps filament_settings_id. @@ -969,6 +974,8 @@ protected: void set_custom_preset_alias(Preset &preset); private: + static BeforeSaveFn s_before_save_fn; + // A preset file and its .info as read from disk, std::nullopt for one that is missing. struct PresetFilesOnDisk { diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 74086b93b2..514c23c70e 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -433,7 +433,11 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "use_3mf" }; - static std::unordered_set steps_ignore; + static std::unordered_set steps_ignore = { + // Which printer asset packs and printer plugins the printer preset uses: no influence on slicing. + "printer_asset_plugins", + "printer_plugins", + }; static const std::unordered_set steps_exclusion_geometry = { "bed_exclude_area", "bed_exclude_volumes", diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 7fb62a3e1b..114452136f 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -1120,6 +1120,24 @@ void PrintConfigDef::init_common_params() def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionString()); + // The printer asset packs whose files bed_custom_model / bed_custom_texture refer to + // ("orcacloud-asset//"), by capability name. Plugin-backed, so the packs land in + // the printer preset's manifest and a machine without them is offered the install. + def = this->add("printer_asset_plugins", coStrings); + def->label = L("Printer asset plugins"); + def->tooltip = L("Resource printer asset plugins whose bed model or texture this printer uses."); + def->mode = comDevelop; + def->plugin_type = "resource-printer-asset"; + def->set_default_value(new ConfigOptionStrings()); + + // A printer preset's plugin manifest. It is kept apart from the process preset's "plugins": the + // full print config applies the printer preset last, so a shared key would replace that manifest. + def = this->add("printer_plugins", coStrings); + def->label = L("Printer plugins used"); + def->tooltip = L("Plugin capabilities referenced by this printer preset, stored as name;uuid;capability."); + def->mode = comDevelop; + def->set_default_value(new ConfigOptionStrings()); + def = this->add("elefant_foot_compensation", coFloat); def->label = L("Elephant foot compensation"); def->category = L("Quality"); diff --git a/src/libslic3r/PrinterAssetRef.hpp b/src/libslic3r/PrinterAssetRef.hpp new file mode 100644 index 0000000000..c69704c4f7 --- /dev/null +++ b/src/libslic3r/PrinterAssetRef.hpp @@ -0,0 +1,126 @@ +#ifndef slic3r_PrinterAssetRef_hpp_ +#define slic3r_PrinterAssetRef_hpp_ + +#include +#include +#include +#include + +namespace Slic3r { + +// A printer preset's bed_custom_model / bed_custom_texture can name a file in an installed +// resource-printer-asset plugin (a "printer asset pack") instead of a local path: +// +// orcacloud-asset// +// +// The value has no drive letter, colon or backslash, so it syncs, versions and shares like any +// other setting; each machine resolves it to its own installed copy of the pack. is the +// Orca Cloud plugin uuid (a local plugin key for packs installed by hand), a file directly +// inside the pack's asset folder. +inline constexpr std::string_view PRINTER_ASSET_REF_PREFIX = "orcacloud-asset/"; + +struct PrinterAssetRef +{ + std::string plugin_id; + std::string filename; +}; + +namespace printer_asset_ref_detail { + +// ASCII only, not : those predicates follow LC_CTYPE, so on a single-byte Windows codepage +// a name like "bed_é.stl" would pass here and then fail to parse on a UTF-8 machine. +inline char ascii_lower(char ch) { return (ch >= 'A' && ch <= 'Z') ? char(ch - 'A' + 'a') : ch; } + +inline bool is_ascii_alnum(char ch) +{ + return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'); +} + +// [A-Za-z0-9._-], like Orca Cloud's sanitized plugin file names; never "." or "..". +inline bool is_segment(std::string_view segment) +{ + if (segment.empty() || segment.size() > 128 || segment == "." || segment == "..") + return false; + for (const char ch : segment) { + const bool allowed = is_ascii_alnum(ch) || ch == '.' || ch == '_' || ch == '-'; + if (!allowed) + return false; + } + return true; +} + +// Windows opens CON, PRN, AUX, NUL, COM0-9 and LPT0-9, with any extension, as devices: a pack file of +// that name could not be read there. +inline bool is_windows_device_name(std::string_view filename) +{ + std::string stem(filename.substr(0, filename.find('.'))); + for (char &ch : stem) + ch = ascii_lower(ch); + if (stem == "con" || stem == "prn" || stem == "aux" || stem == "nul") + return true; + const bool digit = stem.size() == 4 && stem[3] >= '0' && stem[3] <= '9'; + return digit && (stem.compare(0, 3, "com") == 0 || stem.compare(0, 3, "lpt") == 0); +} + +inline bool is_file_segment(std::string_view segment) { return is_segment(segment) && !is_windows_device_name(segment); } + +inline bool iends_with(std::string_view value, std::string_view suffix) +{ + if (value.size() < suffix.size()) + return false; + const std::string_view tail = value.substr(value.size() - suffix.size()); + for (size_t i = 0; i < suffix.size(); ++i) + if (ascii_lower(tail[i]) != ascii_lower(suffix[i])) + return false; + return true; +} + +} // namespace printer_asset_ref_detail + +// The reference in `value`, or nullopt when it is a plain path (or malformed). +inline std::optional parse_printer_asset_ref(std::string_view value) +{ + using namespace printer_asset_ref_detail; + if (value.substr(0, PRINTER_ASSET_REF_PREFIX.size()) != PRINTER_ASSET_REF_PREFIX) + return std::nullopt; + value.remove_prefix(PRINTER_ASSET_REF_PREFIX.size()); + + const size_t slash = value.find('/'); + if (slash == std::string_view::npos) + return std::nullopt; + const std::string_view plugin_id = value.substr(0, slash); + const std::string_view filename = value.substr(slash + 1); + if (!is_segment(plugin_id) || !is_file_segment(filename)) + return std::nullopt; + return PrinterAssetRef{std::string(plugin_id), std::string(filename)}; +} + +// Empty when the id or file name cannot be stored in a reference. +inline std::string make_printer_asset_ref(std::string_view plugin_id, std::string_view filename) +{ + using namespace printer_asset_ref_detail; + if (!is_segment(plugin_id) || !is_file_segment(filename)) + return {}; + return std::string(PRINTER_ASSET_REF_PREFIX) + std::string(plugin_id) + "/" + std::string(filename); +} + +// True when a pack file of this name can be stored in a reference. +inline bool is_printer_asset_file_name(std::string_view filename) +{ + return printer_asset_ref_detail::is_file_segment(filename); +} + +// The Bed Shape dialog's file kinds: an STL bed model, a PNG or SVG bed texture. +inline bool is_printer_bed_model_file(std::string_view filename) +{ + return printer_asset_ref_detail::iends_with(filename, ".stl"); +} + +inline bool is_printer_bed_texture_file(std::string_view filename) +{ + return printer_asset_ref_detail::iends_with(filename, ".png") || printer_asset_ref_detail::iends_with(filename, ".svg"); +} + +} // namespace Slic3r + +#endif // slic3r_PrinterAssetRef_hpp_ diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 9db1ed21f0..3d4fd68ec3 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -817,6 +817,8 @@ set(SLIC3R_GUI_SOURCES plugin/host/PluginHostUi.hpp plugin/host/PluginPages.cpp plugin/host/PluginPages.hpp + plugin/host/PluginPrinterAssets.cpp + plugin/host/PluginPrinterAssets.hpp plugin/host/PluginResourceTextures.cpp plugin/host/PluginResourceTextures.hpp plugin/CloudPluginService.cpp @@ -846,6 +848,9 @@ set(SLIC3R_GUI_SOURCES plugin/pluginTypes/resourceTexture/ResourceTexturePluginCapability.hpp plugin/pluginTypes/resourceTexture/ResourceTexturePluginCapability.cpp plugin/pluginTypes/resourceTexture/ResourceTexturePluginCapabilityTrampoline.hpp + plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.hpp + plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.cpp + plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapabilityTrampoline.hpp plugin/pluginTypes/script/ScriptPluginCapability.hpp plugin/pluginTypes/script/ScriptPluginCapability.cpp plugin/pluginTypes/script/ScriptPluginCapabilityTrampoline.hpp diff --git a/src/slic3r/GUI/BedShapeDialog.cpp b/src/slic3r/GUI/BedShapeDialog.cpp index b174476837..2bd2b23523 100644 --- a/src/slic3r/GUI/BedShapeDialog.cpp +++ b/src/slic3r/GUI/BedShapeDialog.cpp @@ -6,8 +6,10 @@ #include "libslic3r/Point.hpp" #include #include +#include #include "libslic3r/Config.hpp" #include +#include #include #include "libslic3r/BuildVolume.hpp" #include "slic3r/GUI/Field.hpp" @@ -39,6 +41,9 @@ #include "libslic3r/ClipperUtils.hpp" #include "Widgets/LabeledStaticBox.hpp" +#include "libslic3r/PrinterAssetRef.hpp" +#include "slic3r/plugin/host/PluginPrinterAssets.hpp" +#include #include "Widgets/DialogButtons.hpp" #include @@ -343,6 +348,12 @@ wxPanel* BedShapePanel::init_texture_panel() wxSizer* load_sizer = new wxBoxSizer(wxHORIZONTAL); load_sizer->Add(load_btn, 1, wxEXPAND); + Button* pack_btn = new Button(parent, _L("From asset pack...")); + pack_btn->SetStyle(ButtonStyle::Regular, ButtonType::Expanded); + + wxSizer* pack_sizer = new wxBoxSizer(wxHORIZONTAL); + pack_sizer->Add(pack_btn, 1, wxEXPAND); + wxStaticText* filename_lbl = new wxStaticText(parent, wxID_ANY, _(NONE)); wxSizer* filename_sizer = new wxBoxSizer(wxHORIZONTAL); filename_sizer->Add(filename_lbl, 1, wxEXPAND); @@ -356,9 +367,11 @@ wxPanel* BedShapePanel::init_texture_panel() wxSizer* sizer = new wxBoxSizer(wxVERTICAL); sizer->Add(filename_sizer, 1, wxEXPAND); sizer->Add(load_sizer, 1, wxEXPAND); + sizer->Add(pack_sizer, 1, wxEXPAND | wxTOP, 2); sizer->Add(remove_sizer, 1, wxEXPAND | wxTOP, 2); load_btn->Bind(wxEVT_BUTTON, ([this](wxCommandEvent& e) { load_texture(); })); + pack_btn->Bind(wxEVT_BUTTON, ([this, pack_btn](wxCommandEvent& e) { pick_from_asset_pack(false, pack_btn); })); remove_btn->Bind(wxEVT_BUTTON, ([this](wxCommandEvent& e) { m_custom_texture = NONE; update_shape(); @@ -368,7 +381,9 @@ wxPanel* BedShapePanel::init_texture_panel() e.SetText(_(boost::filesystem::path(m_custom_texture).filename().string())); wxStaticText* lbl = dynamic_cast(e.GetEventObject()); if (lbl != nullptr) { - bool exists = (m_custom_texture == NONE) || boost::filesystem::exists(m_custom_texture); + // A printer asset reference counts as found once its pack is installed. + const std::string texture_file = resolve_printer_asset_value(m_custom_texture); + bool exists = (m_custom_texture == NONE) || (!texture_file.empty() && boost::filesystem::exists(texture_file)); lbl->SetForegroundColour(exists ? wxGetApp().get_label_clr_default() : wxColour("#E14747")); // ORCA wxString tooltip_text = ""; @@ -420,6 +435,12 @@ wxPanel* BedShapePanel::init_model_panel() wxSizer* load_sizer = new wxBoxSizer(wxHORIZONTAL); load_sizer->Add(load_btn, 1, wxEXPAND); + Button* pack_btn = new Button(parent, _L("From asset pack...")); + pack_btn->SetStyle(ButtonStyle::Regular, ButtonType::Expanded); + + wxSizer* pack_sizer = new wxBoxSizer(wxHORIZONTAL); + pack_sizer->Add(pack_btn, 1, wxEXPAND); + wxStaticText* filename_lbl = new wxStaticText(parent, wxID_ANY, _(NONE)); wxSizer* filename_sizer = new wxBoxSizer(wxHORIZONTAL); filename_sizer->Add(filename_lbl, 1, wxEXPAND); @@ -433,9 +454,11 @@ wxPanel* BedShapePanel::init_model_panel() wxSizer* sizer = new wxBoxSizer(wxVERTICAL); sizer->Add(filename_sizer, 1, wxEXPAND); sizer->Add(load_sizer, 1, wxEXPAND); + sizer->Add(pack_sizer, 1, wxEXPAND | wxTOP, 2); sizer->Add(remove_sizer, 1, wxEXPAND | wxTOP, 2); load_btn->Bind(wxEVT_BUTTON, ([this](wxCommandEvent& e) { load_model(); })); + pack_btn->Bind(wxEVT_BUTTON, ([this, pack_btn](wxCommandEvent& e) { pick_from_asset_pack(true, pack_btn); })); remove_btn->Bind(wxEVT_BUTTON, ([this](wxCommandEvent& e) { m_custom_model = NONE; @@ -446,7 +469,8 @@ wxPanel* BedShapePanel::init_model_panel() e.SetText(_(boost::filesystem::path(m_custom_model).filename().string())); wxStaticText* lbl = dynamic_cast(e.GetEventObject()); if (lbl != nullptr) { - bool exists = (m_custom_model == NONE) || boost::filesystem::exists(m_custom_model); + const std::string model_file = resolve_printer_asset_value(m_custom_model); + bool exists = (m_custom_model == NONE) || (!model_file.empty() && boost::filesystem::exists(model_file)); lbl->SetForegroundColour(exists ? wxGetApp().get_label_clr_default() : wxColour("#E14747")); // ORCA wxString tooltip_text = ""; @@ -661,5 +685,46 @@ void BedShapePanel::load_model() update_shape(); } +// ---------------------------------------------------------------- +// ------------ Pick a bed file from an installed printer asset pack ---------- +// ---------------------------------------------------------------- +// Lists every file of the right kind in every loaded printer asset pack ("Pack name: file"). The choice is +// stored as "orcacloud-asset//", so the preset works on any machine with the pack. +void BedShapePanel::pick_from_asset_pack(bool model, wxWindow* anchor) +{ + std::vector refs; + wxMenu menu; + for (const PrinterAssetPackEntry& pack : PluginPrinterAssets::instance().entries()) { + for (const std::string& file : pack.files) { + const std::string name = boost::filesystem::path(file).filename().string(); + if (model ? !is_printer_bed_model_file(name) : !is_printer_bed_texture_file(name)) + continue; + const std::string ref = make_printer_asset_ref(pack.pack_id, name); + if (ref.empty()) + continue; + menu.Append(wxID_HIGHEST + 1 + int(refs.size()), from_u8(pack.display_name + ": " + name)); + refs.push_back(ref); + } + } + + if (refs.empty()) { + show_info(this, + model ? _L("No installed printer asset pack has a bed model (.stl). Subscribe to a Resource printer assets plugin on Orca Cloud first.") : + _L("No installed printer asset pack has a bed texture (.png or .svg). Subscribe to a Resource printer assets plugin on Orca Cloud first."), + _L("From asset pack")); + return; + } + + menu.Bind(wxEVT_MENU, [this, model, &refs](wxCommandEvent& e) { + const int index = e.GetId() - wxID_HIGHEST - 1; + if (index < 0 || size_t(index) >= refs.size()) + return; + (model ? m_custom_model : m_custom_texture) = refs[size_t(index)]; + update_shape(); + }); + // PopupMenu is modal, so `refs` outlives every menu event. + anchor->PopupMenu(&menu, 0, anchor->GetSize().GetHeight()); +} + } // GUI } // Slic3r diff --git a/src/slic3r/GUI/BedShapeDialog.hpp b/src/slic3r/GUI/BedShapeDialog.hpp index 78211d103b..5e2402039e 100644 --- a/src/slic3r/GUI/BedShapeDialog.hpp +++ b/src/slic3r/GUI/BedShapeDialog.hpp @@ -93,6 +93,8 @@ private: void load_stl(); void load_texture(); void load_model(); + // Picks a bed model (model = true) or texture from an installed printer asset pack, stored as a reference. + void pick_from_asset_pack(bool model, wxWindow* anchor); wxSimplebook* m_shape_options_book; ComboBox* m_shape_combo; diff --git a/src/slic3r/GUI/CreatePresetsDialog.cpp b/src/slic3r/GUI/CreatePresetsDialog.cpp index 81abb463a2..8b61e2843e 100644 --- a/src/slic3r/GUI/CreatePresetsDialog.cpp +++ b/src/slic3r/GUI/CreatePresetsDialog.cpp @@ -3370,7 +3370,9 @@ bool CreatePrinterPresetDialog::save_printable_area_config(Preset *preset) assert(m_printer_name_to_preset.end() != itor); if (m_printer_name_to_preset.end() != itor) { std::shared_ptr printer_preset = itor->second; - std::vector keys = {"printable_area", "printable_height", "bed_custom_model", "bed_custom_texture"}; + // The bed files may be printer asset pack references, so the packs and manifest come along. + std::vector keys = {"printable_area", "printable_height", "bed_custom_model", "bed_custom_texture", + "printer_asset_plugins", "printer_plugins"}; config.apply_only(printer_preset->config, keys, true); } } diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 73e386e5c2..ea6becabd1 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -275,6 +275,7 @@ #include "slic3r/GUI/Widgets/Button.hpp" #include "slic3r/GUI/wxExtensions.hpp" #include "slic3r/plugin/host/PluginPages.hpp" +#include "slic3r/plugin/host/PluginPrinterAssets.hpp" #include "slic3r/plugin/host/PluginResourceTextures.hpp" #include #include "slic3r/GUI/Widgets/WebView.hpp" @@ -3191,37 +3192,58 @@ void GUI_App::init_plugin_gui_wiring() plugin_mgr.subscribe_on_unload_callback([refresh_missing_plugin_notifications](const std::string&) { refresh_missing_plugin_notifications(); }); plugin_mgr.subscribe_on_capability_unload_callback( [refresh_missing_plugin_notifications](const PluginCapabilityId&) { refresh_missing_plugin_notifications(); }); - plugin_mgr.subscribe_on_load_callback([](const std::string& plugin_key) { + // A printer asset pack came or went: redraw the bed, which may refer to it. Callbacks can fire on worker + // threads, so the redraw runs on the UI thread. + auto refresh_bed_for_asset_packs = [](bool packs_changed) { + if (!packs_changed || wxTheApp == nullptr || wxGetApp().is_closing()) + return; + wxGetApp().CallAfter([]() { + if (wxGetApp().is_closing() || wxGetApp().plater() == nullptr) + return; + wxGetApp().plater()->set_bed_shape(); + // A texture-only change does not mark the canvas dirty, so ask for a frame. + if (GLCanvas3D* canvas = wxGetApp().plater()->get_current_canvas3D()) + canvas->request_extra_frame(); + }); + }; + plugin_mgr.subscribe_on_load_callback([refresh_bed_for_asset_packs](const std::string& plugin_key) { if (wxTheApp == nullptr || wxGetApp().is_closing()) return; PluginResourceTextures::instance().on_plugin_register(plugin_key); Slic3r::GUI::bump_texture_library_generation(); + refresh_bed_for_asset_packs(PluginPrinterAssets::instance().on_plugin_register(plugin_key)); }); - plugin_mgr.subscribe_on_unload_callback([](const std::string& plugin_key) { + plugin_mgr.subscribe_on_unload_callback([refresh_bed_for_asset_packs](const std::string& plugin_key) { if (wxTheApp == nullptr || wxGetApp().is_closing()) return; PluginResourceTextures::instance().on_plugin_deregister(plugin_key); Slic3r::GUI::bump_texture_library_generation(); + refresh_bed_for_asset_packs(PluginPrinterAssets::instance().on_plugin_deregister(plugin_key)); }); - plugin_mgr.subscribe_on_capability_load_callback([](const PluginCapabilityId& capability) { - if (capability.type != PluginCapabilityType::ResourceTexture) - return; + plugin_mgr.subscribe_on_capability_load_callback([refresh_bed_for_asset_packs](const PluginCapabilityId& capability) { if (wxTheApp == nullptr || wxGetApp().is_closing()) return; - PluginResourceTextures::instance().on_cap_register(capability); - Slic3r::GUI::bump_texture_library_generation(); + if (capability.type == PluginCapabilityType::ResourceTexture) { + PluginResourceTextures::instance().on_cap_register(capability); + Slic3r::GUI::bump_texture_library_generation(); + } else if (capability.type == PluginCapabilityType::ResourcePrinterAsset) { + refresh_bed_for_asset_packs(PluginPrinterAssets::instance().on_cap_register(capability)); + } }); - plugin_mgr.subscribe_on_capability_unload_callback([](const PluginCapabilityId& capability) { - if (capability.type != PluginCapabilityType::ResourceTexture) - return; + plugin_mgr.subscribe_on_capability_unload_callback([refresh_bed_for_asset_packs](const PluginCapabilityId& capability) { if (wxTheApp == nullptr || wxGetApp().is_closing()) return; - PluginResourceTextures::instance().on_cap_deregister(capability); - Slic3r::GUI::bump_texture_library_generation(); + if (capability.type == PluginCapabilityType::ResourceTexture) { + PluginResourceTextures::instance().on_cap_deregister(capability); + Slic3r::GUI::bump_texture_library_generation(); + } else if (capability.type == PluginCapabilityType::ResourcePrinterAsset) { + refresh_bed_for_asset_packs(PluginPrinterAssets::instance().on_cap_deregister(capability)); + } }); // Packs already loaded before this wiring, or in tests where no callback fires. PluginResourceTextures::instance().initial_sweep(); Slic3r::GUI::bump_texture_library_generation(); + PluginPrinterAssets::instance().initial_sweep(); } bool GUI_App::on_init_inner() diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 80fb6ced1b..d0a5e4ebdc 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -92,6 +92,7 @@ #include "slic3r/GUI/Monitor.hpp" #include #include +#include #include #include #include @@ -7414,8 +7415,9 @@ struct Plater::priv void note_process_completed(bool cancelled, bool success, const std::string& error); // Missing-plugin set signatures (sorted full refs joined by '\n'), one per notification. They // gate plugin-load re-validation and avoid needlessly recreating the notification when the set - // is unchanged. Whether missing plugins block slicing is derived directly from PluginResolver - // (has_missing_plugins()), not cached here. + // is unchanged. Whether missing plugins block slicing is a different question, derived directly + // from PluginResolver (has_blocking_plugins()): only the process and filament presets block, a + // printer preset's plugins notify. Neither is cached here. std::string m_local_missing_shown_sig; std::string m_cloud_missing_shown_sig; std::string m_inactive_shown_sig; @@ -22756,6 +22758,12 @@ void Plater::set_bed_shape() const } } } + // A printer asset reference resolves to the installed pack's file; a missing pack leaves the value + // empty, so the vendor texture and model are drawn instead. PluginResolver offers to install the + // pack through the printer preset's manifest. + const std::string custom_texture = resolve_printer_asset_value(p->config->option("bed_custom_texture")->value); + const std::string custom_model = resolve_printer_asset_value(p->config->option("bed_custom_model")->value); + const ConfigOptionPoints *bed_exclude_area = p->config->option("bed_exclude_area"); set_bed_shape(p->config->option("printable_area")->values, //BBS: add bed exclude areas @@ -22764,14 +22772,17 @@ void Plater::set_bed_shape() const p->config->option("printable_height")->value, p->config->option("extruder_printable_area")->values, p->config->option("extruder_printable_height")->values, - p->config->option("bed_custom_texture")->value.empty() ? texture_filename : p->config->option("bed_custom_texture")->value, - p->config->option("bed_custom_model")->value); + custom_texture.empty() ? texture_filename : custom_texture, + custom_model); } //BBS: add bed exclude area void Plater::set_bed_shape(const Pointfs& shape, const Pointfs& exclude_area, const Pointfs& wrapping_exclude_area, const double printable_height, std::vector extruder_areas, std::vector extruder_heights, const std::string& custom_texture, const std::string& custom_model, bool force_as_custom) const { - p->set_bed_shape(make_counter_clockwise(shape), exclude_area, wrapping_exclude_area, printable_height, extruder_areas, extruder_heights, custom_texture, custom_model, force_as_custom); + // Callers such as the G-code viewer pass raw preset values, which may be printer asset references. + p->set_bed_shape(make_counter_clockwise(shape), exclude_area, wrapping_exclude_area, printable_height, extruder_areas, + extruder_heights, resolve_printer_asset_value(custom_texture), resolve_printer_asset_value(custom_model), + force_as_custom); } void Plater::force_filament_colors_update() @@ -23977,11 +23988,11 @@ void Plater::validate_current_plate(bool& model_fits, bool& validate_error) bool Plater::refresh_missing_plugin_block(bool* block_toggled) { // PluginResolver owns the per-preset-type missing sets; rebuild them from each preset's own - // "plugins" manifest so the state is always fresh. A plugin is resolved when it is + // plugin manifest so the state is always fresh. A plugin is resolved when it is // installed/loaded, or when no active setting references it any more (refresh drops it then). // The block is derived solely from PluginResolver; snapshot it before the refresh to detect a // toggle (so the caller can refresh the Slice button). - const bool was_blocked = has_missing_plugins() || has_inactive_plugins() || has_broken_plugins(); + const bool was_blocked = has_blocking_plugins(); refresh_missing_plugins(*wxGetApp().preset_bundle); const auto missing_refs = [](const std::vector& missing) { @@ -24019,8 +24030,11 @@ bool Plater::refresh_missing_plugin_block(bool* block_toggled) const std::string sig = signature(missing); if (*shown_sig != sig || !p->notification_manager->has_notification_of_type(type)) { std::vector body; - for (const auto& m : missing) - body.emplace_back(JumpTo{m.ref.capability_name, m.opt, m.opt_type}); + for (const auto& m : missing) { + // printer_asset_plugins is not on a settings page: the Bed Shape dialog edits it. + const std::string jump_opt = m.opt == "printer_asset_plugins" ? "printable_area" : m.opt; + body.emplace_back(JumpTo{m.ref.capability_name, jump_opt, m.opt_type}); + } p->notification_manager->push_plugin_missing_notification( type, header, resolve_label, std::move(body), std::move(resolve_action)); @@ -24063,7 +24077,7 @@ bool Plater::refresh_missing_plugin_block(bool* block_toggled) _u8L("Find on OrcaCloud"), [broken_refs](wxEvtHandler*) { open_missing_plugins_on_cloud(broken_refs); return false; }); - const bool blocked = has_missing_plugins() || has_inactive_plugins() || has_broken_plugins(); + const bool blocked = has_blocking_plugins(); if (block_toggled) *block_toggled = (was_blocked != blocked); return blocked; @@ -24162,8 +24176,10 @@ void Plater::enable_inactive_plugins(const std::vector& refs) bool Plater::plugins_block_slicing() const { // Single source of truth: slicing is blocked while PluginResolver still has unresolved plugin - // references — missing (download), inactive (activate), or broken (capability unavailable). - return has_missing_plugins() || has_inactive_plugins() || has_broken_plugins(); + // references — missing (download), inactive (activate), or broken (capability unavailable) — + // from the process or filament presets. Printer preset plugins (printer agents, printer assets) + // only prompt: they do not change the sliced result. + return has_blocking_plugins(); } void Plater::open_platesettings_dialog(wxCommandEvent& evt) { diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index 3ea628e0c8..5c86e47ed8 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -985,9 +985,11 @@ public: PartPlateList& get_partplate_list(); void validate_current_plate(bool& model_fits, bool& validate_error); // Rebuild the missing-plugin sets from the active presets and (re)show/close their notifications. - // Returns true when slicing must be blocked (a referenced plugin is still missing); sets - // *block_toggled when the blocked state changed since the previous call (so the caller can refresh - // the Slice button). Helper for validate_current_plate and the reslice() gate. + // Returns true when slicing must be blocked: a plugin referenced by the process or filament + // preset is missing, inactive or broken. A printer preset's plugins (printer agent, printer + // assets) only notify. Sets *block_toggled when the blocked state changed since the previous call + // (so the caller can refresh the Slice button). Helper for validate_current_plate and the reslice() + // gate. bool refresh_missing_plugin_block(bool* block_toggled = nullptr); // Re-run plate validation when a plugin finishes loading, but only while a missing-plugin // notification is active, so it clears automatically once the required plugin is available. @@ -1003,8 +1005,10 @@ public: // dialog; the loads run on a background worker that re-validates the plate once they settle, so // the notification clears (or flips to broken if the plugin lacks the capability). void enable_inactive_plugins(const std::vector& refs); - // True when the active preset references plugins that are missing and not yet acknowledged, as - // of the last validate_current_plate. Other slice-ready writers consult this to stay consistent. + // True when a plugin referenced by the active process or filament preset is missing, inactive or + // broken, as of the last refresh of the missing-plugin sets. A printer preset's plugins are + // reported but never block. Other slice-ready writers consult this to stay consistent with + // validate_current_plate's gate. bool plugins_block_slicing() const; //BBS: select the plate by index int select_plate(int plate_index, bool need_slice = false); diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 04dc5cb3b6..fd37ad86b2 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -91,6 +91,7 @@ #include "slic3r/Utils/PresetUpdater.hpp" #include "slic3r/plugin/PluginConfig.hpp" #include "slic3r/plugin/PluginManager.hpp" +#include "slic3r/plugin/host/PluginPrinterAssets.hpp" #include "Plater.hpp" #include "PartPlate.hpp" #include "ParamsDialog.hpp" @@ -2148,7 +2149,7 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) } } - // Keep this preset's "plugins" manifest in sync when a plugin picker changes, so full_config() and + // Keep this preset's plugin manifest in sync when a plugin picker changes, so full_config() and // save_to_json() always find resolved "name;uuid;capability" references and rebuild it nowhere else. // Also drop any plugin config override entries for a capability the change just stopped // referencing (e.g. a plugin removed from slicing_pipeline_plugin), so a saved preset never @@ -2773,8 +2774,18 @@ void Tab::apply_searcher() void Tab::cache_config_diff(const std::vector& selected_options, const DynamicPrintConfig* config/* = nullptr*/) { + const DynamicPrintConfig& source = config ? *config : m_presets->get_edited_preset().config; m_cache_options = selected_options; - m_cache_config.apply_only(config ? *config : m_presets->get_edited_preset().config, selected_options); + m_cache_config.apply_only(source, selected_options); + // Bed files from printer asset packs travel with their packs' manifest entries, so the target can + // name packs that are not installed here (apply_config_from_cache). + m_cache_printer_plugins.reset(); + const bool moves_bed_files = std::any_of(selected_options.begin(), selected_options.end(), [](const std::string& key) { + return key == "bed_custom_texture" || key == "bed_custom_model"; + }); + if (m_type == Preset::TYPE_PRINTER && moves_bed_files) + if (const auto* manifest = source.option("printer_plugins")) + m_cache_printer_plugins = *manifest; } void Tab::apply_config_from_cache() @@ -2786,9 +2797,14 @@ void Tab::apply_config_from_cache() was_applied = static_cast(this)->apply_extruder_cnt_from_cache(); if (!m_cache_config.empty()) { - m_presets->get_edited_preset().config.apply_only(m_cache_config, m_cache_options); + DynamicPrintConfig& edited = m_presets->get_edited_preset().config; + edited.apply_only(m_cache_config, m_cache_options); + // Name the packs the transferred bed files come from, so the notices and the saved manifest match. + if (m_cache_printer_plugins) + update_printer_asset_plugins(edited, &*m_cache_printer_plugins); m_cache_config.clear(); m_cache_options.clear(); + m_cache_printer_plugins.reset(); was_applied = true; } @@ -8834,6 +8850,11 @@ wxSizer* TabPrinter::create_bed_shape_widget(wxWindow* parent) const std::string& custom_model = dlg.get_custom_model(); if (!shape.empty()) { + // Name the printer asset packs the bed files come from before the change + // propagates, so the manifest and the missing-plugin notices see them. + m_config->set_key_value("bed_custom_texture", new ConfigOptionString(custom_texture)); + m_config->set_key_value("bed_custom_model", new ConfigOptionString(custom_model)); + update_printer_asset_plugins(*m_config); load_key_value("printable_area", shape); load_key_value("bed_custom_texture", custom_texture); load_key_value("bed_custom_model", custom_model); diff --git a/src/slic3r/GUI/Tab.hpp b/src/slic3r/GUI/Tab.hpp index d94de649d7..9f169cf99c 100644 --- a/src/slic3r/GUI/Tab.hpp +++ b/src/slic3r/GUI/Tab.hpp @@ -37,6 +37,7 @@ #include #include +#include #include #include @@ -302,6 +303,8 @@ protected: DynamicPrintConfig m_cache_config; std::vector m_cache_options; + // The source preset's manifest when cached bed files may come from printer asset packs. + std::optional m_cache_printer_plugins; bool m_page_switch_running = false; diff --git a/src/slic3r/plugin/PluginConfig.cpp b/src/slic3r/plugin/PluginConfig.cpp index e5eea8c141..bc6cc44086 100644 --- a/src/slic3r/plugin/PluginConfig.cpp +++ b/src/slic3r/plugin/PluginConfig.cpp @@ -531,6 +531,7 @@ std::string PluginConfig::capability_type_label(PluginCapabilityType type) case PluginCapabilityType::Script: return _u8L("Script"); case PluginCapabilityType::SlicingPipeline: return _u8L("Slicing Pipeline"); case PluginCapabilityType::ResourceTexture: return _u8L("Resource Texture"); + case PluginCapabilityType::ResourcePrinterAsset: return _u8L("Resource Printer Asset"); default: return _u8L("Unknown"); } } diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index d2521d5ed0..695e62579f 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -1,5 +1,6 @@ #include "PluginFsUtils.hpp" +#include "libslic3r/PrinterAssetRef.hpp" #include "libslic3r/Utils.hpp" #include "libslic3r/miniz_extension.hpp" @@ -39,6 +40,7 @@ #include #include #include +#include #include #include "slic3r/plugin/PluginDescriptor.hpp" #include @@ -1659,20 +1661,36 @@ boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::pat return {}; } -std::vector collect_resource_texture_files(const std::string& dir, - const std::string& plugin_root, - std::string& error) +namespace { + +// What a resource directory listing reports when it cannot be used. +struct ResourceDirMessages +{ + std::string not_set; + std::string not_resolved; + std::string not_directory; + std::string outside_root; + std::string unreadable; +}; + +// Validated non-recursive regular files with one of `extensions` (lowercase, with the dot) directly +// inside `dir`, every one contained in `plugin_root`, at most `max_files`. A file whose name +// `accepts_name` (when set) rejects is left out before the cap, so it cannot take a slot. +std::vector collect_contained_resource_files(const std::string& dir, + const std::string& plugin_root, + const std::vector& extensions, + size_t max_files, + bool (*accepts_name)(std::string_view), + const ResourceDirMessages& messages, + std::string& error) { namespace fs = boost::filesystem; - // Picker sanity bound, not a security control: the popup draws every entry in its grid. - constexpr size_t kMaxResourceTextureFiles = 64; - std::vector files; error.clear(); if (dir.empty()) { - error = _u8L("Resource texture directory is not set"); + error = messages.not_set; return files; } if (plugin_root.empty()) { @@ -1683,12 +1701,12 @@ std::vector collect_resource_texture_files(const std::string& dir, boost::system::error_code ec; const fs::path resolved_dir = fs::weakly_canonical(fs::path(dir), ec); if (ec) { - error = _u8L("Resource texture directory could not be resolved"); + error = messages.not_resolved; return files; } if (!fs::is_directory(resolved_dir, ec) || ec) { - error = _u8L("Resource texture path is not a directory"); + error = messages.not_directory; return files; } @@ -1699,10 +1717,11 @@ std::vector collect_resource_texture_files(const std::string& dir, } if (!is_inside_allowed_root(resolved_dir, resolved_root)) { - error = _u8L("Resource texture directory is outside the plugin folder"); + error = messages.outside_root; return files; } + std::vector candidates; 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' @@ -1710,14 +1729,18 @@ std::vector collect_resource_texture_files(const std::string& dir, const fs::path io_path = extended_path(path); boost::system::error_code file_ec; - if (!fs::is_regular_file(io_path, file_ec) || file_ec) - continue; - std::string ext = path.extension().string(); boost::algorithm::to_lower(ext); - if (ext != ".png" && ext != ".jpg" && ext != ".jpeg" && ext != ".bmp") + if (std::find(extensions.begin(), extensions.end(), ext) == extensions.end()) continue; + if (!fs::is_regular_file(io_path, file_ec) || file_ec) { + // E.g. a path past MAX_PATH on Windows, or a Windows device name such as con.png. + if (file_ec) + BOOST_LOG_TRIVIAL(warning) << "Skipping unreadable plugin resource file " << path.string() << ": " << file_ec.message(); + continue; + } + // 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. @@ -1726,19 +1749,63 @@ std::vector collect_resource_texture_files(const std::string& dir, !is_inside_allowed_root(path, resolved_root)))) continue; - files.push_back(path.string()); - if (files.size() >= kMaxResourceTextureFiles) - break; + candidates.push_back(path); } if (ec) { - error = _u8L("Resource texture directory could not be read"); + error = messages.unreadable; return {}; } + // Directory order differs between file systems (ext4 hashes it): sort, so the list and which + // files the cap keeps are the same everywhere. + std::sort(candidates.begin(), candidates.end()); + for (const fs::path& path : candidates) { + if (accepts_name != nullptr && !accepts_name(path.filename().string())) + continue; + // Re-check per file: a symlink inside the pack must not resolve outside it. + if (!is_inside_allowed_root(path, resolved_root)) + continue; + files.push_back(path.string()); + if (files.size() >= max_files) + break; + } return files; } +} // namespace + +std::vector collect_resource_texture_files(const std::string& dir, + const std::string& plugin_root, + std::string& error) +{ + // Picker sanity bound, not a security control: the popup draws every entry in its grid. + constexpr size_t kMaxResourceTextureFiles = 64; + + const ResourceDirMessages messages{_u8L("Resource texture directory is not set"), + _u8L("Resource texture directory could not be resolved"), + _u8L("Resource texture path is not a directory"), + _u8L("Resource texture directory is outside the plugin folder"), + _u8L("Resource texture directory could not be read")}; + return collect_contained_resource_files(dir, plugin_root, {".png", ".jpg", ".jpeg", ".bmp"}, kMaxResourceTextureFiles, + nullptr, messages, error); +} + +std::vector collect_printer_asset_files(const std::string& dir, const std::string& plugin_root, std::string& error) +{ + // Menu sanity bound: the Bed Shape dialog lists every file of every pack. + constexpr size_t kMaxPrinterAssetFiles = 16; + + const ResourceDirMessages messages{_u8L("Printer asset directory is not set"), + _u8L("Printer asset directory could not be resolved"), + _u8L("Printer asset path is not a directory"), + _u8L("Printer asset directory is outside the plugin folder"), + _u8L("Printer asset directory could not be read")}; + // A name a reference cannot hold is not offered by the Bed Shape dialog, so it must not take a slot. + return collect_contained_resource_files(dir, plugin_root, {".stl", ".png", ".svg"}, kMaxPrinterAssetFiles, + &is_printer_asset_file_name, messages, error); +} + } // namespace Slic3r // ── uv wheel installation ───────────────────────────────────────────── diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index cbe505859b..643e4fa46a 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -162,6 +162,10 @@ std::vector collect_resource_texture_files(const std::string& dir, const std::string& plugin_root, std::string& error); +// Validated non-recursive .stl/.png/.svg files directly inside `dir` (a printer asset pack's asset folder), every +// one contained in `plugin_root`, at most 16. Empty with `error` set on failure. +std::vector collect_printer_asset_files(const std::string& dir, const std::string& plugin_root, std::string& error); + // Process-wide mutex serializing every in-process read and read-modify-write of a plugin's // .install_state.json sidecar. Hold it across the read and the matching write so two writers // cannot overwrite each other's grants, and around standalone reads so a reader cannot observe a diff --git a/src/slic3r/plugin/PluginHooks.cpp b/src/slic3r/plugin/PluginHooks.cpp index 347687a20b..aa713fc051 100644 --- a/src/slic3r/plugin/PluginHooks.cpp +++ b/src/slic3r/plugin/PluginHooks.cpp @@ -4,11 +4,13 @@ #include "PluginResolver.hpp" #include "PythonInterpreter.hpp" #include "PythonPluginInterface.hpp" +#include "host/PluginPrinterAssets.hpp" #include "pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/Exception.hpp" #include "libslic3r/LifecycleEvents.hpp" +#include "libslic3r/Preset.hpp" #include "libslic3r/Print.hpp" #include "libslic3r_version.h" #include "slic3r/GUI/I18N.hpp" @@ -125,11 +127,23 @@ void install_slicing_pipeline_hook() }); } +// Every printer preset save names the asset packs its bed files come from, whichever dialog saves +// it: the bed files may have changed through a transfer, or been reverted by an unticked row. The +// saved preset's manifest names packs that are not loaded here. +void install_printer_asset_save_hook() +{ + PresetCollection::set_before_save_fn([](Preset::Type type, DynamicPrintConfig& config, const DynamicPrintConfig& selected) { + if (type == Preset::TYPE_PRINTER) + update_printer_asset_plugins(config, selected.option("printer_plugins")); + }); +} + } // namespace void install() { install_capability_resolver(); + install_printer_asset_save_hook(); install_slicing_pipeline_hook(); install_lifecycle_event_hook(); } @@ -137,6 +151,7 @@ void install() void uninstall() { ConfigBase::set_resolve_capability_fn(nullptr); + PresetCollection::set_before_save_fn(nullptr); Print::set_slicing_pipeline_hook_fn(nullptr); set_lifecycle_hook_fn(nullptr); } diff --git a/src/slic3r/plugin/PluginLoader.cpp b/src/slic3r/plugin/PluginLoader.cpp index 8dbf743687..d7450341d8 100644 --- a/src/slic3r/plugin/PluginLoader.cpp +++ b/src/slic3r/plugin/PluginLoader.cpp @@ -10,6 +10,7 @@ #include "PythonInterpreter.hpp" #include "PythonPluginBridge.hpp" #include "pluginTypes/resourceTexture/ResourceTexturePluginCapability.hpp" +#include "pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.hpp" #include "libslic3r/Utils.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/format.hpp" @@ -490,6 +491,32 @@ bool load(const PluginDescriptor& descriptor, } } + // ResourcePrinterAsset capabilities resolve their asset folder the same way: validated once + // here, and a fault only costs the pack its files. + if (auto* printer_bed = dynamic_cast(instance.get())) { + try { + const std::string bed_dir = printer_bed->get_asset_dir(); + std::string bed_error; + if (!bed_dir.empty()) + collect_printer_asset_files(bed_dir, descriptor.plugin_root, bed_error); + if (bed_dir.empty() || !bed_error.empty()) { + if (!bed_error.empty()) + BOOST_LOG_TRIVIAL(warning) + << "Plugin capability '" << found.name << "' of plugin '" << descriptor.plugin_key + << "': asset directory rejected (" << bed_error + << "); the capability will provide no printer assets"; + printer_bed->set_asset_dir({}); + } else { + printer_bed->set_asset_dir(bed_dir); + } + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(warning) + << "Plugin capability '" << found.name << "' of plugin '" << descriptor.plugin_key + << "': get_asset_dir() failed (" << ex.what() << "); the capability will provide no printer assets"; + printer_bed->set_asset_dir({}); + } + } + capabilities.push_back(std::move(instance)); } } catch (const std::exception& ex) { diff --git a/src/slic3r/plugin/PluginResolver.cpp b/src/slic3r/plugin/PluginResolver.cpp index 0adf430e84..8638a1c915 100644 --- a/src/slic3r/plugin/PluginResolver.cpp +++ b/src/slic3r/plugin/PluginResolver.cpp @@ -21,6 +21,7 @@ #include "slic3r/plugin/PythonPluginInterface.hpp" #include #include +#include #include #include @@ -114,7 +115,7 @@ std::vector referenced_capabilities(Preset::Type type, cons if (!is_tracked_type(type)) return {}; - const auto* manifest = dynamic_cast(preset.config.option("plugins")); + const auto* manifest = dynamic_cast(preset.config.option(preset.config.plugin_manifest_key())); if (manifest == nullptr) return {}; @@ -201,6 +202,9 @@ std::vector capabilities_in_use(Preset::Type type, const Pre static std::string resolve_cloud_base_url() { std::string cloud_base_url = "https://cloud.orcaslicer.com"; + // Without the app (unit tests, headless callers) there is no agent to ask: keep the default. + if (wxTheApp == nullptr) + return cloud_base_url; if (auto agent = GUI::wxGetApp().getAgent()) { if (auto orca_agent = std::dynamic_pointer_cast(agent->get_cloud_agent())) { if (!orca_agent->get_cloud_base_url().empty()) @@ -237,7 +241,9 @@ static std::pair loaded_capability_state(const std::string& plugin_k void refresh_missing_plugins(const PresetBundle& preset_bundle) { - const auto manifest_of = [](const Preset& preset) { return dynamic_cast(preset.config.option("plugins")); }; + const auto manifest_of = [](const Preset& preset) { + return dynamic_cast(preset.config.option(preset.config.plugin_manifest_key())); + }; const Preset& print_preset = preset_bundle.prints.get_edited_preset(); refresh_missing_plugins(Preset::TYPE_PRINT, manifest_of(print_preset), &print_preset); const Preset& printer_preset = preset_bundle.printers.get_edited_preset(); @@ -379,6 +385,16 @@ bool has_broken_plugins() return false; } +bool has_blocking_plugins() +{ + std::lock_guard lock(s_missing_mutex); + for (const auto* sets : {&s_missing, &s_inactive, &s_broken}) + for (const auto& [type, set] : *sets) + if (type != Preset::TYPE_PRINTER && !set.empty()) + return true; + return false; +} + static void report_install_failure(const std::string& message) { GUI::wxGetApp().CallAfter([message]() { diff --git a/src/slic3r/plugin/PluginResolver.hpp b/src/slic3r/plugin/PluginResolver.hpp index 2f856a7599..552c86cb52 100644 --- a/src/slic3r/plugin/PluginResolver.hpp +++ b/src/slic3r/plugin/PluginResolver.hpp @@ -23,7 +23,7 @@ struct MissingPlugin PluginCapabilityType type{PluginCapabilityType::Unknown}; }; -// Rebuild one preset type's missing-plugin set from its "plugins" manifest, comparing each ref +// Rebuild one preset type's missing-plugin set from its plugin manifest, comparing each ref // against the live catalog and loaded/enabled capabilities. A null/empty manifest clears the set. // Only TYPE_PRINT, TYPE_PRINTER and TYPE_FILAMENT are tracked. void refresh_missing_plugins(Preset::Type type, const ConfigOptionStrings* manifest, const Preset* preset = nullptr); @@ -45,6 +45,11 @@ bool has_inactive_plugins(); std::vector get_broken_plugins(); bool has_broken_plugins(); +// True while a missing, inactive or broken reference comes from the process or filament presets. +// Printer preset plugins (printer agents, printer assets) are reported but never block slicing: +// they do not change the sliced result. +bool has_blocking_plugins(); + // Optional progress hook for the cloud install worker. All three callbacks fire on the worker // thread; implementations must only touch thread-safe state or marshal to the UI thread. struct PluginInstallProgress @@ -73,7 +78,7 @@ void open_missing_plugins_on_cloud(const std::vector& local_refs); std::string create_full_ref(const PluginCapabilityRef& ref); std::string resolve_recovery_url(const PluginCapabilityRef& ref); -// The capabilities `preset`'s "plugins" manifest declares AND that one of its plugin-backed options +// The capabilities `preset`'s plugin manifest declares AND that one of its plugin-backed options // (ConfigOptionDef::is_plugin_backed) currently references: a manifest entry nobody points at is not // in use. Pure preset logic — the catalog and loader are not consulted. Empty for untracked types. std::vector referenced_capabilities(Preset::Type type, const Preset& preset); diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index 011dd1639a..218e18b9f8 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -33,6 +33,7 @@ #include "pluginTypes/printerAgent/PrinterAgentPluginCapability.hpp" #include "pluginTypes/pages/PagesPluginCapability.hpp" #include "pluginTypes/resourceTexture/ResourceTexturePluginCapability.hpp" +#include "pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.hpp" #include "pluginTypes/script/ScriptPluginCapability.hpp" #include "pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.hpp" #include @@ -410,6 +411,7 @@ void bind_python_api(pybind11::module_& m) .value("Script", PluginCapabilityType::Script) .value("SlicingPipeline", PluginCapabilityType::SlicingPipeline) .value("ResourceTexture", PluginCapabilityType::ResourceTexture) + .value("ResourcePrinterAsset", PluginCapabilityType::ResourcePrinterAsset) .value("Unknown", PluginCapabilityType::Unknown) .export_values(); @@ -672,6 +674,7 @@ void bind_python_api(pybind11::module_& m) ScriptPluginCapability::RegisterBindings(m); SlicingPipelinePluginCapability::RegisterBindings(m); ResourceTexturePluginCapability::RegisterBindings(m); + ResourcePrinterAssetPluginCapability::RegisterBindings(m); PluginHost::RegisterBindings(m); BOOST_LOG_TRIVIAL(debug) << "Registered ScriptPluginCapability Python bindings"; diff --git a/src/slic3r/plugin/PythonPluginInterface.hpp b/src/slic3r/plugin/PythonPluginInterface.hpp index 6d31748e98..887ce99dad 100644 --- a/src/slic3r/plugin/PythonPluginInterface.hpp +++ b/src/slic3r/plugin/PythonPluginInterface.hpp @@ -13,7 +13,7 @@ namespace Slic3r { -enum class PluginCapabilityType { PrinterConnection = 0, Pages, Analysis, Importer, Exporter, Visualization, Script, SlicingPipeline, ResourceTexture, Unknown }; +enum class PluginCapabilityType { PrinterConnection = 0, Pages, Analysis, Importer, Exporter, Visualization, Script, SlicingPipeline, ResourceTexture, ResourcePrinterAsset, Unknown }; struct PluginCapabilityId { @@ -48,6 +48,7 @@ inline std::string plugin_capability_type_to_string(PluginCapabilityType type) case PluginCapabilityType::Script: return "script"; case PluginCapabilityType::SlicingPipeline: return "slicing-pipeline"; case PluginCapabilityType::ResourceTexture: return "resource-texture"; + case PluginCapabilityType::ResourcePrinterAsset: return "resource-printer-asset"; default: return "unknown"; } } @@ -64,6 +65,7 @@ inline std::string plugin_capability_type_display_name(PluginCapabilityType type case PluginCapabilityType::Script: return "Script"; case PluginCapabilityType::SlicingPipeline: return "Slicing Pipeline"; case PluginCapabilityType::ResourceTexture: return "Resource Texture"; + case PluginCapabilityType::ResourcePrinterAsset: return "Resource Printer Asset"; default: return "Unknown"; } } @@ -95,6 +97,8 @@ inline PluginCapabilityType plugin_capability_type_from_string(std::string_view return PluginCapabilityType::SlicingPipeline; if (lowered == "resource-texture") return PluginCapabilityType::ResourceTexture; + if (lowered == "resource-printer-asset") + return PluginCapabilityType::ResourcePrinterAsset; return PluginCapabilityType::Unknown; } diff --git a/src/slic3r/plugin/host/PluginPrinterAssets.cpp b/src/slic3r/plugin/host/PluginPrinterAssets.cpp new file mode 100644 index 0000000000..11b9b3b779 --- /dev/null +++ b/src/slic3r/plugin/host/PluginPrinterAssets.cpp @@ -0,0 +1,303 @@ +#include "PluginPrinterAssets.hpp" + +#include "libslic3r/Config.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/PrinterAssetRef.hpp" +#include "slic3r/plugin/PluginDescriptor.hpp" +#include "slic3r/plugin/PluginFsUtils.hpp" +#include "slic3r/plugin/PluginManager.hpp" +#include "slic3r/plugin/PythonPluginInterface.hpp" +#include "slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { + +PluginPrinterAssets &PluginPrinterAssets::instance() +{ + static PluginPrinterAssets registry; + return registry; +} + +std::optional PluginPrinterAssets::build_entry(const PluginCapabilityId &id) const +{ + // Query by id and re-check state; the manager copies the shared_ptr and releases its lock. + auto capability = PluginManager::instance().get_plugin_capability(id, /*only_enabled=*/false); + if (!capability || !capability->is_enabled() || capability->type() != PluginCapabilityType::ResourcePrinterAsset) + return std::nullopt; + + auto asset_capability = std::dynamic_pointer_cast(capability); + if (!asset_capability) + return std::nullopt; + + // An empty directory means resolution failed at load, so the pack contributes nothing. + const std::string &asset_dir = asset_capability->asset_dir(); + if (asset_dir.empty()) + return std::nullopt; + + PluginDescriptor descriptor; + if (!PluginManager::instance().try_get_plugin_descriptor_for_capability(capability->name(), PluginCapabilityType::ResourcePrinterAsset, + descriptor)) + return std::nullopt; + + PrinterAssetPackEntry entry; + entry.id = capability->identity(); + entry.plugin_key = entry.id.plugin_key; + entry.display_name = capability->name(); + entry.asset_dir = asset_dir; + entry.plugin_root = descriptor.plugin_root; + // References name cloud packs by their uuid, the same on every machine. Packs installed by hand + // fall back to their plugin key, which only this machine knows. + entry.pack_id = descriptor.cloud_uuid().empty() ? descriptor.plugin_key : boost::algorithm::to_lower_copy(descriptor.cloud_uuid()); + + std::string error; + entry.files = collect_printer_asset_files(asset_dir, entry.plugin_root, error); + if (!error.empty()) + return std::nullopt; + return entry; +} + +bool PluginPrinterAssets::on_plugin_register(const std::string &plugin_key) +{ + bool changed = false; + for (const auto &capability : PluginManager::instance().get_plugin_capabilities(plugin_key, PluginCapabilityType::ResourcePrinterAsset)) { + if (capability && on_cap_register(capability->identity())) + changed = true; + } + return changed; +} + +bool PluginPrinterAssets::on_plugin_deregister(const std::string &plugin_key) +{ + std::lock_guard lock(m_mutex); + bool changed = false; + for (auto it = m_entries.begin(); it != m_entries.end();) { + if (it->first.plugin_key == plugin_key) { + it = m_entries.erase(it); + changed = true; + } else { + ++it; + } + } + return changed; +} + +bool PluginPrinterAssets::on_cap_register(const PluginCapabilityId &id) +{ + std::optional entry = build_entry(id); + + std::lock_guard lock(m_mutex); + if (!entry) + return m_entries.erase(id) > 0; + // A re-enable rebuilds the same entry; the bed only redraws when something it shows changed. + auto existing = m_entries.find(entry->id); + const bool changed = existing == m_entries.end() || existing->second.pack_id != entry->pack_id || + existing->second.display_name != entry->display_name || + existing->second.asset_dir != entry->asset_dir || existing->second.files != entry->files; + m_entries[entry->id] = std::move(*entry); + return changed; +} + +bool PluginPrinterAssets::on_cap_deregister(const PluginCapabilityId &id) +{ + std::lock_guard lock(m_mutex); + return m_entries.erase(id) > 0; +} + +void PluginPrinterAssets::initial_sweep() +{ + std::map entries; + for (const auto &capability : PluginManager::instance().get_plugin_capabilities("", PluginCapabilityType::ResourcePrinterAsset)) { + if (!capability) + continue; + // This runs from GUI_App::on_init, outside the loader's and the manager's guards: a throw here + // would abort startup, so a fault only costs the pack its files. + try { + std::optional entry = build_entry(capability->identity()); + if (entry) + entries[entry->id] = std::move(*entry); + } catch (const std::exception &ex) { + BOOST_LOG_TRIVIAL(warning) << "Printer asset pack '" << capability->identity().plugin_key << "/" + << capability->identity().name << "' could not be listed: " << ex.what(); + } catch (...) { + BOOST_LOG_TRIVIAL(warning) << "Printer asset pack of plugin '" << capability->identity().plugin_key + << "' could not be listed"; + } + } + + std::lock_guard lock(m_mutex); + m_entries = std::move(entries); +} + +std::vector PluginPrinterAssets::entries() const +{ + std::lock_guard lock(m_mutex); + + std::vector result; + result.reserve(m_entries.size()); + for (const auto &entry : m_entries) + result.push_back(entry.second); + return result; +} + +// The file of `entry` that `ref` names, or empty when `entry` is another pack or lacks the file. `pack_id` is +// the reference's plugin id in lower case. Matched against the validated listing by name, so a reference can +// never leave the pack. +static std::string pack_file(const PrinterAssetPackEntry &entry, const std::string &pack_id, const PrinterAssetRef &ref) +{ + if (entry.pack_id != pack_id && entry.plugin_key != ref.plugin_id) + return {}; + for (const std::string &file : entry.files) + if (boost::filesystem::path(file).filename().string() == ref.filename) + return file; + return {}; +} + +std::string PluginPrinterAssets::resolve(const PrinterAssetRef &ref) const +{ + const std::string pack_id = boost::algorithm::to_lower_copy(ref.plugin_id); + + std::lock_guard lock(m_mutex); + for (const auto &[id, entry] : m_entries) + if (std::string file = pack_file(entry, pack_id, ref); !file.empty()) + return file; + return {}; +} + +std::string PluginPrinterAssets::capability_name(const PrinterAssetRef &ref) const +{ + const std::string pack_id = boost::algorithm::to_lower_copy(ref.plugin_id); + + std::lock_guard lock(m_mutex); + for (const auto &[id, entry] : m_entries) + if (!pack_file(entry, pack_id, ref).empty()) + return entry.display_name; + return {}; +} + +std::string resolve_printer_asset_value(const std::string &value) +{ + const std::optional ref = parse_printer_asset_ref(value); + return ref ? PluginPrinterAssets::instance().resolve(*ref) : value; +} + +// The name of the ResourcePrinterAsset capability an installed plugin provides for `ref`, enabled or +// not, or empty when the plugin is not installed here or provides none (or several). +static std::string installed_capability_name(const PrinterAssetRef &ref) +{ + PluginManager &manager = PluginManager::instance(); + PluginDescriptor descriptor; + if (!manager.try_get_plugin_descriptor(ref.plugin_id, descriptor)) + return {}; + const auto capabilities = manager.get_plugin_capabilities(descriptor.plugin_key, PluginCapabilityType::ResourcePrinterAsset, + /*only_enabled=*/false); + return capabilities.size() == 1 ? capabilities.front()->name() : std::string(); +} + +// The plugin a manifest entry names: its uuid for a cloud plugin, else its key (the first field). +static const std::string &manifest_plugin_id(const PluginCapabilityRef &entry) +{ + return entry.uuid.empty() ? entry.name : entry.uuid; +} + +// The capability name a manifest entry holds for the pack `ref` names, matched by uuid for a cloud +// pack and by plugin key (the first field) for a local one. Entries carry no type, so a name the +// config already lists as an asset pack wins over another capability of the same plugin. +static std::string manifest_capability_name(const std::vector &manifests, const PrinterAssetRef &ref, + const std::vector &known_names) +{ + std::string first_match; + for (const ConfigOptionStrings *manifest : manifests) { + if (manifest == nullptr) + continue; + for (const std::string &entry : manifest->values) { + const std::optional parsed = parse_capability_ref(entry); + if (!parsed || !boost::algorithm::iequals(manifest_plugin_id(*parsed), ref.plugin_id)) + continue; + if (std::find(known_names.begin(), known_names.end(), parsed->capability_name) != known_names.end()) + return parsed->capability_name; + if (first_match.empty()) + first_match = parsed->capability_name; + } + } + return first_match; +} + +void update_printer_asset_plugins(DynamicPrintConfig &config, const ConfigOptionStrings *fallback_manifest) +{ + auto *names_option = config.option("printer_asset_plugins"); + if (names_option == nullptr) + return; + + const std::vector manifests{config.option("printer_plugins"), fallback_manifest}; + std::vector names; + std::vector pack_ids; + for (const char *key : {"bed_custom_texture", "bed_custom_model"}) { + const auto *value = config.option(key); + const std::optional ref = value != nullptr ? parse_printer_asset_ref(value->value) : std::nullopt; + if (!ref) + continue; + pack_ids.push_back(ref->plugin_id); + std::string name = PluginPrinterAssets::instance().capability_name(*ref); + if (name.empty()) + name = installed_capability_name(*ref); + if (name.empty()) + name = manifest_capability_name(manifests, *ref, names_option->values); + if (!name.empty() && std::find(names.begin(), names.end(), name) == names.end()) + names.push_back(std::move(name)); + } + + const auto is_for_these_packs = [&pack_ids](const std::optional &parsed) { + return parsed && std::any_of(pack_ids.begin(), pack_ids.end(), [&parsed](const std::string &id) { + return boost::algorithm::iequals(manifest_plugin_id(*parsed), id); + }); + }; + + // Take over the fallback's entries for these bed files' packs only, so the rebuild below can reuse + // them for packs that are not installed here (and nothing else leaks in without a resolver). + auto *manifest = config.option("printer_plugins", true); + if (fallback_manifest != nullptr) + for (const std::string &entry : fallback_manifest->values) { + const std::optional parsed = parse_capability_ref(entry); + if (is_for_these_packs(parsed) && std::find(manifest->values.begin(), manifest->values.end(), entry) == manifest->values.end()) + manifest->values.push_back(entry); + } + + // The entries these packs already have. The resolver finds a capability by name alone, so a loaded pack + // of another plugin with the same capability name would answer for a pack that is not loaded here. + std::vector> own_entries; + for (const std::string &entry : manifest->values) + if (std::optional parsed = parse_capability_ref(entry); is_for_these_packs(parsed)) + own_entries.emplace_back(entry, std::move(*parsed)); + + names_option->values = std::move(names); + config.update_plugin_manifest(); + + for (const auto &[entry, own] : own_entries) + for (std::string &value : manifest->values) { + const std::optional other = parse_capability_ref(value); + if (other && other->capability_name == own.capability_name && + !boost::algorithm::iequals(manifest_plugin_id(*other), manifest_plugin_id(own))) + value = entry; + } + std::vector unique; + for (std::string &value : manifest->values) + if (std::find(unique.begin(), unique.end(), value) == unique.end()) + unique.push_back(std::move(value)); + manifest->values = std::move(unique); +} + +} // namespace Slic3r diff --git a/src/slic3r/plugin/host/PluginPrinterAssets.hpp b/src/slic3r/plugin/host/PluginPrinterAssets.hpp new file mode 100644 index 0000000000..d62f21ab74 --- /dev/null +++ b/src/slic3r/plugin/host/PluginPrinterAssets.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Slic3r { + +// One loaded and enabled ResourcePrinterAsset capability (a printer asset pack) and its files. +struct PrinterAssetPackEntry +{ + PluginCapabilityId id; + std::string plugin_key; + std::string pack_id; // in a reference: the cloud uuid, else the plugin key + std::string display_name; // the capability name, e.g. "Voron Bed by sam" + std::string asset_dir; + std::string plugin_root; + std::vector files; // validated absolute paths, at most 16 +}; + +// Tracks every loaded and enabled ResourcePrinterAsset capability by id and resolves printer asset references. +// Holds strings only: a shared_ptr here would keep a Python object alive past Py_Finalize. +class PluginPrinterAssets +{ +public: + static PluginPrinterAssets &instance(); + + PluginPrinterAssets(const PluginPrinterAssets &) = delete; + PluginPrinterAssets &operator=(const PluginPrinterAssets &) = delete; + + // Each returns true when the bed may need a redraw, so callers redraw only then. A rebuild that + // produced the same entry reports no change. + bool on_plugin_register(const std::string &plugin_key); + bool on_plugin_deregister(const std::string &plugin_key); + bool on_cap_register(const PluginCapabilityId &id); + bool on_cap_deregister(const PluginCapabilityId &id); + void initial_sweep(); + + std::vector entries() const; + + // The installed file `ref` names, or empty when its pack is not loaded or lacks the file. + std::string resolve(const PrinterAssetRef &ref) const; + // The capability name of the loaded pack whose listing holds the file `ref` names, or empty when the + // pack is not loaded or lacks the file. + std::string capability_name(const PrinterAssetRef &ref) const; + +private: + PluginPrinterAssets() = default; + + std::optional build_entry(const PluginCapabilityId &id) const; + + mutable std::mutex m_mutex; + std::map m_entries; +}; + +// Resolves a bed_custom_model / bed_custom_texture value. A printer asset reference becomes the +// pack's installed file, or empty when the pack is not loaded here. Any other value (a path, or +// empty) is returned unchanged. +std::string resolve_printer_asset_value(const std::string &value); + +// Points a printer config's printer_asset_plugins at the packs its bed_custom_model and +// bed_custom_texture come from, and rebuilds its manifest, so a machine without those packs is offered +// them. A pack that is not installed here keeps the name its manifest entry holds, in the config's own +// manifest or in `fallback_manifest` (e.g. the saved preset's). Does nothing for a config without +// printer_asset_plugins. +void update_printer_asset_plugins(DynamicPrintConfig &config, const ConfigOptionStrings *fallback_manifest = nullptr); + +} // namespace Slic3r diff --git a/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.cpp b/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.cpp new file mode 100644 index 0000000000..20e27ed327 --- /dev/null +++ b/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.cpp @@ -0,0 +1,38 @@ +#include "ResourcePrinterAssetPluginCapability.hpp" +#include "ResourcePrinterAssetPluginCapabilityTrampoline.hpp" + +#include +#include + +#include + +#include +#include +#include + +namespace py = pybind11; + +namespace Slic3r { + +void ResourcePrinterAssetPluginCapability::RegisterBindings(pybind11::module_& module) +{ + BOOST_LOG_TRIVIAL(debug) << "Registering orca.resource_printer_asset bindings"; + + auto printer_asset = module.def_submodule("resource_printer_asset", "Plugin resource printer asset API"); + + py::class_>( + printer_asset, "ResourcePrinterAssetPluginCapabilityBase", + "Base for a resource printer asset capability: a pack of bed models (.stl) and bed textures (.png, .svg)\n" + "offered in the Bed Shape dialog. A printer preset refers to a file of the pack as\n" + "orcacloud-asset//, and every machine resolves that to its own installed copy.") + .def(py::init<>()) + .def("get_type", &ResourcePrinterAssetPluginCapability::get_type, "Return PluginType.ResourcePrinterAsset.") + .def("get_asset_dir", &ResourcePrinterAssetPluginCapability::get_asset_dir, + "Required. Return the path of the folder holding the pack's files. Called once when the plugin\n" + "loads. The folder must be inside the plugin's own folder; its .stl, .png and .svg files are used,\n" + "without subfolders and at most 16 of them, and a name a reference cannot hold is left out. An\n" + "empty string, a folder that fails these checks or a raised exception leaves the pack without files."); +} + +} // namespace Slic3r diff --git a/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.hpp b/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.hpp new file mode 100644 index 0000000000..c9411b42e5 --- /dev/null +++ b/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapability.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "../../PythonPluginInterface.hpp" +#include "pybind11/pybind11.h" + +#include +#include + +namespace Slic3r { +// A printer asset pack: bed models (.stl) and bed textures (.png/.svg) that printer presets pick in the Bed +// Shape dialog and refer to as "orcacloud-asset//" (libslic3r/PrinterAssetRef.hpp). +class ResourcePrinterAssetPluginCapability : public PluginCapabilityInterface +{ +public: + static void RegisterBindings(pybind11::module_& module); + + PluginCapabilityType get_type() const override { return PluginCapabilityType::ResourcePrinterAsset; } + + // Python contract: the directory holding the pack's bed files. Resolved once at materialization + // under the GIL; never called from the GUI. Overridden in Python through the trampoline. + virtual std::string get_asset_dir() const = 0; + + // C++-only read of the validated directory cached by the loader; empty if resolution failed. + const std::string& asset_dir() const { return m_asset_dir; } + void set_asset_dir(std::string dir) { m_asset_dir = std::move(dir); } + +private: + std::string m_asset_dir; +}; +} // namespace Slic3r diff --git a/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapabilityTrampoline.hpp b/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapabilityTrampoline.hpp new file mode 100644 index 0000000000..da91e28eab --- /dev/null +++ b/src/slic3r/plugin/pluginTypes/resourcePrinterAsset/ResourcePrinterAssetPluginCapabilityTrampoline.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include "ResourcePrinterAssetPluginCapability.hpp" +#include "../../PyPluginTrampoline.hpp" +#include +#include + +#include +#include "slic3r/plugin/PythonPluginInterface.hpp" + +namespace Slic3r { + +class PyResourcePrinterAssetPluginCapabilityTrampoline : public PyPluginCommonTrampoline +{ +public: + using PyPluginCommonTrampoline::PyPluginCommonTrampoline; + + std::string get_asset_dir() const override + { + ORCA_PY_OVERRIDE_AUDITED( + [] {}, + PYBIND11_OVERRIDE_PURE, + std::string, + ResourcePrinterAssetPluginCapability, + get_asset_dir); + } +}; + +} // namespace Slic3r diff --git a/tests/fff_print/test_gcode.cpp b/tests/fff_print/test_gcode.cpp index f03ad92dc3..4b4cbf9b0e 100644 --- a/tests/fff_print/test_gcode.cpp +++ b/tests/fff_print/test_gcode.cpp @@ -721,6 +721,50 @@ TEST_CASE("An exported G-code's settings load back as the settings it was sliced CHECK(bundle.project_config.option>("prime_volume_mode")->value == mode); } +TEST_CASE("A printer with no asset packs writes no plugin keys to the config block", "[GCode]") +{ + DynamicPrintConfig config = Test::multifilament_config(1); + // Both keys are present with their default empty list, as on a printer preset that uses no pack. + REQUIRE(config.option("printer_asset_plugins", true)->values.empty()); + REQUIRE(config.option("printer_plugins", true)->values.empty()); + + const std::string gcode = Test::slice({Test::cube(20.)}, config); + REQUIRE(gcode.find("; CONFIG_BLOCK_START") != std::string::npos); + CHECK(gcode.find("; printer_asset_plugins =") == std::string::npos); + CHECK(gcode.find("; printer_plugins =") == std::string::npos); +} + +TEST_CASE("A printer's asset packs and plugin manifest survive the config block round trip", "[GCode]") +{ + DynamicPrintConfig config = Test::multifilament_config(1); + config.option("printer_asset_plugins", true)->values = {"PEI Plate"}; + config.option("printer_plugins", true)->values = + {"PackA;11111111-2222-3333-4444-555555555555;PEI Plate"}; + + const std::string gcode = Test::slice({Test::cube(20.)}, config); + // The selectable bed files refer to the pack by id, so the pack names have to travel with them. + CHECK(gcode.find("; printer_asset_plugins = " + config.opt_serialize("printer_asset_plugins")) != std::string::npos); + CHECK(gcode.find("; printer_plugins = " + config.opt_serialize("printer_plugins")) != std::string::npos); + + ScopedTemporaryFile file(".gcode"); + { + std::ofstream os(file.string(), std::ios::binary); + os << gcode; + REQUIRE(os.good()); + } + + PresetBundle bundle; + ConfigSubstitutions substitutions; + bundle.load_config_model(file.string(), bundle.config_from_gcode(file.string(), ForwardCompatibilitySubstitutionRule::Enable, substitutions)); + + const DynamicPrintConfig &printer = bundle.printers.get_edited_preset().config; + REQUIRE(printer.option("printer_asset_plugins") != nullptr); + CHECK(printer.option("printer_asset_plugins")->values == std::vector{"PEI Plate"}); + REQUIRE(printer.option("printer_plugins") != nullptr); + CHECK(printer.option("printer_plugins")->values == + std::vector{"PackA;11111111-2222-3333-4444-555555555555;PEI Plate"}); +} + TEST_CASE("Z hop follows the lift settings of the filament printing", "[GCode]") { // One nozzle, two filaments. Filament 2 overrides one lift setting; filament 1 keeps the printer's default, diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 190a51f87b..12a57a7996 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -41,6 +41,7 @@ add_executable(${_TEST_NAME}_tests test_parallel_resolve.cpp test_preset_bundle_loading.cpp test_preset_collection.cpp + test_printer_asset_ref.cpp test_preset_setting_id.cpp test_preset_diff.cpp test_publish_settings.cpp diff --git a/tests/libslic3r/test_config.cpp b/tests/libslic3r/test_config.cpp index 9286e6cffa..27f93d060c 100644 --- a/tests/libslic3r/test_config.cpp +++ b/tests/libslic3r/test_config.cpp @@ -11,6 +11,7 @@ #include "libslic3r/Point.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/PrintConfigConstants.hpp" +#include "libslic3r/Preset.hpp" #include "libslic3r/LocalesUtils.hpp" #include "test_utils.hpp" @@ -906,6 +907,46 @@ TEST_CASE_METHOD(PluginResolverFixture, CHECK(manifest == std::vector{"x;;slicing-pipeline"}); } +TEST_CASE_METHOD(PluginResolverFixture, + "a printer preset config keeps its manifest in printer_plugins", + "[Config][plugins]") { + // The full print config applies the printer preset after the process preset, so a printer manifest + // stored in "plugins" would replace the process preset's. + std::unique_ptr printer(DynamicPrintConfig::new_from_defaults_keys( + {"printer_agent", "printer_plugins"})); + printer->option("printer_agent", true)->value = "agent"; + + printer->update_plugin_manifest(); + CHECK(printer->option("plugins") == nullptr); + CHECK(printer->option("printer_plugins")->values == std::vector{"agent;;printer-connection"}); + + // A full config holds both keys and keeps the combined manifest in "plugins". + std::unique_ptr full(DynamicPrintConfig::new_from_defaults_keys( + {"printer_agent", "printer_plugins", "plugins"})); + full->option("printer_agent", true)->value = "agent"; + full->update_plugin_manifest(); + CHECK(full->option("plugins")->values == std::vector{"agent;;printer-connection"}); + CHECK(full->option("printer_plugins")->values.empty()); +} + +TEST_CASE("update_plugin_manifest keeps the entry of a capability that is not loaded here", "[Config][plugins]") { + // Saving a preset on a machine that lacks one of its plugins must not drop that plugin from the + // manifest other machines read. + ConfigBase::set_resolve_capability_fn([](const std::string& name, const std::string& type) { + return name == "offline" || name == "gone" ? std::string() : name + ";;" + type; + }); + std::unique_ptr config(DynamicPrintConfig::new_from_defaults_keys( + {"slicing_pipeline_plugin", "plugins"})); + config->option("slicing_pipeline_plugin", true)->values = {"offline", "here", "gone"}; + config->option("plugins", true)->values = {"Pack;3f2a6c1e;offline", "Other;9b1d;stale"}; + + config->update_plugin_manifest(); + ConfigBase::set_resolve_capability_fn(nullptr); + // "gone" resolves nowhere and has no previous entry; the stale entry nobody references is dropped. + CHECK(config->option("plugins")->values == + std::vector{"Pack;3f2a6c1e;offline", "here;;slicing-pipeline"}); +} + TEST_CASE("unresolved_plugin_capabilities reports exactly the values the manifest drops", "[Config][plugins]") { // GUI save entry points use this query to warn before a preset loses a plugin reference, so it // must match the serializer's notion of "unresolved" -- same options, same resolver calls. @@ -941,6 +982,78 @@ TEST_CASE("unresolved_plugin_capabilities is empty without a resolver", "[Config CHECK(config->unresolved_plugin_capabilities().empty()); } +TEST_CASE("unresolved_plugin_capabilities skips a value whose manifest entry is kept", "[Config][plugins]") { + // A save on a machine without the plugin keeps the entry the manifest already holds, so no + // reference is lost and there is nothing to prompt about. + ConfigBase::set_resolve_capability_fn([](const std::string& name, const std::string& type) { + return name == "offline" ? std::string() : name + ";;" + type; + }); + std::unique_ptr config(DynamicPrintConfig::new_from_defaults_keys( + {"slicing_pipeline_plugin", "plugins"})); + config->option("slicing_pipeline_plugin", true)->values = {"offline"}; + config->option("plugins", true)->values = {"Pack;3f2a6c1e;offline"}; + + const std::vector unresolved = config->unresolved_plugin_capabilities(); + config->update_plugin_manifest(); + const std::vector manifest = config->option("plugins")->values; + ConfigBase::set_resolve_capability_fn(nullptr); + + CHECK(unresolved.empty()); + CHECK(manifest == std::vector{"Pack;3f2a6c1e;offline"}); +} + +TEST_CASE("A printer preset keeps the printer_plugins entry of a capability not loaded here", "[Config][plugins]") { + ConfigBase::set_resolve_capability_fn([](const std::string& name, const std::string& type) { + return name == "gone" ? std::string() : name + ";;" + type; + }); + std::unique_ptr config(DynamicPrintConfig::new_from_defaults_keys( + {"printer_agent", "printer_plugins"})); + config->option("printer_agent", true)->value = "gone"; + config->option("printer_plugins", true)->values = {"Pack;3f2a6c1e;gone"}; + + const std::vector unresolved = config->unresolved_plugin_capabilities(); + config->update_plugin_manifest(); + const std::vector manifest = config->option("printer_plugins")->values; + ConfigBase::set_resolve_capability_fn(nullptr); + + CHECK(unresolved.empty()); + CHECK(manifest == std::vector{"Pack;3f2a6c1e;gone"}); + CHECK(config->option("plugins") == nullptr); +} + +TEST_CASE("Legacy printer plugin references move into printer_plugins on load", "[Config][plugins]") { + // A printer preset written before "printer_plugins" existed carries its references under the + // process preset's key, which is not a printer option; remove_invalid_keys would report and drop + // them, and the notice for a plugin this machine lacks would go with them. + std::unique_ptr defaults(DynamicPrintConfig::new_from_defaults_keys(Preset::printer_options())); + DynamicPrintConfig child(*defaults); + child.option("printer_plugins")->values = {"Parent Agent;1111;agent"}; + child.set_key_value("plugins", new ConfigOptionStrings{"Child Agent;2222;agent"}); + + // Merged, not replaced: the child file holds only its own references, the parent's manifest is + // already in the config the child was built from. + CHECK(Preset::remove_invalid_keys(child, *defaults).empty()); + CHECK(child.option("plugins") == nullptr); + CHECK(child.option("printer_plugins")->values == + std::vector{"Parent Agent;1111;agent", "Child Agent;2222;agent"}); + + // A process preset keeps its own manifest: "plugins" is one of its keys. + std::unique_ptr print_defaults(DynamicPrintConfig::new_from_defaults_keys( + {"slicing_pipeline_plugin", "plugins"})); + DynamicPrintConfig print(*print_defaults); + print.option("plugins")->values = {"Pack;3333;pipeline"}; + CHECK(Preset::remove_invalid_keys(print, *print_defaults).empty()); + CHECK(print.option("plugins")->values == std::vector{"Pack;3333;pipeline"}); + + // A print preset that somehow holds both keys must still keep its own manifest: the migration only + // runs for a printer config, else "plugins" would move into a key the same check then strips. + DynamicPrintConfig both(*print_defaults); + both.option("plugins")->values = {"Pack;3333;pipeline"}; + both.set_key_value("printer_plugins", new ConfigOptionStrings{"Pack;4444;asset"}); + CHECK(Preset::remove_invalid_keys(both, *print_defaults) == "printer_plugins"); + CHECK(both.option("plugins")->values == std::vector{"Pack;3333;pipeline"}); + CHECK(both.option("printer_plugins") == nullptr); +} TEST_CASE("H2C/A2L-era multi-nozzle and pre-heat config keys exist", "[config]") { // Foundation keys backing H2C 6-nozzle cluster grouping, the pre-heat/pre-cool time // model, and wipe-tower nozzle-change handling. Defaults must keep existing diff --git a/tests/libslic3r/test_preset_bundle_loading.cpp b/tests/libslic3r/test_preset_bundle_loading.cpp index fd673d9d21..06a0f2834a 100644 --- a/tests/libslic3r/test_preset_bundle_loading.cpp +++ b/tests/libslic3r/test_preset_bundle_loading.cpp @@ -9456,6 +9456,214 @@ TEST_CASE("A disabled filament override is saved and reloaded column by column", CHECK(loaded->config.opt_serialize("filament_flow_ratio") == "1,1.1"); } +TEST_CASE("A printer preset saved against its parent keeps its plugin manifest under printer_plugins", "[Preset][Bundle][plugins]") +{ + ScopedPresetDataDir data_dir; + PresetBundle bundle; + ConfigBase::set_resolve_capability_fn([](const std::string& name, const std::string& type) { + return name.empty() ? std::string() : name + ";;" + type; + }); + + Preset &parent = add_inmemory_preset(bundle.printers, "Parent Printer @System"); + + // The manifest in memory is stale (it matches the parent's), so only the plugin-backed option is in the diff. + const fs::path file = data_dir.tmp.path() / PRESET_PRINTER_NAME / "Child Printer.json"; + Preset child(Preset::TYPE_PRINTER, "Child Printer"); + child.file = file.string(); + child.version = *Semver::parse("1.0.0"); + child.config = parent.config; + child.config.option(BBL_JSON_KEY_INHERITS, true)->value = parent.name; + child.config.option("printer_agent", true)->value = "agent"; + const bool saved_ok = child.save(&parent.config); + ConfigBase::set_resolve_capability_fn(nullptr); + REQUIRE(saved_ok); + + // "plugins" would be dropped as a key printer presets do not have. + DynamicPrintConfig saved; + std::map key_values; + std::string reason; + saved.load_from_json(file.string(), ForwardCompatibilitySubstitutionRule::EnableSilent, key_values, reason); + REQUIRE(reason.empty()); + CHECK(saved.option("plugins") == nullptr); + REQUIRE(saved.option("printer_plugins") != nullptr); + CHECK(saved.option("printer_plugins")->values == std::vector{"agent;;printer-connection"}); +} + +namespace { +// Installs a capability resolver for the duration of a test, cleared on teardown so a failing +// REQUIRE does not leak it into the cases that assert the no-resolver behavior. +struct ScopedPluginResolver { + explicit ScopedPluginResolver(std::function fn) + { ConfigBase::set_resolve_capability_fn(std::move(fn)); } + ~ScopedPluginResolver() { ConfigBase::set_resolve_capability_fn(nullptr); } +}; +} // namespace + +TEST_CASE("A printer preset saved against its parent keeps the plugin manifest it inherits", "[Preset][Bundle][plugins]") +{ + ScopedPresetDataDir data_dir; + PresetBundle bundle; + // The parent's asset pack resolves to the reference its manifest already holds. + ScopedPluginResolver resolver([](const std::string& name, const std::string& type) { + if (name == "PEI Plate") + return std::string("PackA;8f3c0000-0000-4000-8000-0000000000aa;PEI Plate"); + return name + ";;" + type; + }); + + Preset& parent = add_inmemory_preset(bundle.printers, "Parent Printer @System"); + parent.config.option("printer_asset_plugins", true)->values = {"PEI Plate"}; + parent.config.option("printer_plugins", true)->values = {"PackA;8f3c0000-0000-4000-8000-0000000000aa;PEI Plate"}; + parent.config.option("bed_custom_model", true)->value = + "orcacloud-asset/8f3c0000-0000-4000-8000-0000000000aa/plate.stl"; + + // The child changes only printer_agent, so the asset pack is not in the diff against the parent. + const fs::path file = data_dir.tmp.path() / PRESET_PRINTER_NAME / "Child Printer.json"; + Preset child(Preset::TYPE_PRINTER, "Child Printer"); + child.file = file.string(); + child.version = *Semver::parse("1.0.0"); + child.config = parent.config; + child.config.option(BBL_JSON_KEY_INHERITS, true)->value = parent.name; + child.config.option("printer_agent", true)->value = "agent"; + REQUIRE(child.save(&parent.config)); + + DynamicPrintConfig saved; + std::map key_values; + std::string reason; + saved.load_from_json(file.string(), ForwardCompatibilitySubstitutionRule::EnableSilent, key_values, reason); + REQUIRE(reason.empty()); + // Both the inherited asset pack and the agent this preset adds; the first alone would be dropped + // when the file is loaded against its parent. + REQUIRE(saved.option("printer_plugins") != nullptr); + CHECK(saved.option("printer_plugins")->values == + std::vector{"agent;;printer-connection", "PackA;8f3c0000-0000-4000-8000-0000000000aa;PEI Plate"}); +} + +TEST_CASE("save_current_preset runs the before-save hook on the config it stores", "[Preset][Bundle]") +{ + ScopedPresetDataDir data_dir; + PresetBundle bundle; + // Gives the collection its folder, where the saved preset is written. + fs::create_directories(data_dir.tmp.path() / PRESET_PRINTER_NAME); + PresetsConfigSubstitutions substitutions; + bundle.printers.load_presets(data_dir.tmp.path().string(), PRESET_PRINTER_NAME, substitutions, + ForwardCompatibilitySubstitutionRule::EnableSilent); + add_inmemory_preset(bundle.printers, "Parent Printer"); + REQUIRE(bundle.printers.select_preset_by_name("Parent Printer", true)); + + std::string selected_name; + PresetCollection::set_before_save_fn([&selected_name](Preset::Type type, DynamicPrintConfig& config, const DynamicPrintConfig& selected) { + if (type == Preset::TYPE_PRINTER) + config.option("printer_asset_plugins", true)->values = {"derived"}; + selected_name = selected.opt_string("printer_settings_id"); + }); + bundle.printers.get_edited_preset().config.option("printer_settings_id", true)->value = "Parent Printer"; + bundle.printers.get_selected_preset().config.option("printer_settings_id", true)->value = "Parent Printer"; + bundle.printers.save_current_preset("Child Printer"); + PresetCollection::set_before_save_fn(nullptr); + + const Preset* saved = bundle.printers.find_preset("Child Printer"); + REQUIRE(saved != nullptr); + CHECK(saved->config.option("printer_asset_plugins")->values == std::vector{"derived"}); + // The saved preset is selected again, so the edited copy carries the derived value and is not dirty. + CHECK(bundle.printers.get_edited_preset().config.option("printer_asset_plugins")->values == + std::vector{"derived"}); + CHECK_FALSE(bundle.printers.current_is_dirty()); + CHECK(selected_name == "Parent Printer"); +} + +TEST_CASE("A printer preset written before printer_plugins keeps its legacy plugins manifest", "[Preset][Bundle][plugins]") +{ + ScopedPresetDataDir data_dir; + PresetBundle bundle; + + // What a build before the printer manifest key wrote: the printer's plugin references under the + // process preset's "plugins", which is not a printer option. + DynamicPrintConfig legacy(bundle.printers.default_preset().config); + legacy.option("printer_settings_id", true)->value = "Legacy Printer"; + legacy.option("printer_agent", true)->value = "moonraker"; + legacy.set_key_value("plugins", new ConfigOptionStrings{"Moonraker Agent;8f3c0000-0000-4000-8000-000000000000;moonraker"}); + const fs::path file = data_dir.tmp.path() / PRESET_PRINTER_NAME / "Legacy Printer.json"; + fs::create_directories(file.parent_path()); + legacy.save_to_json(file.string(), "Legacy Printer", "User", "1.0.0"); + + PresetsConfigSubstitutions substitutions; + bundle.printers.load_presets(data_dir.tmp.path().string(), PRESET_PRINTER_NAME, substitutions, + ForwardCompatibilitySubstitutionRule::EnableSilent); + + const Preset* loaded = bundle.printers.find_preset("Legacy Printer"); + REQUIRE(loaded != nullptr); + // Renamed rather than reported as an incorrect key and dropped, so the notice for a plugin that is + // not installed here still has the reference it needs. + CHECK(bundle.printers.error_count() == 0); + CHECK(loaded->config.option("plugins") == nullptr); + REQUIRE(loaded->config.option("printer_plugins") != nullptr); + CHECK(loaded->config.option("printer_plugins")->values == + std::vector{"Moonraker Agent;8f3c0000-0000-4000-8000-000000000000;moonraker"}); +} + +TEST_CASE("A printer preset inheriting its parent keeps a legacy plugins manifest", "[Preset][Bundle][plugins]") +{ + ScopedPresetDataDir data_dir; + PresetBundle bundle; + + Preset& parent = add_inmemory_preset(bundle.printers, "Parent Printer"); + parent.is_system = true; + parent.config.option("printer_plugins", true)->values = {"Parent Agent;1111;agent"}; + + // A child written before the printer manifest key existed: its own references sit under the process + // preset's "plugins", and there is no printer_plugins key to carry them past the parent merge. + DynamicPrintConfig legacy(bundle.printers.default_preset().config); + legacy.option("printer_settings_id", true)->value = "Legacy Child"; + legacy.option(BBL_JSON_KEY_INHERITS, true)->value = parent.name; + legacy.option("printer_agent", true)->value = "agent"; + legacy.erase("printer_plugins"); + legacy.set_key_value("plugins", new ConfigOptionStrings{"Legacy Agent;9a7d0000-0000-4000-8000-000000000000;agent"}); + const fs::path file = data_dir.tmp.path() / PRESET_PRINTER_NAME / "Legacy Child.json"; + fs::create_directories(file.parent_path()); + legacy.save_to_json(file.string(), "Legacy Child", "User", "1.0.0"); + + PresetsConfigSubstitutions substitutions; + bundle.printers.load_presets(data_dir.tmp.path().string(), PRESET_PRINTER_NAME, substitutions, + ForwardCompatibilitySubstitutionRule::EnableSilent); + + const Preset* loaded = bundle.printers.find_preset("Legacy Child"); + REQUIRE(loaded != nullptr); + CHECK(bundle.printers.error_count() == 0); + CHECK(loaded->config.option("plugins") == nullptr); + // Merged with the parent's manifest: the child file only holds the references it added. + REQUIRE(loaded->config.option("printer_plugins") != nullptr); + CHECK(loaded->config.option("printer_plugins")->values == + std::vector{"Parent Agent;1111;agent", "Legacy Agent;9a7d0000-0000-4000-8000-000000000000;agent"}); +} + +TEST_CASE("Preset::reload keeps a legacy plugins manifest of an inheriting printer preset", "[Preset][Bundle][plugins]") +{ + ScopedPresetDataDir data_dir; + PresetBundle bundle; + + Preset& parent = add_inmemory_preset(bundle.printers, "Parent Printer"); + parent.is_system = true; + parent.config.option("printer_plugins", true)->values = {"Parent Agent;1111;agent"}; + + DynamicPrintConfig legacy(bundle.printers.default_preset().config); + legacy.option(BBL_JSON_KEY_INHERITS, true)->value = parent.name; + legacy.option("printer_agent", true)->value = "agent"; + legacy.erase("printer_plugins"); + legacy.set_key_value("plugins", new ConfigOptionStrings{"Legacy Agent;9a7d0000-0000-4000-8000-000000000000;agent"}); + + Preset child(Preset::TYPE_PRINTER, "Legacy Child"); + child.file = (data_dir.tmp.path() / PRESET_PRINTER_NAME / "Legacy Child.json").string(); + fs::create_directories(fs::path(child.file).parent_path()); + legacy.save_to_json(child.file, "Legacy Child", "User", "1.0.0"); + + child.reload(parent); + + CHECK(child.config.option("plugins") == nullptr); + REQUIRE(child.config.option("printer_plugins") != nullptr); + CHECK(child.config.option("printer_plugins")->values == + std::vector{"Parent Agent;1111;agent", "Legacy Agent;9a7d0000-0000-4000-8000-000000000000;agent"}); +} + TEST_CASE("The cloud diff force-emits a disabled override only where the cloud would fill a value in", "[Preset][Bundle]") { PresetBundle bundle; diff --git a/tests/libslic3r/test_printer_asset_ref.cpp b/tests/libslic3r/test_printer_asset_ref.cpp new file mode 100644 index 0000000000..16de7816b5 --- /dev/null +++ b/tests/libslic3r/test_printer_asset_ref.cpp @@ -0,0 +1,133 @@ +#include +#include +#include + +#include + +#include "libslic3r/PrinterAssetRef.hpp" + +using namespace Slic3r; + +// Printer asset references in bed_custom_model / bed_custom_texture: "orcacloud-asset//". + +TEST_CASE("A printer asset reference parses into its plugin id and file name", "[PrinterAssetRef]") +{ + const auto ref = parse_printer_asset_ref("orcacloud-asset/3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f/voron_24_350.stl"); + REQUIRE(ref.has_value()); + CHECK(ref->plugin_id == "3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f"); + CHECK(ref->filename == "voron_24_350.stl"); +} + +TEST_CASE("make and parse round-trip a printer asset reference", "[PrinterAssetRef]") +{ + const std::string value = make_printer_asset_ref("my-pack", "Plate-A.svg"); + CHECK(value == "orcacloud-asset/my-pack/Plate-A.svg"); + const auto ref = parse_printer_asset_ref(value); + REQUIRE(ref.has_value()); + CHECK(ref->plugin_id == "my-pack"); + CHECK(ref->filename == "Plate-A.svg"); +} + +TEST_CASE("Plain bed paths are not printer asset references", "[PrinterAssetRef]") +{ + CHECK_FALSE(parse_printer_asset_ref("").has_value()); + CHECK_FALSE(parse_printer_asset_ref("/Users/me/Downloads/bed.stl").has_value()); + CHECK_FALSE(parse_printer_asset_ref("C:\\Users\\me\\bed.png").has_value()); + CHECK_FALSE(parse_printer_asset_ref("bed.stl").has_value()); + // The prefix is case-sensitive, like every config key value. + CHECK_FALSE(parse_printer_asset_ref("OrcaCloud-Asset/pack/bed.stl").has_value()); +} + +TEST_CASE("Malformed printer asset references are rejected", "[PrinterAssetRef]") +{ + for (const char* value : { + "orcacloud-asset/", + "orcacloud-asset/pack", + "orcacloud-asset/pack/", + "orcacloud-asset//bed.stl", + "orcacloud-asset/pack/../bed.stl", + "orcacloud-asset/pack/sub/bed.stl", + "orcacloud-asset/../bed.stl", + "orcacloud-asset/pack/..", + "orcacloud-asset/pack/bed .stl", + "orcacloud-asset/pack/bed:stream.stl", + "orcacloud-asset/pa\\ck/bed.stl", + }) { + INFO(value); + CHECK_FALSE(parse_printer_asset_ref(value).has_value()); + } + CHECK(make_printer_asset_ref("pack", "../bed.stl").empty()); + CHECK(make_printer_asset_ref("", "bed.stl").empty()); + CHECK(make_printer_asset_ref("pack one", "bed.stl").empty()); +} + +TEST_CASE("Windows device names are not printer asset file names", "[PrinterAssetRef]") +{ + // Windows opens these, with any extension, as devices, so the reference would resolve everywhere else. + for (const char* filename : {"con.stl", "NUL.png", "Com1.svg", "lpt9.stl", "aux.plate.png", "prn"}) { + INFO(filename); + CHECK(make_printer_asset_ref("pack", filename).empty()); + CHECK_FALSE(parse_printer_asset_ref(std::string("orcacloud-asset/pack/") + filename).has_value()); + } + for (const char* filename : {"console.stl", "com10.stl", "my-con.png", "lpt.png"}) { + INFO(filename); + CHECK(parse_printer_asset_ref(std::string("orcacloud-asset/pack/") + filename).has_value()); + } +} + +TEST_CASE("Bed files are sorted into models and textures by extension", "[PrinterAssetRef]") +{ + CHECK(is_printer_bed_model_file("bed.STL")); + CHECK_FALSE(is_printer_bed_model_file("bed.png")); + CHECK(is_printer_bed_texture_file("plate.png")); + CHECK(is_printer_bed_texture_file("plate.Svg")); + CHECK_FALSE(is_printer_bed_texture_file("plate.jpg")); + CHECK_FALSE(is_printer_bed_texture_file("png")); +} + +TEST_CASE("Only ASCII characters are allowed in a printer asset reference", "[PrinterAssetRef]") +{ + // The rule is A-Z a-z 0-9 . _ -, so a name is the same on every machine whatever its locale. A + // predicate would accept these on a single-byte Windows codepage. + for (const char* value : { + "orcacloud-asset/pack/bed_\xE9.stl", // Latin-1 e-acute, one byte + "orcacloud-asset/pack/bed_\xC3\xA9.stl", // the same letter as UTF-8 + "orcacloud-asset/p\xE9" "ck/bed.stl", + "orcacloud-asset/pack/bed\x7F.stl", + }) { + INFO(value); + CHECK_FALSE(parse_printer_asset_ref(value).has_value()); + } + for (const char* filename : {"bed_\xE9.stl", "bed_\xC3\xA9.stl", "bed\x7F.stl", "b\x80" "ed.stl"}) { + INFO(filename); + CHECK_FALSE(is_printer_asset_file_name(filename)); + CHECK(make_printer_asset_ref("pack", filename).empty()); + } + // Every printable ASCII character outside the set is refused too. + for (char ch = 0x20; ch < 0x7F; ++ch) { + const bool allowed = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || + ch == '.' || ch == '_' || ch == '-'; + if (allowed) + continue; + const std::string filename = std::string("bed") + ch + "stl"; + INFO(filename); + CHECK_FALSE(is_printer_asset_file_name(filename)); + } +} + +TEST_CASE("A printer asset reference segment is capped at 128 characters", "[PrinterAssetRef]") +{ + const std::string longest(128, 'a'); + const std::string too_long(129, 'a'); + + CHECK(is_printer_asset_file_name(longest)); + CHECK_FALSE(is_printer_asset_file_name(too_long)); + + CHECK(parse_printer_asset_ref("orcacloud-asset/pack/" + longest).has_value()); + CHECK_FALSE(parse_printer_asset_ref("orcacloud-asset/pack/" + too_long).has_value()); + CHECK_FALSE(parse_printer_asset_ref("orcacloud-asset/" + too_long + "/bed.stl").has_value()); + + // The traversal-shaped names are rejected by the exact-match rule, not by the charset. + CHECK_FALSE(parse_printer_asset_ref("orcacloud-asset/pack/.").has_value()); + CHECK_FALSE(parse_printer_asset_ref("orcacloud-asset/./bed.stl").has_value()); +} diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 22f0f3bbd7..78a9271e1f 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -68,6 +68,7 @@ add_executable(${_TEST_NAME}_tests test_plugin_lifecycle.cpp test_plugin_wheel_install.cpp test_plugin_resource_texture.cpp + test_plugin_printer_asset.cpp test_plugin_printer_agent.cpp test_post_processor.cpp test_printhost.cpp diff --git a/tests/slic3rutils/test_plugin_capabilities_in_use.cpp b/tests/slic3rutils/test_plugin_capabilities_in_use.cpp index e33c9980dd..54a55d71b2 100644 --- a/tests/slic3rutils/test_plugin_capabilities_in_use.cpp +++ b/tests/slic3rutils/test_plugin_capabilities_in_use.cpp @@ -74,3 +74,46 @@ TEST_CASE("referenced_capabilities skips malformed manifest entries", "[PluginRe CHECK(capability_names(referenced_capabilities(Preset::TYPE_PRINT, preset)) == std::vector{"CapA"}); } + +TEST_CASE("A missing printer preset plugin is reported but does not block slicing", "[PluginResolver]") +{ + const auto clear_missing = [] { + for (const Preset::Type type : {Preset::TYPE_PRINT, Preset::TYPE_PRINTER, Preset::TYPE_FILAMENT}) + refresh_missing_plugins(type, nullptr); + }; + clear_missing(); + + Preset printer(Preset::TYPE_PRINTER, "test-printer"); + const std::unique_ptr defaults( + DynamicPrintConfig::new_from_defaults_keys({"printer_agent", "printer_plugins"})); + printer.config = *defaults; + printer.config.option("printer_agent")->value = "agent"; + printer.config.option("printer_plugins")->values = {"acme;;agent"}; + refresh_missing_plugins(Preset::TYPE_PRINTER, printer.config.option("printer_plugins"), &printer); + + CHECK(has_missing_plugins()); + CHECK_FALSE(has_blocking_plugins()); + + clear_missing(); +} + +TEST_CASE("A missing process preset plugin blocks slicing", "[PluginResolver]") +{ + const auto clear_missing = [] { + for (const Preset::Type type : {Preset::TYPE_PRINT, Preset::TYPE_PRINTER, Preset::TYPE_FILAMENT}) + refresh_missing_plugins(type, nullptr); + }; + clear_missing(); + + // The same unresolved reference blocks when it comes from the process preset: only printer preset + // plugins (printer agents, printer assets) are exempt, so a capability that changes the sliced + // result must still be installed first. + const Preset print = make_print_preset({"acme;;CapA"}, {"CapA"}); + refresh_missing_plugins(Preset::TYPE_PRINT, print.config.option("plugins"), &print); + + CHECK(has_missing_plugins()); + CHECK(has_blocking_plugins()); + + clear_missing(); + CHECK_FALSE(has_blocking_plugins()); +} diff --git a/tests/slic3rutils/test_plugin_printer_asset.cpp b/tests/slic3rutils/test_plugin_printer_asset.cpp new file mode 100644 index 0000000000..0fb1b4dd60 --- /dev/null +++ b/tests/slic3rutils/test_plugin_printer_asset.cpp @@ -0,0 +1,571 @@ +// ResourcePrinterAsset plugin type: asset folder validation, the host registry's lifecycle, +// resolving the "orcacloud-asset//" references printer presets store in +// bed_custom_model / bed_custom_texture, and the printer preset manifest that lets PluginResolver +// offer a missing pack without blocking slicing. +// +// The GUI wiring lives in GUI_App::init_plugin_gui_wiring; the test binary has no app, so the same +// registry callbacks are installed here. Each Catch2 test case runs in its own process +// (catch_discover_tests), so the PluginManager and interpreter come up at most once per test. +#include "test_utils.hpp" +#include +#ifdef WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "libslic3r/Config.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/PrinterAssetRef.hpp" + +#include "slic3r/plugin/PluginFsUtils.hpp" +#include "slic3r/plugin/PluginManager.hpp" +#include "slic3r/plugin/PluginResolver.hpp" +#include "slic3r/plugin/PythonInterpreter.hpp" +#include "slic3r/plugin/PythonPluginInterface.hpp" +#include "slic3r/plugin/host/PluginPrinterAssets.hpp" + +#include "plugin_test_utils.hpp" + +using namespace Slic3r; +namespace fs = boost::filesystem; + +namespace { + +// Declare FIRST in a test so it is destroyed last (see test_plugin_resource_texture.cpp). +struct ScopedPluginManager +{ + ScopedDataDir python_data_dir{"asset-python"}; + bool initialized = false; + + ScopedPluginManager() { initialized = PluginManager::instance().initialize(); } + ~ScopedPluginManager() { PluginManager::instance().shutdown(); } +}; + +void install_printer_asset_wiring() +{ + static bool installed = false; + if (installed) + return; + installed = true; + + PluginManager& manager = PluginManager::instance(); + manager.subscribe_on_load_callback([](const std::string& plugin_key) { PluginPrinterAssets::instance().on_plugin_register(plugin_key); }); + manager.subscribe_on_unload_callback([](const std::string& plugin_key) { PluginPrinterAssets::instance().on_plugin_deregister(plugin_key); }); + manager.subscribe_on_capability_load_callback([](const PluginCapabilityId& capability) { + if (capability.type == PluginCapabilityType::ResourcePrinterAsset) + PluginPrinterAssets::instance().on_cap_register(capability); + }); + manager.subscribe_on_capability_unload_callback([](const PluginCapabilityId& capability) { + if (capability.type == PluginCapabilityType::ResourcePrinterAsset) + PluginPrinterAssets::instance().on_cap_deregister(capability); + }); +} + +std::string printer_asset_script_header(const std::string& display_name) +{ + return std::string{} + + "# /// script\n" + + "# requires-python = \">=3.12\"\n" + + "# dependencies = []\n" + + "#\n" + + "# [tool.orcaslicer.plugin]\n" + + "# name = \"" + display_name + "\"\n" + + "# description = \"Printer asset pack fixture.\"\n" + + "# author = \"tests\"\n" + + "# version = \"1.0.0\"\n" + + "# type = \"resource-printer-asset\"\n" + + "# ///\n"; +} + +// A minimal printer asset pack shaped like the wheel Orca Cloud builds (pa/__init__.py + pa/a/). +std::string make_printer_asset_source(const std::string& display_name, const std::string& get_asset_dir_body) +{ + return printer_asset_script_header(display_name) + + "import os\n" + + "import orca\n" + + "\n\n" + + "class PrinterAssets(orca.resource_printer_asset.ResourcePrinterAssetPluginCapabilityBase):\n" + + " def get_name(self):\n" + + " return \"" + display_name + "\"\n" + + "\n" + + " def get_asset_dir(self):\n" + + " " + get_asset_dir_body + "\n" + + "\n\n" + + "@orca.plugin\n" + + "class PrinterAssetPack(orca.base):\n" + + " def register_capabilities(self):\n" + + " orca.register_capability(PrinterAssets)\n"; +} + +// One plugin with two capabilities, "Voron Bed" over folder a and "Voron Plate" over folder b. +std::string make_two_capability_source() +{ + const std::string base = "orca.resource_printer_asset.ResourcePrinterAssetPluginCapabilityBase"; + return printer_asset_script_header("Voron Packs") + + "import os\n" + + "import orca\n" + + "\n\n" + + "class BedPack(" + base + "):\n" + + " def get_name(self):\n" + + " return \"Voron Bed\"\n" + + "\n" + + " def get_asset_dir(self):\n" + + " return os.path.join(os.path.dirname(__file__), \"a\")\n" + + "\n\n" + + "class PlatePack(" + base + "):\n" + + " def get_name(self):\n" + + " return \"Voron Plate\"\n" + + "\n" + + " def get_asset_dir(self):\n" + + " return os.path.join(os.path.dirname(__file__), \"b\")\n" + + "\n\n" + + "@orca.plugin\n" + + "class PrinterAssetPack(orca.base):\n" + + " def register_capabilities(self):\n" + + " orca.register_capability(BedPack)\n" + + " orca.register_capability(PlatePack)\n"; +} + +std::string default_asset_dir_body() { return "return os.path.join(os.path.dirname(__file__), \"a\")"; } + +fs::path write_plugin(const ScopedDataDir& data_dir_guard, const std::string& stem, const std::string& source) +{ + const fs::path plugin_dir = data_dir_guard.plugins_dir() / stem; + fs::create_directories(plugin_dir); + std::ofstream out((plugin_dir / (stem + ".py")).string(), std::ios::binary); + out << source; + return plugin_dir; +} + +void write_text_file(const fs::path& path, const std::string& content = "x") +{ + fs::create_directories(path.parent_path()); + std::ofstream out(path.string(), std::ios::binary); + out << content; +} + +bool load_and_wait(PluginManager& manager, const std::string& plugin_key, std::string& error) +{ + manager.load_plugin(plugin_key, /*skip_deps=*/true); + return manager.wait_for_plugin_load(plugin_key, std::chrono::seconds(120), error); +} + +std::vector filenames(const std::vector& paths) +{ + std::vector names; + for (const std::string& path : paths) + names.push_back(fs::path(path).filename().string()); + std::sort(names.begin(), names.end()); + return names; +} + +// Loads one local pack "Voron Bed" (plugin key Voron_Bed) with a model, a texture and a stray file. +std::string load_voron_pack(const ScopedDataDir& data_dir_guard) +{ + const std::string plugin_key = "Voron_Bed"; + const fs::path plugin_dir = write_plugin(data_dir_guard, plugin_key, make_printer_asset_source("Voron Bed", default_asset_dir_body())); + write_text_file(plugin_dir / "a" / "bed.stl"); + write_text_file(plugin_dir / "a" / "plate.svg"); + write_text_file(plugin_dir / "a" / "readme.txt"); + + PluginManager& manager = PluginManager::instance(); + install_printer_asset_wiring(); + manager.discover_plugins(/*async=*/false, /*clear=*/true); + + std::string error; + const bool loaded = load_and_wait(manager, plugin_key, error); + INFO("load error: " << error); + REQUIRE(loaded); + return plugin_key; +} + +} // namespace + +// ── Validation (collect_printer_asset_files, no Python) ───────────────────────────────────────── + +TEST_CASE("An asset folder lists only its .stl, .png and .svg files", "[PluginPrinterAsset]") +{ + ScopedTemporaryDir root("asset-root"); + write_text_file(root.path() / "a" / "bed.stl"); + write_text_file(root.path() / "a" / "plate.PNG"); + write_text_file(root.path() / "a" / "plate.svg"); + write_text_file(root.path() / "a" / "notes.txt"); + write_text_file(root.path() / "a" / "photo.jpg"); + write_text_file(root.path() / "a" / "nested" / "deep.stl"); + + std::string error; + const std::vector files = collect_printer_asset_files((root.path() / "a").string(), root.string(), error); + + CHECK(error.empty()); + CHECK(filenames(files) == std::vector{"bed.stl", "plate.PNG", "plate.svg"}); +} + +TEST_CASE("An asset folder outside the plugin folder is refused", "[PluginPrinterAsset]") +{ + ScopedTemporaryDir parent("asset-escape"); + const fs::path root = parent.path() / "pack"; + const fs::path outside = parent.path() / "outside"; + fs::create_directories(root); + write_text_file(outside / "bed.stl"); + + std::string error; + CHECK(collect_printer_asset_files((root / ".." / "outside").string(), root.string(), error).empty()); + CHECK_FALSE(error.empty()); + CHECK(collect_printer_asset_files("", root.string(), error).empty()); + CHECK_FALSE(error.empty()); +} + +TEST_CASE("The asset listing stops at 16 files", "[PluginPrinterAsset]") +{ + ScopedTemporaryDir root("asset-cap"); + for (int i = 0; i < 20; ++i) + write_text_file(root.path() / ("plate_" + std::to_string(i) + ".stl")); + + // Sorted before the cap, so every file system keeps the same 16. + std::string error; + const std::vector files = collect_printer_asset_files(root.string(), root.string(), error); + REQUIRE(files.size() == 16); + CHECK(std::is_sorted(files.begin(), files.end())); + CHECK(fs::path(files.back()).filename() == "plate_5.stl"); +} + +TEST_CASE("Names a reference cannot hold do not take a slot in the 16-file cap", "[PluginPrinterAsset]") +{ + ScopedTemporaryDir root("asset-names"); + // Spaces and device names sort before the valid files, so they would fill the cap first. + for (int i = 0; i < 16; ++i) + write_text_file(root.path() / ("a plate " + std::to_string(i) + ".stl")); + write_text_file(root.path() / "con.stl"); + write_text_file(root.path() / "plate_a.stl"); + write_text_file(root.path() / "plate_b.png"); + + std::string error; + const std::vector files = collect_printer_asset_files(root.string(), root.string(), error); + + CHECK(error.empty()); + CHECK(filenames(files) == std::vector{"plate_a.stl", "plate_b.png"}); +} + +TEST_CASE("A symlink pointing outside the plugin folder is skipped, not reported as an error", "[PluginPrinterAsset]") +{ + ScopedTemporaryDir root("asset-symlink-root"); + ScopedTemporaryDir target("asset-symlink-target"); + write_text_file(target.path() / "secret.stl"); + write_text_file(root.path() / "a" / "bed.stl"); + + const fs::path link = root.path() / "a" / "link.stl"; + boost::system::error_code ec; + fs::create_symlink(target.path() / "secret.stl", link, ec); + if (ec) + SKIP("symlinks unavailable on this filesystem: " + ec.message()); + + std::string error; + const std::vector files = collect_printer_asset_files((root.path() / "a").string(), root.string(), error); + + // The folder itself is legitimate; the escaping link is dropped, not an error. + CHECK(error.empty()); + CHECK(filenames(files) == std::vector{"bed.stl"}); +} + +TEST_CASE("A dangling symlink in the asset folder is skipped", "[PluginPrinterAsset]") +{ + ScopedTemporaryDir root("asset-dangling"); + write_text_file(root.path() / "a" / "bed.stl"); + + const fs::path link = root.path() / "a" / "gone.stl"; + boost::system::error_code ec; + fs::create_symlink(root.path() / "a" / "missing.stl", link, ec); + if (ec) + SKIP("symlinks unavailable on this filesystem: " + ec.message()); + + std::string error; + const std::vector files = collect_printer_asset_files((root.path() / "a").string(), root.string(), error); + + CHECK(error.empty()); + CHECK(filenames(files) == std::vector{"bed.stl"}); +} + +TEST_CASE("Plain bed paths resolve to themselves and packs that are not loaded to nothing", "[PluginPrinterAsset]") +{ + const std::string missing_ref = "orcacloud-asset/3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f/bed.stl"; + + CHECK(resolve_printer_asset_value("") == ""); + CHECK(resolve_printer_asset_value("/Users/me/bed.stl") == "/Users/me/bed.stl"); + CHECK(resolve_printer_asset_value(missing_ref).empty()); +} + +TEST_CASE("A printer's asset pack names follow its bed files, falling back to its manifest for packs not loaded here", + "[PluginPrinterAsset]") +{ + std::unique_ptr config(DynamicPrintConfig::new_from_defaults_keys(Preset::printer_options())); + const auto names = [&config]() { return config->option("printer_asset_plugins")->values; }; + + // Plain paths name no pack, so a stale name is dropped. + config->option("printer_asset_plugins")->values = {"Old Pack"}; + config->set_key_value("bed_custom_model", new ConfigOptionString("/Users/me/bed.stl")); + update_printer_asset_plugins(*config); + CHECK(names().empty()); + + // A pack that is not loaded here keeps the name its manifest entry (matched by uuid) holds. + config->set_key_value("bed_custom_model", new ConfigOptionString("orcacloud-asset/3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f/bed.stl")); + config->set_key_value("bed_custom_texture", new ConfigOptionString("orcacloud-asset/9b1d0000-0000-4000-8000-000000000000/plate.png")); + config->option("printer_plugins")->values = {"Voron Bed;3F2A6C1E-8D4B-4C2A-9E7F-1A2B3C4D5E6F;Voron Bed by sam"}; + update_printer_asset_plugins(*config); + // The texture's pack is neither loaded nor in the manifest: its name is unknown. + CHECK(names() == std::vector{"Voron Bed by sam"}); + + // The saved preset's manifest names a pack this config's manifest has lost (e.g. bed files + // transferred from another preset). Entries carry no type: the plugin's other capability + // ("Voron Agent") loses to the name the config already lists as an asset pack. + config->option("printer_plugins")->values = {}; + config->option("printer_asset_plugins")->values = {"Voron Bed by sam"}; + const ConfigOptionStrings saved_manifest({"Voron Bed;3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f;Voron Agent", + "Voron Bed;3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f;Voron Bed by sam", + "Other Agent;77777777-0000-4000-8000-000000000000;Agent"}); + update_printer_asset_plugins(*config, &saved_manifest); + CHECK(names() == std::vector{"Voron Bed by sam"}); + // Only the bed files' packs are taken over from the fallback, even without a resolver to rebuild + // the manifest. + const std::vector manifest = config->option("printer_plugins")->values; + CHECK(std::find(manifest.begin(), manifest.end(), "Other Agent;77777777-0000-4000-8000-000000000000;Agent") == manifest.end()); + CHECK(std::find(manifest.begin(), manifest.end(), "Voron Bed;3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f;Voron Bed by sam") != manifest.end()); + + // Not a printer config: nothing to do. + std::unique_ptr print(DynamicPrintConfig::new_from_defaults_keys({"bed_custom_model"})); + update_printer_asset_plugins(*print); + CHECK(print->option("printer_asset_plugins") == nullptr); +} + +TEST_CASE("A pack that is not loaded keeps its own manifest entry when another plugin has a capability of the same name", + "[PluginPrinterAsset]") +{ + struct ScopedResolver + { + ScopedResolver() + { + ConfigBase::set_resolve_capability_fn([](const std::string& name, const std::string&) { + return name == "PEI Plate" ? std::string("Other Pack;aaaaaaaa-0000-4000-8000-000000000000;PEI Plate") : std::string(); + }); + } + ~ScopedResolver() { ConfigBase::set_resolve_capability_fn(nullptr); } + } resolver; + + // The bed file belongs to a pack that is not installed here. A loaded plugin has a capability with the + // same name, and the resolver finds capabilities by name alone. + std::unique_ptr config(DynamicPrintConfig::new_from_defaults_keys(Preset::printer_options())); + config->set_key_value("bed_custom_model", new ConfigOptionString("orcacloud-asset/3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f/bed.stl")); + config->option("printer_asset_plugins")->values = {"PEI Plate"}; + config->option("printer_plugins")->values = {"Voron Bed;3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f;PEI Plate"}; + + update_printer_asset_plugins(*config); + + CHECK(config->option("printer_asset_plugins")->values == std::vector{"PEI Plate"}); + CHECK(config->option("printer_plugins")->values == + std::vector{"Voron Bed;3f2a6c1e-8d4b-4c2a-9e7f-1a2b3c4d5e6f;PEI Plate"}); +} + +// ── Lifecycle (Python) ────────────────────────────────────────────────────────────────────────── + +TEST_CASE("Registering a pack again reports no change unless its files or name did", "[PluginPrinterAsset][PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedDataDir data_dir_guard("asset-change-flag"); + const std::string plugin_key = load_voron_pack(data_dir_guard); + PluginManager& manager = PluginManager::instance(); + + const PluginCapabilityId id{PluginCapabilityType::ResourcePrinterAsset, "Voron Bed", plugin_key}; + // Rebuilding the same entry must not redraw the bed: a load registers a pack twice, once through + // the plugin callbacks and once through the capability's. + CHECK_FALSE(PluginPrinterAssets::instance().on_cap_register(id)); + + // A file added to the folder changes what a reference can resolve to, so it is a change. + const fs::path added = data_dir_guard.plugins_dir() / plugin_key / "a" / "bed_small.stl"; + write_text_file(added); + CHECK(PluginPrinterAssets::instance().on_cap_register(id)); + CHECK_FALSE(PluginPrinterAssets::instance().on_cap_register(id)); + + fs::remove(added); + CHECK(PluginPrinterAssets::instance().on_cap_register(id)); + + REQUIRE(manager.unload_plugin(plugin_key)); +} + +TEST_CASE("A pack's files resolve from references and stop resolving on disable and unload", + "[PluginPrinterAsset][PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedDataDir data_dir_guard("asset-lifecycle"); + const std::string plugin_key = load_voron_pack(data_dir_guard); + PluginManager& manager = PluginManager::instance(); + + const std::vector packs = PluginPrinterAssets::instance().entries(); + REQUIRE(packs.size() == 1); + CHECK(packs.front().display_name == "Voron Bed"); + // A local pack has no cloud uuid, so references use its plugin key. + CHECK(packs.front().pack_id == plugin_key); + CHECK(filenames(packs.front().files) == std::vector{"bed.stl", "plate.svg"}); + + const std::string model_ref = make_printer_asset_ref(plugin_key, "bed.stl"); + const std::string model = resolve_printer_asset_value(model_ref); + CHECK(fs::path(model).filename() == "bed.stl"); + CHECK(fs::exists(model)); + // Only files the pack lists resolve; the reference can never leave the asset folder. + CHECK(resolve_printer_asset_value(make_printer_asset_ref(plugin_key, "readme.txt")).empty()); + + manager.set_capability_enabled({PluginCapabilityType::ResourcePrinterAsset, "Voron Bed", plugin_key}, false); + CHECK(PluginPrinterAssets::instance().entries().empty()); + CHECK(resolve_printer_asset_value(model_ref).empty()); + + manager.set_capability_enabled({PluginCapabilityType::ResourcePrinterAsset, "Voron Bed", plugin_key}, true); + CHECK(resolve_printer_asset_value(model_ref) == model); + + REQUIRE(manager.unload_plugin(plugin_key)); + CHECK(PluginPrinterAssets::instance().entries().empty()); +} + +TEST_CASE("A printer preset names its pack in its own manifest, and an inactive pack prompts without blocking slicing", + "[PluginPrinterAsset][PluginResolver][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedDataDir data_dir_guard("asset-manifest"); + const std::string plugin_key = load_voron_pack(data_dir_guard); + PluginManager& manager = PluginManager::instance(); + + // What the Bed Shape dialog stores: references to the pack's files. The pack's capability name and + // manifest entry follow from them. A file from a pack this machine knows nothing about adds no name + // but does not drop the loaded pack's. + std::unique_ptr config(DynamicPrintConfig::new_from_defaults_keys(Preset::printer_options())); + config->set_key_value("bed_custom_texture", new ConfigOptionString("orcacloud-asset/9b1d0000-0000-4000-8000-000000000000/plate.png")); + config->set_key_value("bed_custom_model", new ConfigOptionString(make_printer_asset_ref(plugin_key, "bed.stl"))); + update_printer_asset_plugins(*config); + CHECK(config->option("printer_asset_plugins")->values == std::vector{"Voron Bed"}); + + // The printer keeps its manifest apart from the process preset's "plugins", which the full print + // config would otherwise overwrite with it. + const std::vector expected_manifest{plugin_key + ";;Voron Bed"}; + CHECK(config->option("plugins") == nullptr); + CHECK(config->option("printer_plugins")->values == expected_manifest); + CHECK(config->plugin_manifest_key() == "printer_plugins"); + + Preset printer(Preset::TYPE_PRINTER, "Voron with bed pack"); + printer.config = *config; + const auto refresh = [&printer]() { + refresh_missing_plugins(Preset::TYPE_PRINTER, printer.config.option("printer_plugins"), &printer); + }; + + refresh(); + CHECK_FALSE(has_inactive_plugins()); + + // Turned off: offered for activation, never blocking slicing. The installed pack still names itself + // when the manifest has lost its entry. + manager.set_capability_enabled({PluginCapabilityType::ResourcePrinterAsset, "Voron Bed", plugin_key}, false); + refresh(); + CHECK(has_inactive_plugins()); + CHECK_FALSE(has_blocking_plugins()); + { + DynamicPrintConfig stripped = *config; + stripped.option("printer_plugins")->values = {}; + update_printer_asset_plugins(stripped); + CHECK(stripped.option("printer_asset_plugins")->values == std::vector{"Voron Bed"}); + CHECK(stripped.option("printer_plugins")->values == expected_manifest); + } + + // Unloaded, as on a machine where the pack is not installed yet: saving the preset there keeps the + // pack's name and the manifest entry other machines need. + REQUIRE(manager.unload_plugin(plugin_key)); + update_printer_asset_plugins(*config); + CHECK(config->option("printer_asset_plugins")->values == std::vector{"Voron Bed"}); + CHECK(config->option("printer_plugins")->values == expected_manifest); + printer.config = *config; + refresh(); + CHECK(has_inactive_plugins()); + CHECK_FALSE(has_blocking_plugins()); + + refresh_missing_plugins(Preset::TYPE_PRINTER, nullptr); + CHECK_FALSE(has_inactive_plugins()); +} + +TEST_CASE("A pack whose get_asset_dir raises or leaves the plugin folder provides no files", + "[PluginPrinterAsset][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedDataDir data_dir_guard("asset-hostile"); + ScopedTemporaryDir elsewhere("asset-elsewhere"); + write_text_file(elsewhere.path() / "bed.stl"); + + write_plugin(data_dir_guard, "Raising_Bed", make_printer_asset_source("Raising Bed", "raise RuntimeError(\"no assets today\")")); + write_plugin(data_dir_guard, "Outside_Bed", + make_printer_asset_source("Outside Bed", "return r\"" + elsewhere.path().string() + "\"")); + + PluginManager& manager = PluginManager::instance(); + install_printer_asset_wiring(); + manager.discover_plugins(/*async=*/false, /*clear=*/true); + + std::string error; + CHECK(load_and_wait(manager, "Raising_Bed", error)); + CHECK(load_and_wait(manager, "Outside_Bed", error)); + CHECK(PluginPrinterAssets::instance().entries().empty()); + CHECK(resolve_printer_asset_value(make_printer_asset_ref("Outside_Bed", "bed.stl")).empty()); +} + +TEST_CASE("The capability name of a pack follows the file a reference names", "[PluginPrinterAsset][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedDataDir data_dir_guard("asset-two-capabilities"); + const std::string plugin_key = "Voron_Packs"; + const fs::path plugin_dir = write_plugin(data_dir_guard, plugin_key, make_two_capability_source()); + write_text_file(plugin_dir / "a" / "bed.stl"); + write_text_file(plugin_dir / "b" / "plate.svg"); + + PluginManager& manager = PluginManager::instance(); + install_printer_asset_wiring(); + manager.discover_plugins(/*async=*/false, /*clear=*/true); + + std::string error; + const bool loaded = load_and_wait(manager, plugin_key, error); + INFO("load error: " << error); + REQUIRE(loaded); + REQUIRE(PluginPrinterAssets::instance().entries().size() == 2); + + // Both capabilities belong to one plugin, so the plugin id alone cannot tell them apart. + const PluginPrinterAssets& packs = PluginPrinterAssets::instance(); + CHECK(packs.capability_name(PrinterAssetRef{plugin_key, "bed.stl"}) == "Voron Bed"); + CHECK(packs.capability_name(PrinterAssetRef{plugin_key, "plate.svg"}) == "Voron Plate"); + CHECK(packs.capability_name(PrinterAssetRef{plugin_key, "missing.stl"}).empty()); +}