#include "PluginsDialog.hpp" #include "GUI.hpp" #include "GUI_App.hpp" #include "slic3r/Utils/NetworkAgent.hpp" #include "I18N.hpp" #include "MsgDialog.hpp" #include "OrcaCloudServiceAgent.hpp" #include "slic3r/GUI/Mcp/AutomationRuntime.hpp" #include "slic3r/plugin/PluginConfig.hpp" #include "slic3r/plugin/PluginFsUtils.hpp" #include "slic3r/plugin/PluginManager.hpp" #include #include #include #include #include #include #include #include #include #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Operations/PluginOps.hpp" #include "slic3r/GUI/PluginPermissionValidation.hpp" #include "slic3r/GUI/PluginSource.hpp" #include "slic3r/GUI/PluginStatus.hpp" #include "slic3r/GUI/Widgets/WebViewHostDialog.hpp" #include "slic3r/GUI/PluginSort.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Slic3r { namespace GUI { namespace { const wxString kDeletePluginTitle = _L("Delete Plugin"); const wxString kUnsubscribeTitle = _L("Unsubscribe"); const wxString kOverwritePluginTitle = _L("Overwrite Plugin"); std::string s_selected_plugin_install_action = "explore"; // The permission validator has already checked the path and its final wildcard. Compare both // its spelling and its resolved location, since a symlink can also point to a filesystem root. bool is_root_tree_permission(const std::string& permission) { if (permission.empty() || permission.back() != '*') return false; const std::string folder = permission.substr(0, permission.size() - 1); if (is_filesystem_root(boost::filesystem::path(folder))) return true; boost::system::error_code ec; const boost::filesystem::path resolved = boost::filesystem::weakly_canonical(boost::filesystem::path(folder), ec); return !ec && is_filesystem_root(resolved); } struct PluginContextAction { std::string id; std::string label; bool enabled = true; bool danger = false; }; struct PluginAvailableActions { bool can_toggle = false; bool toggle_installs_cloud_plugin = false; std::vector context_actions; }; struct PluginCapabilityView { PluginCapabilityId id; bool enabled = false; bool can_toggle = false; bool can_run = false; // Whether the capability supplies its own config UI; every capability is configurable, this only // picks the editor. False for descriptor-only rows: an unloaded plugin has no capabilities yet. bool has_config_ui = false; }; struct PluginChangelogView { std::string version; std::string changelog; long long created_time = 0; }; // View-model for one plugin row in the dialog struct PluginDialogItem { std::string plugin_key; std::string plugin_id; std::string display_name; std::string description; std::string author; std::string version; std::string installed_version; std::string latest_version; std::string sort_version; // Version shown in the row (installed if installed, else latest); used by the Version sort. std::string type_label; std::string type_key; std::string sharing_token; std::string thumbnail_url; std::vector type_labels; std::vector changelog; PluginSource source = PluginSource::Local; PluginStatus status = PluginStatus::Inactive; PluginUpdateStatus update_status = PluginUpdateStatus::Normal; std::string error_text; bool has_error = false; bool is_loaded = false; bool loading = false; bool is_cloud_plugin = false; bool orphaned = false; bool has_local_package = false; bool unauthorized = false; bool has_script_capability = false; bool can_run_script = false; // Runtime capabilities in registration order, or descriptor-only type rows when unloaded. std::vector capabilities; // Grants stored in the plugin's install sidecar. False when the sidecar is missing or unreadable // (e.g. an uninstalled cloud plugin), so the payload reports null instead of empty permissions. PluginPermissions permissions; bool has_permissions = false; PluginAvailableActions available_actions; }; constexpr bool kFetchCloudMeta = true; constexpr bool kUseCurrentCloudMeta = false; // The type of a package's first loaded capability. A package that is not loaded has no type. PluginCapabilityType primary_capability_type_of(PluginManager& manager, const std::string& plugin_key) { const auto capabilities = manager.get_plugin_capabilities(plugin_key, PluginCapabilityType::Unknown, /*only_enabled=*/false); return capabilities.empty() ? PluginCapabilityType::Unknown : capabilities.front()->type(); } std::string to_string(PluginUpdateStatus status); nlohmann::json build_context_actions_payload(const PluginAvailableActions& available_actions); nlohmann::json build_permissions_payload(const PluginPermissions& permissions) { nlohmann::json payload; payload["fs_read"] = permissions.fs_read; payload["fs_readwrite"] = permissions.fs_readwrite; payload["fs_create"] = permissions.fs_create; payload["fs_delete"] = permissions.fs_delete; payload["network_http"] = permissions.network_http; payload["network_socket"] = permissions.network_socket; payload["process"] = permissions.process; payload["threading"] = permissions.threading; payload["events"] = permissions.events; payload["full_access"] = permissions.full_access; payload["tools"] = permissions.tools; return payload; } nlohmann::json build_plugin_payload_item(const PluginDialogItem& dialog_item) { nlohmann::json payload_item; payload_item["plugin_key"] = dialog_item.plugin_key; payload_item["plugin_id"] = dialog_item.plugin_id; payload_item["name"] = dialog_item.display_name; payload_item["description"] = dialog_item.description; payload_item["author"] = dialog_item.author; payload_item["version"] = dialog_item.version; payload_item["type"] = dialog_item.type_label; payload_item["type_key"] = dialog_item.type_key; payload_item["types"] = dialog_item.type_labels; nlohmann::json caps = nlohmann::json::array(); for (const PluginCapabilityView& capability : dialog_item.capabilities) { nlohmann::json c; c["name"] = capability.id.name; c["type"] = PluginConfig::capability_type_label(capability.id.type); c["type_key"] = plugin_capability_type_to_string(capability.id.type); c["enabled"] = capability.enabled; c["can_toggle"] = capability.can_toggle; c["can_run"] = capability.can_run; c["has_config_ui"] = capability.has_config_ui; caps.push_back(std::move(c)); } payload_item["capabilities"] = std::move(caps); // The Config tab's sidebar, built by the shared builder so it stays identical to PluginsConfigDialog's. // Not the `capabilities` array above: that is the list tab's, with enable/run state and descriptor-only // rows the config view has no use for. std::vector config_ids; for (const PluginCapabilityView& capability : dialog_item.capabilities) if (!capability.id.name.empty()) config_ids.push_back(capability.id); payload_item["config_capabilities"] = PluginConfig::capabilities_payload(config_ids); nlohmann::json changelog = nlohmann::json::array(); for (const PluginChangelogView& entry : dialog_item.changelog) { nlohmann::json c; c["version"] = entry.version; c["changelog"] = entry.changelog; c["created_time"] = entry.created_time; changelog.push_back(std::move(c)); } payload_item["changelog"] = std::move(changelog); payload_item["label"] = dialog_item.display_name; payload_item["source"] = to_string(dialog_item.source); payload_item["status"] = to_string(dialog_item.status); payload_item["is_loaded"] = dialog_item.is_loaded; payload_item["error"] = dialog_item.error_text; payload_item["update_status"] = to_string(dialog_item.update_status); payload_item["unauthorized"] = dialog_item.unauthorized; payload_item["context_actions"] = build_context_actions_payload(dialog_item.available_actions); payload_item["update_available"] = dialog_item.update_status == PluginUpdateStatus::UpdateAvailable; payload_item["can_toggle"] = dialog_item.available_actions.can_toggle; payload_item["has_script_capability"] = dialog_item.has_script_capability; payload_item["can_run_script"] = dialog_item.can_run_script; payload_item["sharing_token"] = dialog_item.sharing_token; payload_item["thumbnail_url"] = dialog_item.thumbnail_url; payload_item["installed"] = dialog_item.has_local_package; payload_item["orphaned"] = dialog_item.orphaned; payload_item["installed_version"] = dialog_item.installed_version; payload_item["latest_version"] = dialog_item.latest_version; // Null when the sidecar could not be read: an uninstalled/unreadable plugin has unknown grants, // not no grants. if (dialog_item.has_permissions) payload_item["permissions"] = build_permissions_payload(dialog_item.permissions); else payload_item["permissions"] = nullptr; return payload_item; } std::string to_string(PluginUpdateStatus status) { switch (status) { case PluginUpdateStatus::Normal: return "normal"; case PluginUpdateStatus::UpdateAvailable: return "update_available"; case PluginUpdateStatus::Unauthorized: return "unauthorized"; } return "normal"; } // The row's switch and menu items, from what Ops::plugin_actions() says the row offers. PluginAvailableActions evaluate_action_policy(const PluginDescriptor& descriptor, bool loading) { PluginAvailableActions available_actions; const Ops::PluginActions offered = Ops::plugin_actions(descriptor, loading); available_actions.toggle_installs_cloud_plugin = offered.toggle_installs_cloud_plugin; available_actions.can_toggle = offered.can_toggle; auto add_action = [&available_actions](const char* id, const char* label, bool enabled = true, bool danger = false) { available_actions.context_actions.push_back(PluginContextAction{id, _u8L(label), enabled, danger}); }; if (offered.unsubscribe) add_action("unsubscribe_plugin", L("Unsubscribe"), true, true); else if (offered.remove) add_action("delete_plugin", L("Delete"), true, true); add_action("open_folder", L("Show in folder"), offered.open_folder); if (offered.reinstall) add_action("reinstall_plugin", L("Reinstall")); if (offered.reload) { add_action("reload_plugin", L("Reload")); add_action("clear_cache_reload_plugin", L("Delete cache and reload")); } return available_actions; } PluginDialogItem build_plugin_dialog_item(const PluginDescriptor& descriptor) { PluginDialogItem item; PluginManager& manager = PluginManager::instance(); item.plugin_key = descriptor.plugin_key; item.display_name = descriptor.name; item.description = !descriptor.is_metadata_valid() && descriptor.has_error() ? descriptor.normalized_error() : (descriptor.description.empty() ? _u8L("No description.") : descriptor.description); item.author = descriptor.author; item.version = descriptor.version; item.installed_version = Ops::installed_plugin_version(descriptor); item.latest_version = descriptor.latest_available_version(); item.sort_version = item.installed_version.empty() ? item.latest_version : item.installed_version; // A package that is not loaded has no capabilities, so its row contributes none and does not // expand. const std::vector> capabilities = manager.get_plugin_capabilities(descriptor.plugin_key, PluginCapabilityType::Unknown, /*only_enabled=*/false); const PluginCapabilityType primary_type = capabilities.empty() ? PluginCapabilityType::Unknown : capabilities.front()->type(); item.type_label = plugin_capability_type_to_string(primary_type); item.type_key = plugin_capability_type_to_string(primary_type); // "types" is the display-only compatibility list. Cloud plugins show the raw labels the // service returned (which may not map to real capability types); local plugins derive them // from the capabilities actually loaded. if (descriptor.is_cloud_plugin() && !descriptor.display_types.empty()) { for (const std::string& label : descriptor.display_types) if (std::find(item.type_labels.begin(), item.type_labels.end(), label) == item.type_labels.end()) item.type_labels.push_back(label); } else { for (const auto& capability : capabilities) { const std::string label = PluginConfig::capability_type_label(capability->type()); if (std::find(item.type_labels.begin(), item.type_labels.end(), label) == item.type_labels.end()) item.type_labels.push_back(label); } } for (const PluginChangelog& entry : descriptor.changelog) item.changelog.push_back({entry.version, entry.changelog, entry.created_time}); item.source = Ops::plugin_source(descriptor); item.update_status = descriptor.get_update_status(); item.error_text = descriptor.normalized_error(); item.has_error = descriptor.has_error(); item.is_cloud_plugin = descriptor.is_cloud_plugin(); item.orphaned = descriptor.cloud.has_value() && descriptor.cloud->orphaned; item.has_local_package = descriptor.has_local_package(); item.unauthorized = descriptor.is_unauthorized(); item.is_loaded = manager.is_plugin_loaded(descriptor.plugin_key); item.loading = manager.is_plugin_load_in_progress(descriptor.plugin_key); PluginInstallState install_state; item.has_permissions = manager.get_install_state(descriptor.plugin_key, install_state); if (item.has_permissions) item.permissions = std::move(install_state.permissions); item.has_script_capability = false; for (const auto& capability : capabilities) { item.capabilities.push_back({capability->identity(), capability->is_enabled(), true, false, capability->config_ui_available()}); if (capability->type() == PluginCapabilityType::Script) item.has_script_capability = true; } item.sharing_token = descriptor.sharing_token; item.thumbnail_url = descriptor.thumbnail_url; item.status = resolve_plugin_status(item.loading, item.has_error, item.is_loaded); item.available_actions = evaluate_action_policy(descriptor, item.loading); const bool has_enabled_script = std::any_of(item.capabilities.begin(), item.capabilities.end(), [](const PluginCapabilityView& capability) { return capability.id.type == PluginCapabilityType::Script && capability.enabled; }); item.can_run_script = descriptor.is_metadata_valid() && !descriptor.has_error() && item.has_script_capability && item.is_loaded && !item.loading && has_enabled_script; for (PluginCapabilityView& capability : item.capabilities) { capability.can_run = item.can_run_script && capability.id.type == PluginCapabilityType::Script && capability.enabled; } return item; } const PluginContextAction* find_context_action(const PluginAvailableActions& available_actions, const std::string& action_id) { const auto it = std::find_if(available_actions.context_actions.begin(), available_actions.context_actions.end(), [&action_id](const PluginContextAction& action) { return action.id == action_id; }); return it != available_actions.context_actions.end() ? &(*it) : nullptr; } nlohmann::json build_context_actions_payload(const PluginAvailableActions& available_actions) { nlohmann::json payload = nlohmann::json::array(); for (const PluginContextAction& action : available_actions.context_actions) { nlohmann::json item; item["id"] = action.id; item["label"] = action.label; item["enabled"] = action.enabled; item["danger"] = action.danger; payload.push_back(std::move(item)); } return payload; } // The outcome of an operation run behind a progress dialog, handed from its worker to its completion. struct PluginOperationState { std::mutex mutex; std::optional> outcome; }; void store_plugin_operation_result(const std::shared_ptr& state, Ops::Outcome outcome) { std::lock_guard lock(state->mutex); state->outcome.emplace(std::move(outcome)); } // The worker's outcome; none where it ended without one (it threw). std::optional> take_plugin_operation_result(const std::shared_ptr& state) { std::lock_guard lock(state->mutex); return state->outcome; } // A full-access or permission-save request carries an opaque correlation token that the webview // ties to its pending operation. Bound the shape so a malformed or oversized value cannot be // echoed back: non-empty, at most 128 bytes, printable ASCII only. bool is_valid_bridge_request_id(const std::string& request_id) { constexpr size_t kMaxRequestIdLength = 128; if (request_id.empty() || request_id.size() > kMaxRequestIdLength) return false; return std::all_of(request_id.begin(), request_id.end(), [](unsigned char c) { return c >= 0x21 && c <= 0x7e; }); } // Reports every permission mutation outcome, including rejection and cancelled confirmation. void send_permissions_result(WebViewHostDialog& dialog, const std::string& plugin_key, const std::string& request_id, bool success) { nlohmann::json payload; payload["command"] = "plugin_permissions_result"; payload["plugin_key"] = plugin_key; payload["request_id"] = request_id; payload["success"] = success; dialog.call_web_handler(payload); } } // namespace // ── Dialog-independent plugin actions (also used by the speed dial) ─────────────────────────── namespace { // Snapshot of the currently-known cloud plugin descriptors, used to refresh metadata without a // network round-trip (kUseCurrentCloudMeta). std::vector current_cloud_metadata_snapshot() { std::vector cloud_entries; for (const PluginDescriptor& entry : PluginManager::instance().get_plugin_descriptors(/*include_invalid=*/true)) if (entry.is_cloud_plugin()) cloud_entries.push_back(entry); return cloud_entries; } } // namespace void refresh_plugin_metadata_blocking(bool fetch_cloud) { PluginManager& manager = PluginManager::instance(); std::vector not_found, unauthorized; const std::vector current_cloud_metadata = fetch_cloud ? std::vector{} : current_cloud_metadata_snapshot(); manager.rescan_plugins(); if (!fetch_cloud) { manager.update_cloud_metadata(current_cloud_metadata); return; } manager.fetch_plugins_from_cloud(¬_found, &unauthorized); wxGetApp().CallAfter([not_found = std::move(not_found), unauthorized = std::move(unauthorized)]() { if (wxGetApp().is_closing()) return; Plater* plater = wxGetApp().plater(); if (plater == nullptr) return; for (const auto& uuid : not_found) plater->get_notification_manager()->push_notification(NotificationType::CustomNotification, NotificationManager::NotificationLevel::RegularNotificationLevel, format(_L("Plugin %s is no longer available."), uuid)); for (const auto& uuid : unauthorized) plater->get_notification_manager()->push_notification(NotificationType::CustomNotification, NotificationManager::NotificationLevel::RegularNotificationLevel, format(_L("Plugin %s access is unauthorized."), uuid)); }); } void open_plugin_hub() { std::string cloud_base_url = "https://cloud.orcaslicer.com"; if (wxGetApp().getAgent()) { auto orca_agent = std::dynamic_pointer_cast(wxGetApp().getAgent()->get_cloud_agent()); if (orca_agent && !orca_agent->get_cloud_base_url().empty()) cloud_base_url = orca_agent->get_cloud_base_url(); } while (!cloud_base_url.empty() && cloud_base_url.back() == '/') cloud_base_url.pop_back(); if (cloud_base_url.empty()) cloud_base_url = "https://cloud.orcaslicer.com"; wxLaunchDefaultBrowser(wxString::FromUTF8(cloud_base_url + "/app/plugins/plugin-hub")); } bool install_local_plugin_package(const boost::filesystem::path& package_file, wxWindow* parent, wxString& message, std::optional overwrite, std::optional* refused) { message.clear(); if (package_file.empty()) return false; // ---- pre-flight (main thread): validate + inspect + overwrite prompt ---- const wxString package_name = from_u8(package_file.filename().string()); std::string extension = package_file.extension().string(); std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char ch) { return static_cast(std::tolower(ch)); }); if (extension != ".py" && extension != ".whl") { message = _L("Select a .py or .whl plugin package."); return false; } // The message is the package's own error, which says what to fix in it. Each reason arrives framed as a // failed install ("Plugin installation failed: ...") by the code that made it, so none is framed here. const auto failed = [&](const std::string& reason) { BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": Plugin package installation failed for " << package_file << " error=" << reason; message = reason.empty() ? _L("Failed to install plugin package. See the log for details.") : from_u8(reason); return false; }; PluginDescriptor plugin_descriptor; bool existing_installation = false; std::string error; try { if (!PluginManager::instance().inspect_local_plugin_package(package_file, plugin_descriptor, existing_installation, error)) return failed(error); } catch (const std::exception& ex) { return failed(GUI::format(_u8L("Plugin installation failed: %1%"), ex.what())); } catch (...) { return failed({}); } if (existing_installation && overwrite == false) { const std::string plugin_name = plugin_descriptor.name.empty() ? package_file.filename().string() : plugin_descriptor.name; // The overwrite prompt's question is the reason. const Ops::Refusal installed{Ops::RefusalKind::Precondition, "plugin_installed", // TRN %s is a plugin's name. L("Plugin \"%s\" is already installed.\n\n" "Installing this package will overwrite the existing plugin."), {plugin_name}}; message = installed.translated(); if (refused != nullptr) *refused = installed; return false; } if (existing_installation && !overwrite) { const wxString plugin_name = from_u8(plugin_descriptor.name.empty() ? package_file.filename().string() : plugin_descriptor.name); // Orca's own message dialog rather than a native box, which dialog_answer can't press on every platform. MessageDialog dialog(parent, wxString::Format(_L("Plugin \"%s\" is already installed.\n\nInstalling this package will overwrite the existing plugin."), plugin_name), kOverwritePluginTitle, wxOK | wxCANCEL | wxICON_WARNING); dialog.SetButtonLabel(wxID_OK, _L("Overwrite")); dialog.SetButtonLabel(wxID_CANCEL, _L("Cancel"), /*set_focus=*/true); if (dialog.ShowModal() != wxID_OK) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Plugin package installation cancelled before overwrite. package=" << package_file << " plugin=" << plugin_descriptor.name; return false; // cancelled: message stays empty so callers stay silent } } // ---- install + refresh on a worker behind a modal progress dialog (keeps the UI live) ---- bool installed = false; { struct Result { std::mutex mutex; bool ok = false; std::string error; }; auto state = std::make_shared(); detail::run_wait_with_progress( [state, package_file]() { std::string error; bool ok = false; try { ok = PluginManager::instance().install_plugin(package_file, error); } catch (const std::exception& ex) { error = GUI::format(_u8L("Plugin installation failed: %1%"), ex.what()); } catch (...) { error.clear(); } if (ok) { // Reflect the new package in discovery/cloud metadata without blocking the caller. try { refresh_plugin_metadata_blocking(kUseCurrentCloudMeta); } catch (...) {} } std::lock_guard lock(state->mutex); state->ok = ok; state->error = std::move(error); }, parent, _L("Installing plugin"), _L("Installing plugin") + ": " + package_name, 100, wxPD_APP_MODAL | wxPD_AUTO_HIDE | wxPD_ELAPSED_TIME, /*alive=*/nullptr, /*restore=*/{}); std::lock_guard lock(state->mutex); installed = state->ok; error = std::move(state->error); } if (!installed) return failed(error); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Plugin package installed successfully from " << package_file; const wxString installed_name = from_u8(plugin_descriptor.name.empty() ? package_file.filename().string() : plugin_descriptor.name); message = wxString::Format(_L("Installed \"%s\"."), installed_name); return true; } PluginsDialog::PluginsDialog(wxWindow* parent, wxWindowID id, const wxString&, const wxPoint& pos, const wxSize& size, long style) : WebViewHostDialog(parent, id, _L("Plugins"), pos, size, style) { create_webview("web/dialog/PluginsDialog/index.html", _L("Plugins"), wxSize(900, 820), wxSize(760, 715)); } nlohmann::json PluginsDialog::localized_strings() const { return { {"search_plugins", _u8L("Search plugins")}, {"clear", _u8L("Clear")}, {"clear_search", _u8L("Clear search")}, {"match_case", _u8L("Match case")}, {"match_whole_word", _u8L("Match whole word")}, {"refresh", _u8L("Refresh")}, {"install_options", _u8L("More plugin install options")}, {"install_plugin", _u8L("Install plugin")}, {"install_local_plugin", _u8L("Install local plugin")}, {"activate", _u8L("Activate")}, {"sort_by_name", _u8L("Sort by name")}, {"name", _u8L("Name")}, {"sort_by_version", _u8L("Sort by version")}, {"plugin_version", _u8L("Plugin Version")}, {"sort_by_source", _u8L("Sort by source")}, {"source", _u8L("Source")}, {"sort_by_status", _u8L("Sort by status")}, {"status", _u8L_CONTEXT("Status", "Plugin")}, {"resize_hint", _u8L("Drag to resize; double-click to reset")}, {"resize_list", _u8L("Resize the plugin list")}, {"details_label", _u8L("Plugin details")}, {"tab_info", _u8L("Plugin Info")}, {"description", _u8L("Description")}, {"tab_config", _u8L("Config")}, {"tab_changelog", _u8L("Changelog")}, {"tab_diagnostics", _u8L("Diagnostics")}, {"types", _u8L("Types")}, {"author", _u8L("Author")}, {"installed_version", _u8L("Installed Version")}, {"latest_version", _u8L("Latest Version")}, {"update_available", _u8L("Update available")}, {"update_title", _u8L("Update to the latest version")}, {"update", _u8L("Update")}, {"no_description", _u8L("No description available")}, {"config_select_plugin", _u8L("Select a plugin to configure its capabilities")}, {"configurable_capabilities", _u8L("Configurable capabilities")}, {"config_json_label", _u8L("Capability configuration (JSON)")}, {"config_frame_title", _u8L("Plugin configuration")}, {"restore_title", _u8L("Discard the settings saved for this capability and restore the plugin's defaults")}, {"restore_defaults", _u8L("Restore defaults")}, {"save", _u8L("Save")}, {"changelog_label", _u8L("Plugin changelog")}, {"version", _u8L("Version")}, {"date", _u8L("Date")}, {"changes", _u8L("Changes")}, {"no_changelog", _u8L("No changelog available")}, {"no_issues", _u8L("No issues detected")}, {"no_plugins", _u8L("No plugins found")}, {"no_match", _u8L("No plugins match \"%s\"")}, {"source_mine", _u8L("Mine")}, {"source_subscribed", _u8L_CONTEXT("Subscribed", "Plugin")}, {"source_orphaned", _u8L("Orphaned")}, {"source_local", _u8L_CONTEXT("Local", "Plugin")}, {"mixed_capabilities", _u8L("Some plugin capabilities are enabled")}, {"collapse_named", _u8L("Collapse %s capabilities")}, {"expand_named", _u8L("Expand %s capabilities")}, {"collapse", _u8L("Collapse capabilities")}, {"expand", _u8L("Expand capabilities")}, {"open_in_browser", _u8L("Open this plugin in your browser")}, {"capability_count", _u8L("Capabilities: %s")}, {"capabilities", _u8L_CONTEXT("Capabilities", "Plugin")}, {"permissions_tab", _u8L("Permissions")}, {"permissions_unavailable", _u8L("Permissions are unavailable.")}, {"permissions_fs_read", _u8L("File system read")}, {"permissions_fs_readwrite", _u8L("File system read and write")}, {"permissions_network_http", _u8L("HTTP network")}, {"permissions_network_socket", _u8L("Network sockets")}, // TRN Operating system processes a plugin may start, not print process presets. {"permissions_process", _u8L_CONTEXT("Processes", "Permission category")}, {"permissions_threading", _u8L("Threading")}, {"permissions_events", _u8L_CONTEXT("Events", "Permission category")}, {"permissions_filesystem_help", _u8L("Enter an absolute path on this computer. Add /* at the end to include the folder and everything below it; no other wildcard is accepted. A read/write grant can create files through open(), but does not cover create or delete events such as os.mkdir and os.remove.")}, {"permissions_create", _u8L_CONTEXT("Create", "Permission access")}, {"permissions_delete", _u8L_CONTEXT("Delete", "Permission access")}, {"permissions_create_name", _u8L("File system: Create")}, {"permissions_delete_name", _u8L("File system: Delete")}, {"permissions_folder_modes_help", _u8L("Choose none, selected folders, or all folders. Enter an absolute folder path to allow operations directly inside it, or add /* to include all nested folders. No other wildcard is accepted. Delete access allows deleting files and folders inside the granted scope; deleting the granted folder itself requires access to its parent. Some folders are allowed automatically, while protected paths remain blocked. Other operations may require approval. A background operation needing approval is denied first; after approval, a retry may succeed.")}, {"permissions_mode_none", _u8L_CONTEXT("None", "Permission access")}, {"permissions_mode_partial", _u8L("Selected folders")}, {"permissions_mode_full", _u8L("All folders")}, {"permissions_folder_placeholder", _u8L("Absolute folder path")}, {"permissions_folder_empty", _u8L("Add a folder to save selected-folder access. No selected folders are saved until you add one.")}, {"permissions_folder_invalid_wildcard", _u8L("The wildcard is ignored when combined with folder paths. Remove it or choose all folders.")}, #ifdef _WIN32 {"permissions_filesystem_placeholder", _u8L("C:\\path\\to\\directory\\*")}, #else {"permissions_filesystem_placeholder", _u8L("/path/to/directory/*")}, #endif {"permissions_network_access_guidance", _u8L("Enter a full http:// or https:// URL; only its scheme and host are saved, so the grant covers every port, path, and query on that host. A network socket grant also accepts a bare host name or IP address, with or without a port, and covers every port on that host. Other schemes are not accepted. Grants in either list are checked for HTTP and socket access.")}, {"permissions_process_help", _u8L("Executable grants cover all arguments. CommandLine: entries cover only the exact command line.")}, {"permissions_process_placeholder", _u8L("Executable or command name")}, {"permissions_threading_help_short", _u8L("Allow this plugin to create threads.")}, // TRN The name of a plugin permission: calling OrcaSlicer's tools, the commands AI agents call (MCP tools). {"permissions_tools", _u8L("OrcaSlicer tools")}, {"permissions_tools_help_short", _u8L("Allow this plugin to call OrcaSlicer's tools, as AI agents do: change your project, presets and files, run post-processing scripts, and answer dialogs, permission requests included.")}, {"permissions_events_help", _u8L("Enter a category and event separated by a colon, such as Socket:socket.__new__.")}, {"permissions_events_placeholder", _u8L("Socket:socket.__new__")}, {"permissions_full_access_label", _u8L("Full access")}, {"permissions_group_filesystem", _u8L("File system")}, {"permissions_network_access_title", _u8L("Network access")}, {"permissions_group_execution", _u8L("Execution")}, {"permissions_group_events", _u8L("Audit events")}, {"permissions_files_folders", _u8L("Files and folders")}, {"permissions_access_read", _u8L_CONTEXT("Read", "Permission access")}, {"permissions_access_readwrite", _u8L_CONTEXT("Read and write", "Permission access")}, {"permissions_read_unavailable", _u8L("Read permissions are unavailable.")}, {"permissions_readwrite_unavailable", _u8L("Read and write permissions are unavailable.")}, {"permissions_filesystem_read_name", _u8L("File system: Read")}, {"permissions_filesystem_readwrite_name", _u8L("File system: Read and write")}, {"permissions_full_access_help", _u8L("Full access bypasses permission checks. The plugin can read and write most files you can access; modifying startup or application files can let code run outside these checks. Direct Python access to OrcaSlicer's configuration, secret, certificate and install-state paths stays blocked, but subprocesses are not restricted.")}, {"permissions_full_access_editor_disabled", _u8L("Permission list editing is disabled while full access is on.")}, {"permissions_full_access_unavailable", _u8L("Full access status is unavailable.")}, {"permissions_values_empty", _u8L("No values added.")}, {"permissions_apply", _u8L_CONTEXT("Apply", "Permission value")}, {"permissions_apply_value_label", _u8L("Apply value for %s")}, {"permissions_install_to_edit", _u8L("Install this plugin to edit its permissions.")}, {"permissions_add_value_label", _u8L("New value for %s")}, {"permissions_edit_value_label", _u8L("Edit value for %s")}, {"permissions_add", _u8L_CONTEXT("Add", "Permission value")}, {"permissions_add_label", _u8L("Add value to %s")}, // TRN %s is the original permission value that was removed outside this dialog. {"permissions_edit_no_longer_granted", _u8L("The original value is no longer granted: %s. Add the edited value or discard it.")}, // TRN %s is the original permission value before the user's unsaved edit. {"permissions_edit_original", _u8L("Unsaved edit of: %s")}, {"permissions_discard", _u8L("Discard")}, // TRN %s is the original permission value whose unsaved edit will be discarded. {"permissions_discard_edit_label", _u8L("Discard edit of %s")}, {"permissions_remove", _u8L_CONTEXT("Remove", "Permission value")}, {"permissions_remove_label", _u8L("Remove %s")}, {"run_named", _u8L("Run \"%s\"")}, {"enable_named", _u8L("Enable %s")}, {"not_available", _u8L("N/A")}, {"unauthorized", _u8L("Unauthorized for updates")}, {"not_installed", _u8L("Not installed")}, {"config_loading", _u8L("Loading the plugin…")}, {"config_no_capabilities", _u8L("This plugin exposes no capabilities")}, {"config_activate", _u8L("Activate this plugin to configure its capabilities")}, {"invalid_json", _u8L("Invalid JSON")}, {"view_on_cloud", _u8L("View on OrcaCloud here")}, {"status_activated", _u8L("Activated")}, {"status_loading", _u8L("Loading")}, {"status_error", _u8L("Error")}, {"status_runtime_error", _u8L("Runtime error")}, {"status_inactive", _u8L("Inactive")}, {"status_activated_desc", _u8L("This plugin is active and ready to be used.")}, {"status_loading_desc", _u8L("This plugin is still loading.")}, {"status_error_desc", _u8L("This plugin is blocked until its error is fixed.")}, {"status_runtime_error_desc", _u8L("This plugin is loaded but a capability reported an error.")}, {"status_inactive_desc", _u8L("This plugin is inactive. Activate it to install or load it.")}, {"select_plugin", _u8L("Select a plugin to view its status and details.")}, {"orphaned_note", _u8L("Orphaned: This plugin is no longer subscribed or available in OrcaCloud. The local copy remains installed and can still be used.")}, {"newer_version_note", _u8L("A newer plugin version is available.")}, {"unauthorized_note", _u8L("Cloud updates are unavailable because this plugin is unauthorized for updates.")}, }; } PluginsDialog::~PluginsDialog() { m_alive->store(false, std::memory_order_release); } void PluginsDialog::set_open_terminal_dlg_fn() { m_open_terminal_dlg_fn = [] { wxGetApp().open_terminal_dialog(); }; } void PluginsDialog::update_plugin_dialog_ui() { // Called after the any metadata is already updated, for example from the // cloud-plugin state callback. Do not fetch here or the callback can re-enter. send_plugins(); resolve_pending_activation(); } void PluginsDialog::refresh_permissions_if_visible() { if (IsShown() && !IsBeingDeleted()) send_plugins(); } void PluginsDialog::resolve_pending_activation() { if (m_activating_plugin_key.empty()) return; PluginManager& manager = PluginManager::instance(); if (manager.is_plugin_load_in_progress(m_activating_plugin_key)) return; // Still loading: keep the "Activating..." message until the load resolves. const std::string plugin_key = m_activating_plugin_key; m_activating_plugin_key.clear(); // Mirror the row's status precedence (Error before Activated) so the message matches the list. PluginDescriptor descriptor; if (get_descriptor(plugin_key, descriptor) && descriptor.has_error()) show_status(wxString::Format(_L("Failed to activate \"%s\"."), plugin_display_name(plugin_key)), "error"); else if (manager.is_plugin_loaded(plugin_key)) show_status(wxString::Format(_L("Activated \"%s\"."), plugin_display_name(plugin_key)), "success"); // Otherwise it ended up inactive (toggled off or cancelled mid-load): stay silent. } void PluginsDialog::on_script_message(const nlohmann::json& payload) { if (handle_common_script_command(payload)) return; // Defer command handling out of the webview script-message callback: GTK and macOS // deliver it synchronously inside the native webview callback (see ui_create_window // in PluginHostUi.cpp), and window work on that stack is the crash class fixed in // b779a7bfed/f2ccbfc8b5. Deferring here keeps every command handler in THIS dialog off // that stack; it is not a guarantee for other WebViewHostDialog subclasses, which each // have to defer for themselves (PluginsConfigDialog does; others still do not). wxGetApp().CallAfter([this, alive = m_alive, payload]() { if (alive->load(std::memory_order_acquire)) handle_web_command(payload); }); } void PluginsDialog::handle_web_command(const nlohmann::json& payload) { const std::string command = payload.value("command", ""); if (command == "request_plugins") { send_plugins(); } else if (command == "refresh_plugins") { refresh_plugins(); } else if (command == "toggle_plugin") { toggle_plugin(payload.value("plugin_key", ""), payload.value("enabled", false)); } else if (command == "toggle_plugin_capability") { toggle_plugin_capability(payload.value("plugin_key", ""), plugin_capability_type_from_string(payload.value("capability_type", "")), payload.value("capability_name", ""), payload.value("enabled", false)); } else if (command == "install_local_plugin") { install_plugin_from_file(); } else if (command == "plugin_menu_action") { handle_plugin_menu_action(payload.value("plugin_key", ""), payload.value("action", "")); } else if (command == "run_script_plugin_capability") { run_script_plugin_capability(payload.value("plugin_key", ""), payload.value("capability_name", "")); } else if (command == "open_terminal") { m_open_terminal_dlg_fn(); } else if (command == "update_plugin") { update_plugin(payload.value("plugin_key", "")); } else if (command == "open_plugin_on_cloud") { open_plugin_on_cloud(payload.value("sharing_token", "")); } else if (command == "open_plugin_hub") { open_plugin_hub(); } else if (command == "set_plugin_sort") { set_plugin_sort(payload.value("sort_key", ""), payload.value("sort_order", "")); } else if (command == "get_capability_config" || command == "save_capability_config" || command == "restore_capability_config") { const PluginCapabilityId id{plugin_capability_type_from_string(payload.value("capability_type", "")), payload.value("capability_name", ""), payload.value("plugin_key", "")}; if (command == "get_capability_config") { send_capability_config(id); return; } if (command == "restore_capability_config") { restore_capability_config(id); return; } // `config` is a JSON string from the default editor's textarea, or an already-structured // value from a capability's custom UI. Both land here; save_capability_config sorts it out. save_capability_config(id, payload.contains("config") ? payload.at("config") : nlohmann::json::object()); } else if (command == "mutate_plugin_permission") { mutate_plugin_permission(payload); } else if (command == "set_plugin_install_action") { const std::string action = payload.value("action", ""); if (action == "explore" || action == "install-local") s_selected_plugin_install_action = action; } } void PluginsDialog::send_plugins() { call_web_handler(build_plugins_payload()); } void PluginsDialog::set_plugin_sort(const std::string& sort_key, const std::string& sort_order) { m_plugin_sort_key = plugin_sort_key_from_string(sort_key, m_plugin_sort_key); m_plugin_sort_order = plugin_sort_order_from_string(sort_order, m_plugin_sort_order); send_plugins(); } nlohmann::json PluginsDialog::build_plugins_payload() const { nlohmann::json response; response["command"] = "list_plugins"; response["install_action"] = s_selected_plugin_install_action; response["sort_key"] = to_string(m_plugin_sort_key); response["sort_order"] = to_string(m_plugin_sort_order); response["data"] = nlohmann::json::array(); const auto rows = PluginManager::instance().get_plugin_descriptors(/*include_invalid=*/true); BOOST_LOG_TRIVIAL(info) << "Prepared " << rows.size() << " plugin rows for Plugins dialog"; std::vector items; items.reserve(rows.size()); for (const PluginDescriptor& row : rows) items.push_back(build_plugin_dialog_item(row)); sort_plugin_items_for_dialog(items, m_plugin_sort_key, m_plugin_sort_order); for (const PluginDialogItem& item : items) response["data"].push_back(build_plugin_payload_item(item)); return response; } bool PluginsDialog::get_descriptor(const std::string& plugin_key, PluginDescriptor& descriptor) const { return Ops::plugin_descriptor(plugin_key, descriptor); } void PluginsDialog::refresh_plugin_metadata_async(const wxString& title, const wxString& message, bool fetch_cloud) { run_with_dialog([fetch_cloud]() { refresh_plugin_metadata_blocking(fetch_cloud); }, [this]() { prompt_for_missing_plugins(); send_plugins(); }, title, message); } void PluginsDialog::prompt_for_missing_plugins() { PluginManager& manager = PluginManager::instance(); const std::vector missing = manager.get_missing_plugin_descriptors(); if (missing.empty()) return; wxString names; std::vector keys; keys.reserve(missing.size()); for (const PluginDescriptor& plugin : missing) { keys.push_back(plugin.plugin_key); names += "\n- "; names += plugin_display_name(plugin.plugin_key); } const int result = wxMessageBox( wxString::Format(_L("The following installed plugins were not found on disk:\n%s\n\nRemove them from OrcaSlicer?"), names), _L("Missing Plugins"), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING, this); restore_z_order(); if (result == wxYES) manager.remove_missing_plugins(keys); } void PluginsDialog::refresh_plugins() { BOOST_LOG_TRIVIAL(info) << "Refreshing plugins from Plugins dialog"; refresh_plugin_metadata_async(_L("Refreshing"), _L("Refreshing plugins data"), kFetchCloudMeta); } bool PluginsDialog::prompt_enable_full_access(const std::string& plugin_key) { const wxString plugin_name = plugin_display_name(plugin_key); MessageDialog dialog( this, wxString::Format( _L("Enable full access for \"%s\"?\n\n" "Full access turns off permission auditing for this plugin: its file system, network, " "process, thread, event and OrcaSlicer tools permissions are no longer checked. The plugin " "can read and write most files your user account can access, including startup scripts, SSH keys " "and a writable OrcaSlicer installation. Modifying startup or application files can " "let code run outside these checks. Direct Python access to OrcaSlicer's " "configuration, secret, certificate and install-state paths stays blocked, but " "subprocesses are not restricted. Full access is not a sandbox.\n\n" "Only enable this for a plugin you trust."), plugin_name), _L("Full access"), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING); // MsgDialog builds its own buttons in a fixed order and always gives Yes the initial focus; // wxNO_DEFAULT does not change that. Focus No explicitly so Enter cannot grant full access. dialog.SetButtonLabel(wxID_NO, _L("No"), /*set_focus=*/true); const int rc = dialog.ShowModal(); restore_z_order(); return rc == wxID_YES; } void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload) { const auto string_field = [&payload](const char* key) -> std::string { return payload.contains(key) && payload.at(key).is_string() ? payload.at(key).get() : std::string{}; }; const std::string plugin_key = string_field("plugin_key"); const std::string request_id = string_field("request_id"); const std::string operation = string_field("operation"); const std::string category = string_field("category"); const auto finish = [&](bool success) { send_plugins(); send_permissions_result(*this, plugin_key, is_valid_bridge_request_id(request_id) ? request_id : std::string{}, success); }; const auto invalid = [&]() { show_status(_L("Invalid permission save request."), "error"); finish(false); }; if (plugin_key.empty() || !is_valid_bridge_request_id(request_id)) { invalid(); return; } PluginInstallState stored; if (!PluginManager::instance().get_install_state(plugin_key, stored)) { show_status(_L("Install this plugin to edit its permissions."), "warn"); finish(false); return; } PluginPermissionMutation mutation; const wxString plugin_name = plugin_display_name(plugin_key); PluginPermissionCategory bucket = PluginPermissionCategory::FsRead; const std::vector* entries = nullptr; if (category == "fs_read") { bucket = PluginPermissionCategory::FsRead; entries = &stored.permissions.fs_read; } else if (category == "fs_readwrite") { bucket = PluginPermissionCategory::FsReadWrite; entries = &stored.permissions.fs_readwrite; } else if (category == "fs_create") { bucket = PluginPermissionCategory::FsCreate; entries = &stored.permissions.fs_create; } else if (category == "fs_delete") { bucket = PluginPermissionCategory::FsDelete; entries = &stored.permissions.fs_delete; } else if (category == "network_http") { bucket = PluginPermissionCategory::NetworkHttp; entries = &stored.permissions.network_http; } else if (category == "network_socket") { bucket = PluginPermissionCategory::NetworkSocket; entries = &stored.permissions.network_socket; } else if (category == "process") { bucket = PluginPermissionCategory::Process; entries = &stored.permissions.process; } else if (category == "events") { bucket = PluginPermissionCategory::Events; entries = &stored.permissions.events; } if (category == "full_access" || category == "threading" || category == "tools") { if (operation != "set" || !payload.contains("value") || !payload.at("value").is_boolean()) { invalid(); return; } const bool enabled = payload.at("value").get(); if (category == "full_access") { if (enabled && !prompt_enable_full_access(plugin_key)) { finish(false); return; } mutation.full_access = enabled; } else if (category == "tools") { mutation.tools = enabled; } else { mutation.threading = enabled; } } else if ((category == "fs_create" || category == "fs_delete") && operation == "set_mode") { const std::string mode = string_field("value"); if (mode != "none" && mode != "partial" && mode != "full") { invalid(); return; } if (mode == "full" && !(entries->size() == 1 && entries->front() == "*")) { const wxString message = category == "fs_delete" ? wxString::Format(_L("Allow \"%s\" to delete entries in all folders?\n\n" "This includes deleting existing files and folders accessible to your account. " "Protected paths remain blocked. Only allow this for a plugin you trust."), plugin_name) : wxString::Format(_L("Allow \"%s\" to create entries in all folders?\n\n" "This includes creating files and folders accessible to your account. " "Protected paths remain blocked. Only allow this for a plugin you trust."), plugin_name); MessageDialog dialog(this, message, _L("All folders"), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING); dialog.SetButtonLabel(wxID_NO, _L("No"), /*set_focus=*/true); const int result = dialog.ShowModal(); restore_z_order(); if (result != wxID_YES) { finish(false); return; } // A permission prompt may have saved another grant while this dialog was open. if (!PluginManager::instance().get_install_state(plugin_key, stored)) { show_status(_L("Failed to save permissions."), "error"); finish(false); return; } } for (const std::string& entry : *entries) mutation.remove.push_back({bucket, entry}); if (mode == "full") mutation.add.push_back({bucket, "*"}); } else { if (!entries || (operation != "add" && operation != "remove" && operation != "replace") || (operation != "add" && (!payload.contains("old_value") || !payload.at("old_value").is_string())) || (operation != "remove" && (!payload.contains("value") || !payload.at("value").is_string()))) { invalid(); return; } if (operation != "add") { const std::string old_value = string_field("old_value"); if (std::find(entries->begin(), entries->end(), old_value) == entries->end()) { invalid(); return; } mutation.remove.push_back({bucket, old_value}); // A mixed list does not grant full access, but removing its last folder would turn // the remaining wildcard into a full grant. Remove the wildcard as well. if (operation == "remove" && (category == "fs_create" || category == "fs_delete") && entries->size() == 2 && old_value != "*" && std::find(entries->begin(), entries->end(), "*") != entries->end()) mutation.remove.push_back({bucket, "*"}); } if (operation != "remove") { const std::string raw = string_field("value"); const std::string value = trim_permission_target(raw); std::string normalized = value; wxString reason; bool valid = !value.empty() && value.find('\0') == std::string::npos; if (valid && (category == "fs_read" || category == "fs_readwrite")) valid = normalize_filesystem_permission(value, normalized, reason); else if (valid && (category == "fs_create" || category == "fs_delete")) { valid = normalize_filesystem_permission(value, normalized, reason); if (entries->size() == 1 && entries->front() == "*") valid = false; } else if (valid && category == "network_http") valid = normalize_network_permission(value, normalized, reason); else if (valid && category == "network_socket") valid = normalize_socket_permission(value, normalized, reason); if (!valid) { if (!reason.empty()) show_status(format_wxstr(_L("Cannot save \"%1%\": %2%"), from_u8(raw), reason), "error"); else show_status(_L("Invalid permission save request."), "error"); finish(false); return; } if ((category == "fs_create" || category == "fs_delete") && is_root_tree_permission(normalized)) { // TRN %1% is the plugin name; %2% is the folder tree path being granted. const wxString message = category == "fs_delete" ? format_wxstr(_L("Allow \"%1%\" to delete entries throughout \"%2%\"?\n\n" "This covers the entire filesystem, drive, or network share named by this path, " "including existing files and folders in nested folders. Protected paths remain blocked. " "Only allow this for a plugin you trust."), plugin_name, from_u8(normalized)) : format_wxstr(_L("Allow \"%1%\" to create entries throughout \"%2%\"?\n\n" "This covers the entire filesystem, drive, or network share named by this path, " "including nested folders. Protected paths remain blocked. " "Only allow this for a plugin you trust."), plugin_name, from_u8(normalized)); MessageDialog dialog(this, message, _L("All folders"), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING); dialog.SetButtonLabel(wxID_NO, _L("No"), /*set_focus=*/true); const int result = dialog.ShowModal(); restore_z_order(); if (result != wxID_YES) { finish(false); return; } } mutation.add.push_back({bucket, normalized}); } } PluginPermissions applied; if (!PluginManager::instance().mutate_plugin_permissions(plugin_key, mutation, &applied)) { show_status(_L("Failed to save permissions."), "error"); finish(false); return; } // An edit that leaves the plugin without the tools ends what its calls left in force (auto-answer rules, a // recording, held presses) and stops its running calls. On the UI thread, as the calls publish those. if ((mutation.tools || mutation.full_access) && !applied.allows_tools()) if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started()) runtime->plugin_tools_withdrawn(plugin_key); finish(true); show_status(wxString::Format(_L("Permissions saved for \"%s\"."), plugin_name), "success"); } void PluginsDialog::toggle_plugin(const std::string& plugin_key, bool enabled) { if (plugin_key.empty()) return; Ops::SetPluginEnabledArgs args; args.plugin = plugin_key; args.enabled = enabled; // Switching on a cloud plugin that is not installed downloads it behind this dialog's progress dialog. args.run_download = [this, plugin_key](const std::function()>& download) { PluginDescriptor descriptor; const wxString name = get_descriptor(plugin_key, descriptor) ? from_u8(descriptor.name) : from_u8(plugin_key); return run_with_dialog_wait(download, _L("Downloading plugin"), _L("Downloading") + ": " + name); }; const Ops::Outcome done = Ops::set_plugin_enabled(args); if (!done) { const Ops::Refusal& refusal = done.refusal(); const std::string code = refusal.code; if (code == "unauthorized_plugin") { // The row shows why it stays off. PluginManager::instance().set_plugin_error(plugin_key, into_u8(refusal.translated())); show_status(refusal.translated(), "warn"); } else if (code == "not_unloaded" || code == "manifest_not_found") { show_status(refusal.translated(), "warn"); } else if (code == "download_failed") { show_status(refusal.translated(), "error"); } // Otherwise the row shows how the plugin stands: gone, loading, or with its error. send_plugins(); return; } if (!enabled) { // A prior activation of this plugin is moot now; drop it so no stale "Activated" arrives later. if (m_activating_plugin_key == plugin_key) m_activating_plugin_key.clear(); send_plugins(); show_status(wxString::Format(_L("Deactivated \"%s\"."), plugin_display_name(plugin_key)), "success"); return; } send_plugins(); if (done.value().change != Ops::PluginChange::LoadStarted) return; // Loading is asynchronous: show a pending message now; resolve_pending_activation() turns it into // Activated/Failed once the loader's completion callback runs update_plugin_dialog_ui(). m_activating_plugin_key = plugin_key; show_status(wxString::Format(_L("Activating \"%s\"..."), plugin_display_name(plugin_key)), "info"); } void PluginsDialog::toggle_plugin_capability(const std::string& plugin_key, PluginCapabilityType type, const std::string& capability_name, bool enabled) { if (plugin_key.empty() || capability_name.empty() || type == PluginCapabilityType::Unknown) return; Ops::SetPluginEnabledArgs args; args.plugin = plugin_key; args.capability = capability_name; args.capability_type = type; args.enabled = enabled; const Ops::Outcome done = Ops::set_plugin_enabled(args); send_plugins(); // A plugin or capability that is gone leaves the rows to show it. if (done) show_status(wxString::Format(enabled ? _L("Enabled \"%s\".") : _L("Disabled \"%s\"."), from_u8(capability_name)), "success"); } void PluginsDialog::handle_plugin_menu_action(const std::string& plugin_key, const std::string& action) { PluginDescriptor row_data; if (!get_descriptor(plugin_key, row_data)) return; const PluginDialogItem dialog_item = build_plugin_dialog_item(row_data); const PluginContextAction* context_action = find_context_action(dialog_item.available_actions, action); if (!context_action || !context_action->enabled) return; if (action == "open_folder") { open_plugin_folder(row_data); } else if (action == "delete_plugin") { delete_local_plugin(row_data); } else if (action == "unsubscribe_plugin") { unsubscribe_cloud_plugin(row_data); } else if (action == "reload_plugin") { reload_local_plugin(plugin_key, /*clear_cache=*/false); } else if (action == "clear_cache_reload_plugin") { reload_local_plugin(plugin_key, /*clear_cache=*/true); } else if (action == "reinstall_plugin") { if (row_data.is_cloud_plugin()) reinstall_cloud_plugin(row_data); } } void PluginsDialog::install_plugin_from_file() { wxFileDialog dialog(this, _L("Select plugin package"), wxEmptyString, wxEmptyString, _L("Plugin files (*.py;*.whl)|*.py;*.whl"), wxFD_OPEN | wxFD_FILE_MUST_EXIST); const int rc = dialog.ShowModal(); restore_z_order(); if (rc != wxID_OK) return; if (!install_plugin_package(dialog.GetPath().ToUTF8().data())) { BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to install plugin package."; } } bool PluginsDialog::install_plugin_package(const std::string& package_path) { if (package_path.empty()) return false; BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Installing local plugin package from path: " << package_path; const boost::filesystem::path package_file(package_path); wxString message; const bool installed = install_local_plugin_package(package_file, this, message); // The helper's overwrite prompt and progress dialog can push this webview behind; re-raise it // once, after both have closed (the speed-dial path parents to the mainframe instead). restore_z_order(); // The shared helper reports a user-cancelled overwrite with an empty message: stay silent. if (message.IsEmpty()) { send_plugins(); return false; } if (!installed) { BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to install plugin package."; show_status(message, "warn"); send_plugins(); return false; } show_status(message, "success"); prompt_for_missing_plugins(); send_plugins(); return true; } bool PluginsDialog::install_cloud_plugin(const std::string& plugin_key, const std::string& version, const wxString& name) { if (plugin_key.empty()) return false; const Ops::Outcome downloaded = run_with_dialog_wait( [plugin_key, version]() { return Ops::download_cloud_plugin(plugin_key, version); }, _L("Downloading plugin"), _L("Downloading") + ": " + name); if (!downloaded) { show_status(downloaded.refusal().translated(), "error"); return false; } return true; } void PluginsDialog::show_status(const wxString& message, const char* level) { nlohmann::json payload; payload["command"] = "status_message"; payload["level"] = level; payload["message"] = into_u8(message); call_web_handler(payload); } wxString PluginsDialog::plugin_display_name(const std::string& plugin_key) const { PluginDescriptor descriptor; if (get_descriptor(plugin_key, descriptor) && !descriptor.name.empty()) return from_u8(descriptor.name); return from_u8(plugin_key); } void PluginsDialog::send_capability_config(const PluginCapabilityId& id) { call_web_handler(PluginConfig::get_config_response(id)); } void PluginsDialog::save_capability_config(const PluginCapabilityId& id, const nlohmann::json& config) { const nlohmann::json response = PluginConfig::save_config_response(id, config); call_web_handler(response); if (response.value("ok", false)) show_status(_L("Configuration saved."), "success"); } void PluginsDialog::restore_capability_config(const PluginCapabilityId& id) { // Destructive, so confirm first. The confirmation stays here rather than in PluginConfig: it needs // a parent window. const int rc = wxMessageBox(wxString::Format(_L("Restore the default configuration for \"%s\"?\n\n" "This discards the settings currently saved for this capability."), from_u8(id.name)), _L("Restore defaults"), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING, this); if (rc != wxYES) return; const nlohmann::json response = PluginConfig::restore_config_response(id); call_web_handler(response); if (response.value("ok", false)) show_status(_L("Default configuration restored."), "success"); } void PluginsDialog::run_script_plugin_capability(const std::string& plugin_key, const std::string& capability_name) { PluginManager& manager = PluginManager::instance(); auto complete_with_error = [this, &manager, plugin_key](const std::string& plugin_error, const wxString& status_message) { const std::string normalized_error = plugin_error.empty() ? _u8L("Script plugin failed.") : plugin_error; if (!manager.set_plugin_error(plugin_key, normalized_error)) BOOST_LOG_TRIVIAL(warning) << "Failed to record plugin error. plugin_key=" << plugin_key; if (!manager.unload_plugin(plugin_key)) BOOST_LOG_TRIVIAL(error) << "Failed to unload plugin after script error. plugin_key=" << plugin_key; send_plugins(); // The row already shows "Error" and the Diagnostics tab holds the full text, so report in the // footer status bar instead of a modal box. const wxString message = status_message.empty() ? from_u8(normalized_error) : status_message; show_status(message, "error"); }; // Always runs on the GUI thread. For a started invocation (sync `def execute` or `async def`) // the runtime delivers it later; it is called inline here only when the launch itself failed. auto finish = [this, alive = m_alive, plugin_key, &manager, complete_with_error](const ScriptCompletion& completion) { if (!alive->load()) return; // Cancelled by PluginManager (unload/shutdown): expected termination. Report neither an // error nor a normal success, and do not touch the plugin's error/state. if (completion.cancelled) return; if (!completion.error.empty()) { complete_with_error(completion.error, wxString()); return; } const ExecutionResult& result = completion.result; BOOST_LOG_TRIVIAL(info) << "Script plugin execution completed. plugin_key=" << plugin_key << " status=" << static_cast(result.status) << " message=" << result.message << " data=" << result.data; const bool failed = result.status == PluginResult::RecoverableError || result.status == PluginResult::FatalError; if (failed) { complete_with_error(result.message, wxString()); return; } manager.clear_plugin_error(plugin_key); send_plugins(); const bool skipped = result.status == PluginResult::Skipped; const wxString fallback = skipped ? _L("Script plugin skipped.") : _L("Script plugin finished."); const wxString message = result.message.empty() ? fallback : from_u8(result.message); show_status(message, skipped ? "info" : "success"); }; PluginManager::ScriptLaunchResult launch; { wxBusyCursor busy; launch = manager.launch_script_capability(plugin_key, capability_name, finish); } // Every started invocation — a synchronous `def execute` included — completes later through // `finish`; only a launch failure is reported inline. Return without blocking. if (!launch.launched_async) finish(launch.outcome); } void PluginsDialog::update_plugin(const std::string& plugin_key) { if (plugin_key.empty()) return; BOOST_LOG_TRIVIAL(info) << "Updating cloud plugin. plugin_key=" << plugin_key; PluginDescriptor descriptor; const wxString name = get_descriptor(plugin_key, descriptor) ? from_u8(descriptor.name) : from_u8(plugin_key); // update_cloud_plugin unloads the old plugin, deletes its local package, reinstalls the latest // version and reloads a package that was active; all of that is off-main-thread work, so run it // on the worker behind a progress dialog. std::string error; bool updated = false; try { updated = run_with_dialog_wait([plugin_key, &error]() { return PluginManager::instance().update_cloud_plugin(plugin_key, error); }, _L("Updating plugin"), _L("Updating") + ": " + name); } catch (const std::exception& ex) { error = ex.what(); } catch (...) { error = _u8L("Unknown error"); } if (!updated) { BOOST_LOG_TRIVIAL(error) << "Cloud plugin update failed. plugin_key=" << plugin_key << " error=" << error; show_status(error.empty() ? _L("Failed to update plugin.") : from_u8(error), "error"); send_plugins(); return; } // update_cloud_plugin already updated the in-memory descriptor and restored the loaded state, // so a UI refresh is enough here. send_plugins(); show_status(wxString::Format(_L("Updated \"%s\"."), name), "success"); } void PluginsDialog::open_plugin_folder(const PluginDescriptor& plugin) { const boost::filesystem::path plugin_folder = resolve_plugin_root_from_descriptor(plugin); if (plugin_folder.empty()) { show_status(_L("Plugin folder could not be determined."), "warn"); return; } desktop_open_any_folder(plugin_folder.string()); } void PluginsDialog::open_plugin_on_cloud(const std::string& sharing_token) { if (sharing_token.empty()) return; if (!wxGetApp().getAgent()) return; auto orca_agent = std::dynamic_pointer_cast(wxGetApp().getAgent()->get_cloud_agent()); if (!orca_agent) return; wxLaunchDefaultBrowser(wxString::FromUTF8(orca_agent->get_cloud_base_url() + "/p/" + sharing_token)); } void PluginsDialog::open_plugin_hub() { Slic3r::GUI::open_plugin_hub(); } void PluginsDialog::delete_local_plugin(const PluginDescriptor& plugin) { const wxString plugin_name = from_u8(plugin.name); const int rc = wxMessageBox( wxString::Format(plugin.is_cloud_plugin() ? _L("Delete plugin \"%s\"?\n\nThis removes the local plugin files. The plugin stays in the cloud " "and can be reinstalled.") : _L("Delete plugin \"%s\"?\n\nThis permanently removes the plugin folder."), plugin_name), kDeletePluginTitle, wxYES_NO | wxNO_DEFAULT | wxICON_WARNING, this); restore_z_order(); if (rc != wxYES) return; const Ops::PluginUninstall plan{plugin.plugin_key, plugin.name, /*unsubscribe=*/false, plugin}; auto state = std::make_shared(); run_with_dialog([plan, state]() { store_plugin_operation_result(state, Ops::uninstall_plugin(plan)); }, [this, state, plugin_name]() { const std::optional> deleted = take_plugin_operation_result(state); if (!deleted || !*deleted) { show_status(deleted ? deleted->refusal().translated() : _L("Failed to delete plugin."), "error"); return; } send_plugins(); Ops::plugin_uninstalled(); show_status(wxString::Format(_L("Deleted \"%s\"."), plugin_name), "success"); }, _L("Deleting plugin"), _L("Deleting plugin...")); } void PluginsDialog::unsubscribe_cloud_plugin(const PluginDescriptor& plugin) { const wxString plugin_name = from_u8(plugin.name); const int rc = wxMessageBox( wxString::Format(_L("Unsubscribe plugin \"%s\"?\n\nThis will stop tracking the plugin and delete any local plugin files."), plugin_name), kUnsubscribeTitle, wxYES_NO | wxNO_DEFAULT | wxICON_WARNING, this); restore_z_order(); if (rc != wxYES) return; const Ops::PluginUninstall plan{plugin.plugin_key, plugin.name, /*unsubscribe=*/true, plugin}; auto state = std::make_shared(); run_with_dialog([plan, state]() { store_plugin_operation_result(state, Ops::uninstall_plugin(plan)); }, [this, state, plugin_name]() { const std::optional> unsubscribed = take_plugin_operation_result(state); if (!unsubscribed || !*unsubscribed) { show_status(unsubscribed ? unsubscribed->refusal().translated() : _L("Failed to unsubscribe plugin."), "error"); return; } send_plugins(); Ops::plugin_uninstalled(); show_status(wxString::Format(_L("Unsubscribed \"%s\"."), plugin_name), "success"); }, _L("Unsubscribing plugin"), _L("Deleting local files and unsubscribing plugin...")); } void PluginsDialog::reload_local_plugin(const std::string& plugin_key, bool clear_cache) { if (plugin_key.empty()) return; const Ops::Outcome plan = Ops::plugin_reload_plan(plugin_key, clear_cache); if (!plan) { show_status(plan.refusal().translated(), "warn"); send_plugins(); return; } if (const Ops::Outcome reloaded = run_reload([plan = plan.value()]() { return Ops::reload_plugin(plan); }); !reloaded) { show_status(reloaded.refusal().translated(), "warn"); send_plugins(); return; } send_plugins(); show_status(wxString::Format(_L("Reloaded \"%s\"."), plugin_display_name(plugin_key)), "success"); } Ops::Outcome PluginsDialog::run_reload(const std::function()>& work) { Ops::Outcome reloaded = Ops::Done{}; try { reloaded = run_with_dialog_wait(work, _L("Reloading plugin"), _L("Reloading plugin")); } catch (const std::exception& ex) { reloaded = Ops::Refusal{Ops::RefusalKind::Failed, "not_loaded", ex.what()}; } catch (...) { reloaded = Ops::Refusal{Ops::RefusalKind::Failed, "not_loaded", L("Unknown plugin reload error.")}; } // A failure with no text of its own. if (!reloaded && reloaded.refusal().msgid.empty()) return Ops::Refusal{Ops::RefusalKind::Failed, reloaded.refusal().code, L("Failed to reload plugin.")}; return reloaded; } void PluginsDialog::reinstall_cloud_plugin(const PluginDescriptor& plugin) { const std::string plugin_key = plugin.plugin_key; if (plugin_key.empty()) return; const bool was_loaded = PluginManager::instance().is_plugin_loaded(plugin_key); if (plugin.has_local_package()) { if (const Ops::Outcome removed = Ops::remove_plugin_package_for_reinstall(plugin); !removed) { show_status(removed.refusal().translated(), "error"); send_plugins(); return; } } if (!install_cloud_plugin(plugin_key, plugin.version, from_u8(plugin.name))) { send_plugins(); return; } if (was_loaded) { if (const Ops::Outcome reloaded = run_reload([plugin_key]() { return Ops::load_plugin_and_wait(plugin_key); }); !reloaded) { show_status(reloaded.refusal().translated(), "warn"); send_plugins(); return; } } send_plugins(); show_status(wxString::Format(_L("Reloaded \"%s\"."), plugin_display_name(plugin_key)), "success"); } }} // namespace Slic3r::GUI