#ifndef slic3r_PluginManager_hpp_ #define slic3r_PluginManager_hpp_ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "slic3r/plugin/PluginFsUtils.hpp" #include #include #include #include #include #include #include "CloudPluginService.hpp" #include "PluginDescriptor.hpp" #include "PluginLoader.hpp" #include "PluginConfig.hpp" struct _object; using PyObject = _object; namespace pybind11 { class object; } namespace Slic3r { class OrcaCloudServiceAgent; // Explicit result of an unsubscribe-keep-local request. The conversion is committed separately // from the reload so a pending reload is neither success nor failure. For Pending, observe // local_plugin_key through is_plugin_loaded()/subscribe_on_load_callback(); a later failure is // also surfaced as a warning notification. Failed with local_copy_kept=true means the conversion // committed but the reload failed or could not start; reload distinguishes those outcomes. enum class PluginRemovalStatus { Failed, Pending, Succeeded }; enum class PluginReloadStatus { NotNeeded, Running, Succeeded, Failed, Cancelled, Busy }; struct CloudUnsubscribeResult { PluginRemovalStatus status = PluginRemovalStatus::Failed; bool local_copy_kept = false; PluginReloadStatus reload = PluginReloadStatus::NotNeeded; std::string local_plugin_key; // set once the local conversion is committed std::string error; }; // One discovered plugin package: one .py/.whl file -> one descriptor + one Python module + // N materialized capabilities. // // PluginManager holds every discovered plugin in a single std::vector, loaded or not; // module == nullptr means the package was discovered but is not loaded. "What exists" and // "what is live" are therefore the same vector, distinguished by a null check. // // A capability carries its own name, type and enable flag (PluginCapabilityInterface), cached by // the loader at materialization, and its owning package via audit_plugin_key(). Capability state // therefore lives exactly as long as the capability: a package that is not loaded has none. The // only durable record is the .install_state.json sidecar, which the loader seeds enable flags from. // The descriptor holds package state only. struct Plugin { PluginDescriptor descriptor; // All plugin state and metadata lives here. PyObject* module = nullptr; // Python module object, shared by all capabilities. nullptr => not loaded. std::string module_name; // Root name used in sys.modules, including package submodules. std::vector plugin_sys_paths; // Paths added for this plugin load. std::vector plugin_modules; // Plugin-originated sys.modules entries. // Materialized capability instances. Empty unless loaded. std::vector> capabilities; Plugin() = default; Plugin(const Plugin&) = delete; Plugin& operator=(const Plugin&) = delete; // Move transfers module ownership; the moved-from package must not Py_DECREF it. Move // assignment is required: the manager's vector is erased from and reordered. Plugin(Plugin&& other) noexcept : descriptor(std::move(other.descriptor)), module(other.module), module_name(std::move(other.module_name)), plugin_sys_paths(std::move(other.plugin_sys_paths)), plugin_modules(std::move(other.plugin_modules)), capabilities(std::move(other.capabilities)) { other.module = nullptr; } Plugin& operator=(Plugin&& other) noexcept { if (this != &other) { release_module(); descriptor = std::move(other.descriptor); module = other.module; module_name = std::move(other.module_name); plugin_sys_paths = std::move(other.plugin_sys_paths); plugin_modules = std::move(other.plugin_modules); capabilities = std::move(other.capabilities); other.module = nullptr; } return *this; } ~Plugin() { release_module(); } bool is_loaded() const { return module != nullptr; } // Removes the module namespace and plugin-owned sys.path entries before dropping the module // reference. If the interpreter is already finalized, PythonInterpreter deliberately leaves // the raw reference untouched because there is no safe way to DECREF it. void release_module(); }; // Outcome of one Script invocation, delivered to a script completion callback. // // `cancelled` marks a run terminated by PluginManager's own cancellation (plugin unload / shutdown): // expected termination, not a failure. Callers must not surface it as an error nor as a normal // success. `error` carries only genuine user/plugin exceptions; `result` is meaningful when neither // `cancelled` nor a non-empty `error` is set. struct ScriptCompletion { ExecutionResult result; std::string error; bool cancelled = false; }; // One string bucket of PluginPermissions. Used by PluginPermissionMutation. enum class PluginPermissionCategory { FsRead, FsReadWrite, FsCreate, FsDelete, NetworkHttp, NetworkSocket, Process, Events, }; // A granular edit of a plugin's stored permissions, applied to the latest sidecar contents. // Entries are matched verbatim. An empty add/remove list means "change nothing"; the boolean // grants change only when the corresponding optional is engaged. struct PluginPermissionMutation { struct Entry { PluginPermissionCategory category = PluginPermissionCategory::FsRead; std::string value; }; std::vector add; std::vector remove; std::optional threading; std::optional full_access; }; class PluginManager { public: using PluginLifecycleCompleteFn = std::function; using CapabilityLifecycleFn = std::function; static PluginManager& instance(); ~PluginManager(); // Initialize the plugin system, eagerly starting the embedded Python interpreter on the main thread. bool initialize(); // Stop discovery and unload Python plugin objects before Python finalizes. void shutdown(); // Reject new plugin loads. Called early in app teardown, before shutdown() drains. void set_shutting_down(); bool is_shutting_down() const { return m_shutting_down.load(std::memory_order_acquire); } void discover_plugins(bool async = false, bool clear = false); // Manually trigger a manifest-only rescan. Blocks until discovery is complete. void rescan_plugins(); PluginConfig& get_config() { return m_config; } const PluginConfig& get_config() const { return m_config; } bool is_discovery_complete() const; bool is_discovery_in_progress() const; std::string get_discovery_error() const; bool wait_for_discovery(std::chrono::milliseconds timeout, std::string& error) const; std::vector get_plugin_descriptors(bool include_invalid = false) const; // Packages that materialize at least one capability of this type. A package's capability types // are only known once it has been loaded, so a never-loaded package never matches. bool try_get_plugin_descriptor(const std::string& plugin_key, PluginDescriptor& out) const; // Records the installation revision the loader just wrote for a package root. Used so a // later reload compares against the same installation instead of accepting a replacement. void set_plugin_installation_revision(const std::string& plugin_key, const std::string& plugin_root, const std::string& revision); // Same, but only for packages that are loadable (i.e. not an invalid package). bool try_get_valid_plugin_descriptor(const std::string& plugin_key, PluginDescriptor& out) const; // Packages that were present in the previous discovery pass but were not found on disk in the // latest rescan. They are retained until the user explicitly removes them or a later scan finds // them again. std::vector get_missing_plugin_descriptors() const; void remove_missing_plugins(const std::vector& plugin_keys); // Packages whose .install_state.json marks them for auto-load. std::vector get_enabled_plugin_keys() const; // The package owning a loaded capability, for the by-name dispatch path. bool try_get_plugin_descriptor_for_capability(const std::string& capability_name, PluginCapabilityType type, PluginDescriptor& out) const; // The "name;uuid;capability" reference for a loaded capability, as stored in a preset's // "plugins" manifest; std::nullopt when no loaded package provides it. std::optional resolve_capability_ref(const std::string& capability_name, PluginCapabilityType type) const; // Per-plugin storage directory under orca_plugins/plugin_data, created if missing. Throws // std::runtime_error if the plugin is unregistered, the key is invalid, or (cloud plugins) // no user is logged in yet. std::string get_storage_dir(const std::string& plugin_key) const; std::vector> get_plugin_capabilities( const std::string& plugin_key = "", // "" => all plugins PluginCapabilityType type = PluginCapabilityType::Unknown, // Unknown => all types bool only_enabled = true) const; std::shared_ptr get_plugin_capability(const PluginCapabilityId& id, bool only_enabled = true) const; // Try to resolve from just capability name and type from presets. std::shared_ptr get_plugin_capability(const std::string& capability_name, PluginCapabilityType type = PluginCapabilityType::Unknown, bool only_enabled = true) const; // Reads the sidecar under install_state_mutex(), so the result is not interleaved with a // permission write. Returns false when the plugin is unknown or has no readable sidecar. // The lock is reentrant per thread, but new code should still avoid nesting it. bool get_install_state(const std::string& plugin_key, PluginInstallState& install_state); // Applies a granular edit to the plugin's latest sidecar contents in one locked read-modify- // write. Only the named entries and engaged boolean grants change; every other stored grant, // including one another writer added after the caller last read the state, is preserved. // Additions are deduplicated, removals of absent entries are ignored, and empty values are // skipped. Requires a known installed package with a readable sidecar; enabling full access // additionally requires a loadable (non-invalid) package, while disabling it and plain list // edits accept any known installed package. // Accepted while the plugin is loaded or loading; the running audit re-reads the sidecar, so // the edit applies to its next audited operation. On success `applied`, when non-null, // receives the permissions as written. bool mutate_plugin_permissions(const std::string& plugin_key, const PluginPermissionMutation& mutation, PluginPermissions* applied = nullptr); void load_plugin(const std::string& plugin_key, bool skip_deps = false, std::vector capabilities_to_enable = {}); bool unload_plugin(const std::string& plugin_key); void unload_all_plugins(); void unload_cloud_plugins(); bool is_plugin_loaded(const std::string& plugin_key) const; bool is_plugin_load_in_progress(const std::string& plugin_key) const; // True when an in-flight load has been cancelled but its worker has not released the slot yet. // Such a load stays "in progress" for wait_for_all_plugin_loads(), but it is no longer treated // as a live plugin when cancellation is observed. A dialog racing with cancellation may still // appear or remain open, but its answer is discarded unless the commit already won. bool is_plugin_load_cancelled(const std::string& plugin_key) const; void wait_for_all_plugin_loads() const; bool wait_for_all_plugin_loads(std::chrono::milliseconds timeout) const; // false on timeout bool wait_for_plugin_load(const std::string& plugin_key, std::chrono::milliseconds timeout, std::string& error) const; bool cancel_plugin_load(const std::string& plugin_key); std::string get_plugin_load_error(const std::string& plugin_key) const; // True when a discovered plugin's most recent load attempt failed for an ordinary reason. // Cancelling the load, starting another one, unloading the plugin, installing it again, or // removing its package clears it. A discovery rescan leaves it alone, because a rescan does // not prove the executable package changed. A queued runtime prompt stays actionable in this // state, because approving it saves the grant that lets the retry load succeed. bool is_plugin_load_failed(const std::string& plugin_key) const; void set_capability_enabled(const PluginCapabilityId& id, bool enabled); // Sets the cloud user whose _subscribed/{user_id} directory is scanned and installed into. void set_cloud_user(const std::string& user_id); void subscribe_on_load_callback(PluginLifecycleCompleteFn fn); void subscribe_on_unload_callback(PluginLifecycleCompleteFn fn); void subscribe_on_capability_load_callback(CapabilityLifecycleFn fn); void subscribe_on_capability_unload_callback(CapabilityLifecycleFn fn); void set_cloud_agent(std::shared_ptr agent) { m_cloud_service.set_cloud_agent(std::move(agent)); } bool install_plugin(const boost::filesystem::path& filepath, std::string& error); bool install_plugin(const boost::filesystem::path& filepath, PluginDescriptor& plugin_descriptor, std::string& error); bool inspect_local_plugin_package(const boost::filesystem::path& filepath, PluginDescriptor& plugin_descriptor, bool& existing_installation, std::string& error) const; bool set_plugin_error(const std::string& plugin_key, std::string error); bool clear_plugin_error(const std::string& plugin_key); void fetch_plugins_from_cloud(std::vector* out_not_found = nullptr, std::vector* out_unauthorized = nullptr); void update_cloud_metadata(const std::vector& cloud_list); void clear_cloud_plugin_metadata(); bool download_and_install_cloud_plugin(const std::string& plugin_key, const std::string& version, std::string& error); bool subscribe_and_install_cloud_plugin(const std::string& plugin_key, std::string& error); // If the version is empty, take the latest version. The new package is downloaded before the // old one is replaced, so a download failure leaves the installed package and its state intact. // On success the previous per-capability choices are retained while every permission is reset, // and a loaded package is reloaded afterwards; a deactivated one keeps enabled=false in its // sidecar across the restart. A load already in progress makes the update fail instead of // being cancelled by the replacement. A failed install restores the previous permissions and // reloads the old package only when that package is still present at its recorded root; a // committed replacement never inherits them. The install always targets the account the update // started under, and a detected account change aborts before the installed package is touched. bool update_cloud_plugin(const std::string& plugin_key, std::string& error, std::string version = ""); bool delete_plugin(const std::string& plugin_key, std::string& error); // Returns the committed conversion and reload outcome separately. No current UI caller; any // future caller must handle Pending and observe the eventual load result. CloudUnsubscribeResult unsubscribe_cloud_plugin(const std::string& plugin_key); bool delete_and_unsubscribe_cloud_plugin(const std::string& plugin_key, std::string& error); ExecutionResult run_script_capability(const std::string& plugin_key, const std::string& capability_name, std::string& error); // Outcome of launching a Script capability. struct ScriptLaunchResult { bool launched_async = false; // true => a run started off-thread; wait for on_done ScriptCompletion outcome; // meaningful when !launched_async (start failure only) }; // Invoked on the GUI thread when a Script invocation finishes (or inline, on the calling thread, // when the run could not be started at all). using ScriptCompletionFn = std::function; // Starts a Script capability off the caller's thread. Both a synchronous `def execute` and an // `async def execute` run on a ScriptAsyncRuntime worker, so this never blocks the UI thread and // no invocation runs before returning. `launched_async` is true exactly when a run started; the // caller then waits for on_done instead of a returned result. When it is false, `outcome.error` // explains why (the caller's guarded UI normally prevents this). ScriptLaunchResult launch_script_capability(const std::string& plugin_key, const std::string& capability_name, ScriptCompletionFn on_done = {}); void dispatch_lifecycle_event(LifecycleEvent evt, const LifecycleEventContext& ctx); private: PluginManager() = default; PluginManager(const PluginManager&) = delete; PluginManager& operator=(const PluginManager&) = delete; enum class CallbackType { Load, Unload }; // Caller holds m_mutex. The returned pointer is invalidated by any push_back into m_plugins, // so it must never escape the lock. Plugin* find_plugin_locked(const std::string& plugin_key); const Plugin* find_plugin_locked(const std::string& plugin_key) const; void load_plugin_impl(const std::string& plugin_key, bool skip_deps, const std::vector& capabilities_to_enable); // Caller holds m_mutex. Non-empty return means the load must be abandoned. std::string check_registry_locked(const std::string& plugin_key, const Plugin& candidate) const; void run_discovery(bool async, bool clear); void run_discovery_task(bool clear); void merge_discovered_plugins(std::vector discovered, bool clear); // Unload every loaded Plugin matching should_remove, then erase every matching entry (loaded or // not). Unloading runs outside m_mutex (Python teardown and lifecycle callbacks can re-enter the // manager), so the snapshot-unload cycle retries until a pass finds nothing left to unload; the // final check and the erase itself run in one critical section so a concurrent load cannot make a // live entry reach vector compaction and move-assignment. after_erase_locked, if given, runs right // after the erase while m_mutex is still held. void unload_and_erase_if(const std::function& should_remove, const std::function& after_erase_locked = {}); bool cancel_plugin_load_locked(const std::string& plugin_key); bool is_plugin_load_cancelled_locked(const std::string& plugin_key) const; void notify_plugin_load_state_changed(bool changed); // Outcome of a pending keep-local reload, captured under m_mutex so exactly one observer (the // load worker, or the keep-local caller when the load already finished) reports a failure. enum class PendingReloadOwner { Caller, // synchronous keep-local caller takes the outcome after its wait returns Worker, // the load worker reports the eventual outcome }; struct PendingReloadOutcome { bool pending = false; // the mark existed at capture time bool claimed = false; // this caller removed the mark and owns reporting bool in_progress = false; bool update_in_progress = false; bool loaded = false; bool cancelled = false; std::string error; }; // A resolved entry keeps the exact outcome captured when the load released its slot, so a // later retry cannot change what the synchronous caller reports. struct PendingReloadState { PendingReloadOwner owner = PendingReloadOwner::Worker; bool resolved = false; bool update_at_start = false; // an update already owned the key when marked PendingReloadOutcome outcome; }; // Caller holds m_mutex and must not remove the mark. PendingReloadOutcome capture_pending_reload_outcome_locked(const std::string& plugin_key) const; // Caller must not hold m_mutex. Claims an already-finished reload; a running load is marked // for worker reporting and returned as pending, so the caller never reports a running load as // finished. A frozen Caller outcome is returned as-is. PendingReloadOutcome take_finished_pending_reload_outcome(const std::string& plugin_key); // Reports a claimed pending reload outcome outside m_mutex. No-op unless it is a real failure. void report_pending_reload_outcome(const PendingReloadOutcome& outcome); void release_load_slot(const std::string& plugin_key); void cancel_and_wait_for_capabilities( const std::vector>& capabilities); // Snapshot subscribers under m_mutex so they can be invoked without holding it. std::vector copy_callbacks(CallbackType type) const; std::vector copy_capability_callbacks(CallbackType type) const; void run_on_load_callbacks(const std::string& plugin_key); void run_on_unload_callbacks(const std::string& plugin_key); void run_on_capability_load_callbacks(const PluginCapabilityId& id); void run_on_capability_unload_callbacks(const PluginCapabilityId& id); void clear_callbacks(); // Writes the sidecar for a loaded plugin (enabled=true plus the current per-capability flags). void write_loaded_plugin_install_state(const std::string& plugin_key); // Persists enabled=false and mirrors it into the in-memory descriptor. A sidecar that cannot be // read or written is left untouched. void mark_plugin_install_state_disabled(const std::string& plugin_key); // Revoke permissions after a package replacement so the new package must request them again. // Returns false when the sidecar could not be updated, so an install must fail closed instead // of letting new code inherit the replaced package's grants. bool revoke_plugin_permissions(const std::string& plugin_key); // Keep the cloud install directory in step with the signed-in agent, as every cloud install // must land in _subscribed//. void sync_cloud_user_from_agent(); // What a failed cloud package install left behind, for the updater's rollback decision. enum class CloudUpdateFailure { PreviousPackageUsable, // the installer left the previously installed package in place ReplacementInstalled, // the replacement was installed; only the metadata update failed RollbackFailed, // the install target could not be restored; the previous package may // have lived at a different root and is then unaffected }; // Installs a package. The caller holds no manager lock. cloud_user_id_override, when given, is // the account directory resolved and validated by an update; otherwise the current cloud user // is read after the discovery wait. preserved_state, when given, carries the previous // activation and capability choices into the installer's sidecar. mark_error_on_failure is // false when the caller owns the failure (an update that may restore the previous package). bool install_plugin_impl(const boost::filesystem::path& filepath, PluginDescriptor& plugin_descriptor, const std::string* cloud_user_id_override, std::string& error, bool* install_target_intact, const PluginInstallState* preserved_state = nullptr, bool mark_error_on_failure = true, std::shared_ptr package_lease = {}); // Installs an already downloaded cloud package and updates the in-memory descriptor. The // caller owns the package file: it is removed here on both success and failure. cloud_user_id, // when given, is the account directory the caller validated the install target against; // otherwise the current cloud user is used. When the call fails, `failure` (if given) reports // what was left on disk so the caller can decide whether restoring the previous package's // state and reloading it is meaningful; the caller then also owns marking the plugin error. bool install_cloud_plugin_package(const std::string& plugin_key, const std::string& requested_version, const boost::filesystem::path& package_path, const PluginDescriptor& descriptor, const std::string* cloud_user_id, std::string& error, CloudUpdateFailure* failure = nullptr, const PluginInstallState* preserved_state = nullptr, std::shared_ptr package_lease = {}); // Puts back the sidecar (permissions, capability choices and enabled flag) that the unload // step overwrote when a replacement failed and the previous package is still in place. void restore_plugin_state_after_failed_update(const PluginDescriptor& previous, const PluginInstallState& previous_state, bool had_previous_state, bool was_enabled); // Conversion + reload outcome for unsubscribe-keep-local. CloudUnsubscribeResult finalize_cloud_unsubscribe(const PluginDescriptor& plugin); CloudUnsubscribeResult keep_installed_plugin_as_local(const PluginDescriptor& plugin_descriptor); // Removal path used when the local package is deleted, not kept. bool finalize_cloud_plugin_removal(const PluginDescriptor& plugin, std::string& error); bool delete_installed_plugin_package(const PluginDescriptor& plugin, std::string& error); bool m_initialized = false; CloudPluginService m_cloud_service; PluginConfig m_config; // Leaf lock: code holding m_mutex must not call Python, acquire the GIL, invoke lifecycle // callbacks, or re-enter the manager. Live plugin payloads are detached and torn down after // releasing this lock. mutable std::mutex m_mutex; // Every discovered plugin, loaded or not. module == nullptr => not loaded. std::vector m_plugins; std::unordered_set m_missing_plugin_keys; std::unordered_set m_load_in_progress; // Keys owned by an in-flight package update. load_plugin() refuses to start while a key is // here, so the old package cannot be imported while it is unloaded or replaced on disk. The // updater removes the key before it reloads the replacement itself. std::unordered_set m_updates_in_progress; // Keys whose in-flight load has been cancelled. Cancellation does NOT remove the key from // m_load_in_progress: the detached worker is still inside the loader touching Python, and it // releases its own slot only once it has unwound. Dropping the key here would let // wait_for_all_plugin_loads() return early, after which shutdown() unloads everything and // GUI_App finalizes the interpreter — leaving the live worker to run Python against it. std::unordered_set m_cancelled; // Keys whose most recent load attempt failed without being cancelled. Kept separately from // m_load_errors so clearing it never changes the error a load waiter reads. std::unordered_set m_failed_loads; // Keep-local conversions with an unresolved reload. Caller-owned entries are resolved by the // load worker at release and kept for the synchronous caller; Worker-owned entries are // captured and reported by the worker. Only one owner ever reports a failure. std::unordered_map m_pending_local_reloads; std::map m_load_errors; mutable std::condition_variable m_load_cv; // Sidecar readers and writers serialize on Slic3r::install_state_mutex() (PluginFsUtils), // shared with the audit grant writers. Taken before m_mutex, never after it. std::map> m_callbacks; std::map> m_capability_callbacks; bool m_discovery_complete = false; bool m_discovery_in_progress = false; std::string m_discovery_error; mutable std::condition_variable m_discovery_cv; std::string m_cloud_user_id; std::atomic m_shutting_down{false}; }; // ── Async Script execution ────────────────────────────────────────────────────────────────── // // A Script capability whose Python `execute` is an `async def` (or otherwise returns a // coroutine) must not run on the UI thread, and cannot use the synchronous trampoline path, // which casts the return value to ExecutionResult and would reject a coroutine. // // ScriptAsyncRuntime drives such executions off the calling (UI) thread. Each invocation gets its // own worker thread and, for an `async def`, its own asyncio event loop. Every invocation body — // detection, a synchronous `def execute`, or an `async def` coroutine — runs on that worker, so no // Script invocation ever blocks the UI thread and no invocation is queued behind another plugin's. // For the whole invocation the worker holds: // * a shared_ptr to the capability, so the capability and its module stay alive across awaits; // * a PythonRuntimeLease plus the GIL, so the interpreter cannot finalize underneath it; // * the capability's audit scope (ScopedPluginAuditContext), // which keeps plugin unload and interpreter shutdown from tearing the module out from under a // suspended run. Unload cancels the run and drains it (it never force-unloads after a timeout). // // Interface for host awaitables (see plugin/host/): a host awaitable is constructed inside the // Script coroutine, i.e. on the worker thread with that invocation's loop running, so it can // read that loop with asyncio.get_running_loop() or ScriptAsyncRuntime::current_loop(). To // resume from another thread (typically the UI thread) it must resolve its future with // loop.call_soon_threadsafe(...) and must never touch plugin Python objects, or the loop, // directly from that other thread. The loop only runs while the coroutine is suspended inside // run_until_complete; once Script execute returns the loop is closed and the module may unload. class ScriptAsyncRuntime { public: static ScriptAsyncRuntime& instance(); ~ScriptAsyncRuntime(); ScriptAsyncRuntime(const ScriptAsyncRuntime&) = delete; ScriptAsyncRuntime& operator=(const ScriptAsyncRuntime&) = delete; // Starts one Script invocation on its own worker thread. The invocation body (Python `execute`, // whether `def` or `async def`) and its detection both run on that worker, never on the calling // thread. `on_done` is invoked on the GUI thread (or inline when there is no wx app) when the // invocation finishes; a `cancelled` completion is expected termination from cancel_plugin(). // Returns false when the runtime is shutting down. bool start(const std::string& plugin_key, const std::string& capability_name, std::shared_ptr capability, std::function on_done); // Requests cancellation of every active run owned by plugin_key: marks the run and cancels // its asyncio task via loop.call_soon_threadsafe (a synchronous invocation has no loop). void cancel_plugin(const std::string& plugin_key); // True while a run for `capability` is active. bool has_active_run(const PluginCapabilityInterface* capability) const; // Stops accepting runs and waits for every in-flight invocation worker. Nothing is torn down // by force. void shutdown(); // Re-arms the runtime after a shutdown() so a later initialize() in the same process can // start runs again. void reset(); // The asyncio loop of the Script invocation running on the calling thread, or an empty // object when the calling thread is not running one. Must be called with the GIL held. static pybind11::object current_loop(); private: ScriptAsyncRuntime(); struct Impl; std::unique_ptr m_impl; }; // Resolve each configured capability reference to a loaded capability of type T and run `execute`. template void execute_capabilities_from_refs(const ConfigOptionStrings& capabilities, const ConfigOptionStrings* plugins, PluginCapabilityType type, std::function, const PluginCapabilityRef&)> execute) { PluginManager& plugin_mgr = PluginManager::instance(); // Log prefix derived from the capability type so each capability family (Printer connection, // Slicing Pipeline, ...) tags its dispatch diagnostics with its own display name. const std::string tag = plugin_capability_type_display_name(type); const bool has_any = std::any_of(capabilities.values.begin(), capabilities.values.end(), [](const std::string& s) { return !s.empty(); }); if (has_any && !plugin_mgr.wait_for_all_plugin_loads(std::chrono::seconds(10))) { BOOST_LOG_TRIVIAL(warning) << tag << ": timed out waiting for plugin loads; unresolved capabilities will be skipped"; } for (const std::string& capability : capabilities.values) { if (capability.empty()) continue; std::optional ref; if (plugins != nullptr) { for (const std::string& plugin_ref : plugins->values) { auto parsed = Slic3r::parse_capability_ref(plugin_ref); if (parsed && parsed->capability_name == capability) { ref = std::move(parsed); break; } } } // The manifest is derived from the picker value only when that value changes, so it can be // stale or empty (e.g. derived before the plugin finished loading) even though the // capability is loaded now. Resolve it by name instead of silently skipping the step. if (!ref) { ref = plugin_mgr.resolve_capability_ref(capability, type); if (ref) BOOST_LOG_TRIVIAL(warning) << tag << ": capability '" << capability << "' missing from the plugins manifest; resolved by name"; } if (!ref) { BOOST_LOG_TRIVIAL(warning) << tag << ": no plugin reference found for capability '" << capability << "'; skipping"; continue; } const std::string cap_name = ref->capability_name; const std::string plugin_key = ref->uuid.empty() ? ref->name : ref->uuid; // only_enabled = false so that "not loaded" and "loaded but disabled" stay distinguishable // and each keeps its own diagnostic. auto cap = plugin_mgr.get_plugin_capability({type, cap_name, plugin_key}, /*only_enabled=*/false); if (!cap) { BOOST_LOG_TRIVIAL(warning) << tag << ": no loaded capability '" << cap_name << "' for plugin '" << plugin_key << "'; skipping"; continue; } if (!cap->is_enabled()) { BOOST_LOG_TRIVIAL(warning) << tag << ": capability '" << cap_name << "' for plugin '" << plugin_key << "' is disabled; skipping"; continue; } auto plugin_capability = std::dynamic_pointer_cast(cap); if (!plugin_capability) { BOOST_LOG_TRIVIAL(warning) << tag << ": capability '" << cap_name << "' (plugin_key=" << cap->audit_plugin_key() << ") is not a " << plugin_capability_type_to_string(type) << "; skipping"; continue; } execute(plugin_capability, ref.value()); } } } // namespace Slic3r #endif /* slic3r_PluginManager_hpp_ */