diff --git a/README.md b/README.md index f6adf64..9c0f2f0 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,12 @@ For `There is no profile is selected. Please create one first.`, create a profil For `Unable to load profile` or a missing profile-key error, back up the profile data before attempting repairs. Try creating a separate profile for the same game version to check whether the problem is limited to the original profile. +### Account avatar shows Steve or Alex instead of a custom skin + +The launcher downloads account avatars from MCHeads and caches them locally. A cached default avatar can remain visible +even after you change your skin. Wait a few minutes, then open the account page and click **Refresh avatar cache** +(**重新整理頭像快取**) to download the avatars again. If the problem persists, check the launcher log for avatar download errors. + ### Game closes immediately after launch Check the Minecraft Log window for the error preceding the exit message. An exit code alone does not identify the cause. @@ -138,4 +144,4 @@ refresh tokens, and sign-in codes before sharing logs. - [ ] Add more custom settings. - [ ] Add a usage guide. - [ ] Add download mod from third party website support. -- [ ] Add a simple plugin system, allows customizing launcher behavior such as adding a new page or button. +- [X] Add a simple plugin system, allows customizing launcher behavior such as adding a new page or button. diff --git a/TapLauncher/__init__.py b/TapLauncher/__init__.py index 509eaf7..31bc549 100644 --- a/TapLauncher/__init__.py +++ b/TapLauncher/__init__.py @@ -1,4 +1,4 @@ -from manager.plugin import Plugin, PluginManager +from manager.plugins import Plugin, PluginManager, PluginContext import core_lib as core -__all__ = ["Plugin", "PluginManager", "core"] +__all__ = ["Plugin", "PluginManager", "core", "PluginContext"] diff --git a/app.py b/app.py index 3a2cdeb..5a51c0f 100644 --- a/app.py +++ b/app.py @@ -5,6 +5,8 @@ from collections.abc import Mapping from pathlib import Path from typing import Callable +from manager.plugins import PluginManager + try: import tomllib except ModuleNotFoundError: # Python 3.10 @@ -24,7 +26,7 @@ from manager.account import AccountManager from manager.game import GameManager from manager.profile import ProfileManager from manager.settings import SettingsManager -from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings +from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings, PluginSettings from manager.widgets import WidgetManager from window import LauncherMainWindow @@ -68,6 +70,7 @@ class Launcher(QApplication, LauncherObject): self.settings_manager.register("general", GeneralSettings) self.settings_manager.register("appearance", AppearanceSettings) self.settings_manager.register("account", AccountSettings) + self.settings_manager.register("plugins", PluginSettings) if self.root_settings_dir.is_file(): self.load_settings() else: @@ -85,6 +88,9 @@ class Launcher(QApplication, LauncherObject): self.account_manager = AccountManager(self, self.widget_manager) self.game_manager = GameManager(self) + # Plugin manager + self.plugin_manager = PluginManager(self) + # Window config self.setApplicationName("TapLauncher") self.main_window = LauncherMainWindow( @@ -100,6 +106,23 @@ class Launcher(QApplication, LauncherObject): elif not icon_existing: self.logger.error("No icon found.") + # Load plugins + self.register_plugin_apis() + + def register_plugin_apis(self): + for manager in (self.settings_manager, self.profile_manager, self.account_manager, + self.game_manager, self.widget_manager): + manager.register_plugin_apis(self.plugin_manager) + + for widget in (self.main_window,): + widget.register_plugin_apis(self.plugin_manager) + + self.plugin_manager.register_api("launcher.app.set_reloadable_toolbutton_icon", self.set_reloadable_toolbutton_icon) + self.plugin_manager.register_api("launcher.app.paths", lambda: { + "work_dir": Path(self.work_dir), + "default_game_dir": Path(self.default_game_dir), + }) + self.plugin_manager.register_api("launcher.app.tr_text", lambda text, **kwargs: self.tr_text(text, **kwargs)) def exec(self): # init managers @@ -108,6 +131,8 @@ class Launcher(QApplication, LauncherObject): self.main_window.show() self.main_window.toolbar.update_all() + # Restore plugins after profile/account data and host APIs are ready. + self.plugin_manager.signals.load_plugins.emit() self.exec_() def get_icon(self, path: Path, no_color_change: bool = False) -> QIcon: @@ -199,40 +224,48 @@ class Launcher(QApplication, LauncherObject): return picture @property - def temp_dir(self): + def temp_dir(self) -> Path: return self.work_dir / "temp" @property - def config_dir(self): + def config_dir(self) -> Path: return self.work_dir / "config" @property - def data_dir(self): + def data_dir(self) -> Path: return self.work_dir / "data" @property - def log_dir(self): + def log_dir(self) -> Path: return self.work_dir / "log" @property - def root_settings_dir(self): + def root_settings_dir(self) -> Path: return self.data_dir / "settings.toml" + @property + def plugins_dir(self) -> Path: + return self.work_dir / "plugins" + + @property + def internal_plugins_dir(self) -> Path: + return self.resources_dir / "builtin_plugins" + @property def default_game_dir(self) -> Path: # Completely with official Minecraft launcher return self.work_dir @property - def resources_dir(self): + def resources_dir(self) -> Path: return self.program_dir / "resources" @property - def icon_path(self): + def icon_path(self) -> Path: return self.resources_dir / "icons" / "icon.png" @property - def icon_dir(self): + def icon_dir(self) -> Path: return self.resources_dir / "icons" @property @@ -240,7 +273,7 @@ class Launcher(QApplication, LauncherObject): return LAUNCHER_VERSION @property - def styles_path(self): + def styles_path(self) -> Path: return self.resources_dir / "styles" def locate_styles_path(self, relative_path: Path | str) -> Path: diff --git a/constant.py b/constant.py index 2c39d9a..40cc289 100644 --- a/constant.py +++ b/constant.py @@ -1,4 +1,4 @@ -LAUNCHER_VERSION = "0.0.9-alpha" +LAUNCHER_VERSION = "0.1.0-alpha" LAUNCHER_NAME = "TapLauncher" LAUNCHER_DIR_NAME = "TapLauncher" MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/" @@ -16,3 +16,5 @@ Launcher while being more lightweight and easier to use. This launcher is not associated with Mojang Studios or Microsoft. Is a personal project that just for fun. """ +LAUNCHER_DESCRIPTION_KEYWORD = "$ABOUT_THIS_LAUNCHER" +WHEEL_PLUGIN_API_VERSION = "0.0.1" \ No newline at end of file diff --git a/core_lib/__init__.py b/core_lib/__init__.py index c153c8e..4a41992 100644 --- a/core_lib/__init__.py +++ b/core_lib/__init__.py @@ -1,4 +1,4 @@ -__version__ = '0.1.3' +__version__ = '0.1.4' __description__ = """ The core library of the *Launcher* diff --git a/core_lib/common/python.py b/core_lib/common/python.py new file mode 100644 index 0000000..3b96685 --- /dev/null +++ b/core_lib/common/python.py @@ -0,0 +1,22 @@ +import ast + + +def is_function_in_file(file_path, function_name) -> tuple[bool, bool]: + """ + Parse a Python file via ast module to check if a function exists. + :param file_path: + :param function_name: + :return: + is_check_success: bool + is_function_exist: bool + """ + try: + with open(file_path, "r", encoding="utf-8") as f: + root = ast.parse(f.read(), filename=file_path) + + for node in ast.iter_child_nodes(root): + if isinstance(node, ast.FunctionDef) and node.name == function_name: + return True, True + return True, False + except (FileNotFoundError, SyntaxError): + return False, False diff --git a/core_lib/game/third_party.py b/core_lib/game/third_party.py index 19302c8..ebbf4a4 100644 --- a/core_lib/game/third_party.py +++ b/core_lib/game/third_party.py @@ -1,5 +1,5 @@ """ -Contains some function that deal with 3rd party api +Contains some functions that dealing with 3rd party api """ import requests diff --git a/core_lib/i18n.py b/core_lib/i18n.py index 51fce2f..fd7c2e7 100644 --- a/core_lib/i18n.py +++ b/core_lib/i18n.py @@ -54,5 +54,9 @@ class TranslationManager(QObject): def translate(self, key: str, /, **values: Any) -> str: text = self._catalog.get(key, key) + + if text == "": + return key + return text.format(**values) if values else text diff --git a/core_lib/qt/item_button.py b/core_lib/qt/item_button.py new file mode 100644 index 0000000..0664b56 --- /dev/null +++ b/core_lib/qt/item_button.py @@ -0,0 +1,26 @@ +from PySide6.QtWidgets import QLabel, QPushButton + + +class ItemButton(QPushButton): + """Expose button states on child labels for reliable QSS color rules.""" + + def __init__(self, parent=None): + super().__init__(parent) + self.toggled.connect( + lambda checked: self._set_label_state("itemChecked", checked) + ) + + def _set_label_state(self, name: str, active: bool) -> None: + for label in self.findChildren(QLabel): + label.setProperty(name, active) + label.style().unpolish(label) + label.style().polish(label) + label.update() + + def enterEvent(self, event): + super().enterEvent(event) + self._set_label_state("itemHovered", True) + + def leaveEvent(self, event): + super().leaveEvent(event) + self._set_label_state("itemHovered", False) diff --git a/manager/account.py b/manager/account.py index 436ad2f..8e80f3c 100644 --- a/manager/account.py +++ b/manager/account.py @@ -14,7 +14,7 @@ from pathlib import Path import keyring from PySide6.QtCore import QObject, Signal, QThread, QTimer, QSize, Qt, Slot from PySide6.QtGui import QPixmap, QImage -from PySide6.QtWidgets import QMessageBox +from PySide6.QtWidgets import QMessageBox, QWidget from keyring.errors import KeyringError, PasswordDeleteError from constant import LAUNCHER_NAME, CLIENT_ID, ACCESS_TOKEN_KEYWORD, REFRESH_TOKEN_KEYWORD, SYSTEM_KEYRING_KEYWORD @@ -366,6 +366,12 @@ class AccountManager(QObject): def _display_name(account: Account) -> str: return account.minecraft_name.strip() or account.username.strip() or "Unnamed Account" + def register_plugin_apis(self, plugin_manager): + plugin_manager.register_api("launcher.accounts.list", self.list_accounts) + plugin_manager.register_api("launcher.accounts.contains", self.contains) + plugin_manager.register_api("launcher.accounts.current_id", self.get_current_account_id) + plugin_manager.register_api("launcher.accounts.set_current", self.set_current_account) + def list_accounts(self) -> list[AccountSummary]: """ List (Return) all accounts (couple of account summaries) @@ -1437,13 +1443,13 @@ class AccountManager(QObject): # background. return self.app.get_icon(Path(self.app.icon_dir, "head.png")).pixmap(size) - def request_account_head(self, account_id: str, username: str, size: int = 32) -> bool: - """Download and persist a missing account head without blocking the UI.""" + def request_account_head(self, account_id: str, username: str, size: int = 32, *, force: bool = False) -> bool: + """Download an account head, optionally replacing a cached avatar.""" if account_id in self._head_jobs or not username.strip(): return False account = self.get_account(account_id) - if account is None or self.has_saved_head(account.avatar): + if account is None or (not force and self.has_saved_head(account.avatar)): return False request_size = min(256, max(32, int(size))) diff --git a/manager/game.py b/manager/game.py index 94e3398..e9ddbf0 100644 --- a/manager/game.py +++ b/manager/game.py @@ -1359,3 +1359,8 @@ class GameManager(QObject): self.game_file = GameFileManager(self.app, manifest_manager=self.manifest) self.launch = LaunchManager(self.app, self.manifest, self.java, self.game_file, self.account_manager, self.profile_mgr) + + def register_plugin_apis(self, plugin_manager): + plugin_manager.register_api("launcher.game.versions.list", self.manifest.list_available_profile_versions) + plugin_manager.register_api("launcher.game.java.list", self.java.list_runtimes) + plugin_manager.register_api("launcher.game.is_profile_running", self.launch.is_profile_running) diff --git a/manager/plugin.py b/manager/plugin.py deleted file mode 100644 index b8d6d8a..0000000 --- a/manager/plugin.py +++ /dev/null @@ -1,7 +0,0 @@ - - -class Plugin: - pass - -class PluginManager: - pass \ No newline at end of file diff --git a/manager/plugins.py b/manager/plugins.py new file mode 100644 index 0000000..55c8a99 --- /dev/null +++ b/manager/plugins.py @@ -0,0 +1,534 @@ +""" +Wheel plugin API + +My simple plugin API for "all" Python-based applications +""" +import importlib +import re +import sys +import traceback +from dataclasses import dataclass +from hashlib import sha256 +from importlib.machinery import ModuleSpec +from importlib.util import spec_from_file_location +from logging import Logger +from pathlib import Path +from typing import Callable + +from PySide6.QtCore import QObject, Signal + +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 + import tomli as tomllib + +from packaging.specifiers import SpecifierSet, InvalidSpecifier + +from constant import WHEEL_PLUGIN_API_VERSION +from core_lib.common.python import is_function_in_file +from manager.settings_models import PluginSettings + +OPERATORS = { + "==": "equal", + "!=": "not equal", + ">": "higher than", + ">=": "not lower than", + "<": "lower than", + "<=": "not higher than", + "~=": "compatible with", + "===": "same", +} + +def describe_specifier(spec: SpecifierSet) -> str: + if not spec: + return "No version limit" + + return ", and ".join( + f"{OPERATORS[item.operator]} {item.version}" + for item in sorted(spec, key=str) + ) + +class Plugin: + def __init__(self, plugin_id: str, name: str, group: str, version: str, api_version_range: SpecifierSet, entrypoint: str, path: Path, + icon_path: Path | None = None, module_spec: ModuleSpec | None = None, description: str = ""): + self.id: str = plugin_id + self.name: str = name + self.group: str = group + self.version: str = version + self.description: str = description + + self.enabled: bool = False + self._changing_state = False + self._cleanup_callbacks: list[Callable[[], None]] = [] + self.api_version_range: SpecifierSet = api_version_range + + self.entrypoint = entrypoint + self.entry: Callable[[PluginContext], None] | None = None + self.path = path + self.icon_path: Path | None = icon_path + self.module_spec: ModuleSpec | None = module_spec + + def get_support_api_range_string(self): + return describe_specifier(self.api_version_range) + + @property + def is_changing_state(self) -> bool: + return self._changing_state + + def get_entrypoint_name(self): + """ + Get entrypoint name + IMPORTANT: The entrypoint should be verified. + :return: + """ + return self.entrypoint.rsplit(":", 1)[-1] + +@dataclass(frozen=True) +class PluginContext: + api_version: str + plugin_id: str + plugin_dir: Path + data_dir: Path + logger: Logger + + # callback + get_api: Callable[[str], Callable] + show_info: Callable[[str], None] + show_error: Callable[[str], None] + on_cleanup: Callable[[Callable[[], None]], None] + +class PluginManager(QObject): + def __init__(self, app): + QObject.__init__(self) + self.app = app + self.widget_manager = app.widget_manager + self.plugins: list[Plugin] = [] + self._apis: dict[str, Callable] = {} + self._updating_plugin_state = False + self.register_api("launcher.apis.list", self.list_apis) + + self.signals = PluginManager.Signals() + + self.signals.load_plugins.connect(self.load_plugins) + self.signals.reload_plugins.connect(self.load_plugins) + self.app.aboutToQuit.connect(self.shutdown_plugins) + + class Signals(QObject): + load_plugins = Signal() + reload_plugins = Signal() + plugins_loaded = Signal() # For gui + plugin_state_changed = Signal(object) + + def _show_error(self, message: str, error: BaseException | None = None): + details = message + if error is not None: + details += "\n" + "".join(traceback.format_exception(type(error), error, error.__traceback__)) + + self.widget_manager.signal.show_and_print_error_message.emit({ + "title": "Plugin Error", + "message": message, + "error": details, + }) + + def load_plugins_from_path(self, plugins_dir: Path): + try: + plugins = [d for d in plugins_dir.iterdir() if d.is_dir()] + except FileNotFoundError: + return + except OSError as e: + message = f"Failed to load plugins from {plugins_dir}: {e}" + self._show_error(message, e) + return + + for plugin_dir in plugins: + plugin = self._load_plugin_config(plugin_dir) + + if plugin: + self.app.logger.debug(f"Loading plugin: {plugin.id}") + if self._init_plugin_entry(plugin): + self.plugins.append(plugin) + + def load_plugins(self): + if self._updating_plugin_state: + return + try: + settings = self.app.settings_manager.get("plugins", PluginSettings) + enabled_ids = set(settings.enabled) + except Exception as e: + self._show_error(f"Failed to read plugin enabled states: {e}", e) + self.signals.plugins_loaded.emit() + return + + plugins_dir: Path = self.app.plugins_dir + internal_dir: Path = self.app.internal_plugins_dir + enabled_ids.update(f"{plugin.group}:{plugin.id}" for plugin in self.plugins if plugin.enabled) + + if not self.shutdown_plugins(): + self.signals.plugins_loaded.emit() + return + + self.plugins.clear() + self.load_plugins_from_path(internal_dir) + self.load_plugins_from_path(plugins_dir) + for plugin in self.plugins: + if f"{plugin.group}:{plugin.id}" in enabled_ids: + self.enable_plugin(plugin) + self.signals.plugins_loaded.emit() + + def _init_plugin_entry(self, plugin: Plugin) -> bool: + # For current state, the plugin manager only supports init plugin entry in main thread + spec = plugin.module_spec + if spec is None or spec.loader is None: + self._show_error(f"Failed to initialize plugin entry: {plugin.id}. Module spec or loader is missing.") + return False + + # Keep existing modules so a failed reload can restore them. + previous_modules = { + name: module for name, module in sys.modules.copy().items() + if name == spec.name or name.startswith(spec.name + ".") + } + + try: + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + + entry_name = plugin.get_entrypoint_name() + entry: Callable[[PluginContext], None] | None = getattr(module, entry_name, None) + if not callable(entry): + raise ValueError(f'Plugin entry "{entry_name}" is missing or is not callable.') + + plugin.entry = entry + except (Exception, SystemExit) as e: + for name in list(sys.modules): + if name == spec.name or name.startswith(spec.name + "."): + sys.modules.pop(name, None) + sys.modules.update(previous_modules) + + message = f"Failed to initialize plugin entry: {plugin.id}\n{e}" + self._show_error(message, e) + return False + + return True + + def set_plugin_enabled(self, plugin: Plugin, enabled: bool) -> bool: + """Change runtime state and persist the user's preference after success.""" + if not isinstance(enabled, bool): + raise TypeError("Plugin enabled state must be a bool.") + if self._updating_plugin_state or plugin.is_changing_state: + return False + + self._updating_plugin_state = True + was_enabled = plugin.enabled + previous_settings = None + settings_changed = False + try: + settings_manager = self.app.settings_manager + previous_settings = settings_manager.get("plugins", PluginSettings).model_copy(deep=True) + plugin_id = f"{plugin.group}:{plugin.id}" + success = self.enable_plugin(plugin) if enabled else self.disable_plugin(plugin) + if not success: + return False + if (plugin_id in previous_settings.enabled) == enabled: + return True + + enabled_ids = [value for value in previous_settings.enabled if value != plugin_id] + if enabled: + enabled_ids.append(plugin_id) + updated_settings = previous_settings.model_copy(update={"enabled": enabled_ids}) + settings_manager.set("plugins", updated_settings) + settings_changed = True + settings_manager.save() + return True + except Exception as e: + if settings_changed: + self.app.settings_manager.set("plugins", previous_settings) + # Keep runtime and stored preference consistent if writing fails. + if plugin.enabled != was_enabled: + if was_enabled: + self.enable_plugin(plugin) + else: + self.disable_plugin(plugin) + self._show_error(f"Failed to save enabled state for plugin: {plugin.id}\n{e}", e) + return False + finally: + self._updating_plugin_state = False + self.signals.plugin_state_changed.emit(plugin) + + def enable_plugin(self, plugin: Plugin) -> bool: + if plugin._changing_state: + return False + if plugin.enabled: + return True + + plugin._changing_state = True + try: + if not self._cleanup_plugin(plugin): + return False + entry: Callable[[PluginContext], None] | None = plugin.entry + if not entry or not callable(entry): + raise ValueError("Plugin entry has not been initialized.") + + context = self._create_plugin_context(plugin) + entry(context) + plugin.enabled = True + return True + except (Exception, SystemExit) as e: + self._cleanup_plugin(plugin) + self._show_error(f"Failed to enable plugin: {plugin.id}\n{e}", e) + return False + finally: + plugin._changing_state = False + self.signals.plugin_state_changed.emit(plugin) + + def disable_plugin(self, plugin: Plugin) -> bool: + if plugin._changing_state: + return False + + plugin._changing_state = True + try: + if not self._cleanup_plugin(plugin): + return False + plugin.enabled = False + return True + finally: + plugin._changing_state = False + self.signals.plugin_state_changed.emit(plugin) + + def shutdown_plugins(self) -> bool: + success = True + for plugin in reversed(self.plugins): + if plugin.enabled or plugin._cleanup_callbacks: + success = self.disable_plugin(plugin) and success + + return success + + def _create_plugin_context(self, plugin: Plugin) -> PluginContext: + plugin_id = f"{plugin.group}:{plugin.id}" + data_root = (self.app.data_dir / "plugins").resolve() + data_dir = (data_root / plugin.group / plugin.id).resolve() + if data_dir == data_root or not data_dir.is_relative_to(data_root): + raise ValueError(f"Invalid plugin data directory: {plugin_id}") + data_dir.mkdir(parents=True, exist_ok=True) + return PluginContext( + plugin_id=plugin_id, + plugin_dir=plugin.path, + data_dir=data_dir, + logger=self.app.logger.getChild(f"plugins.{plugin.group}.{plugin.id}"), + api_version=WHEEL_PLUGIN_API_VERSION, + show_info=lambda message: self.widget_manager.signal.show_info_message.emit(f"[{plugin_id}] {message}"), + show_error=lambda message: self._show_error(f"[{plugin_id}] {message}"), + on_cleanup=lambda callback: self._register_plugin_cleanup(plugin, callback), + get_api=self.get_api, + ) + + @staticmethod + def _register_plugin_cleanup(plugin: Plugin, callback: Callable[[], None]): + if not callable(callback): + raise TypeError("Plugin cleanup callback must be callable.") + + plugin._cleanup_callbacks.append(callback) + + def _cleanup_plugin(self, plugin: Plugin) -> bool: + callbacks = plugin._cleanup_callbacks + plugin._cleanup_callbacks = [] + failed_callbacks = [] + for callback in reversed(callbacks): + try: + callback() + except (Exception, SystemExit) as e: + failed_callbacks.append(callback) + self._show_error(f"Failed to clean up plugin: {plugin.id}\n{e}", e) + + # Keep failed callbacks available for retry without repeating successful ones. + plugin._cleanup_callbacks[:0] = reversed(failed_callbacks) + return not plugin._cleanup_callbacks + + def _load_plugin_config(self, plugin_dir: Path) -> Plugin | None: + plugin_config_path = plugin_dir / "plugin.toml" + + try: + if not plugin_config_path.exists(): + self._show_error(f"Plugin config not found for plugin: {plugin_dir}") + return None + + with plugin_config_path.open("rb") as f: + plugin_config = tomllib.load(f) + + for key in ("group", "id", "name", "version", "api_version", "entrypoint", "icon"): + if key in plugin_config and not isinstance(plugin_config[key], str): + raise ValueError(f"Plugin {key} must be a string.") + + group = plugin_config.get("group", "") + if not group: + raise ValueError("Plugin missing group id.") + + plugin_id = plugin_config.get("id", "") + if not plugin_id: + raise ValueError("Plugin id is missing.") + + name = plugin_config.get("name", "") + if not name: + name = f"UnnamedPlugin.{plugin_id}" + + version: str = plugin_config.get("version", "") + if not version: + raise ValueError("Plugin version is missing.") + + if not self._check_plugin_version(version): + raise ValueError("Plugin version is invalid.") + + required_api_version = plugin_config.get("api_version", "") + if not required_api_version: + raise ValueError("Required API version is missing.") + + is_valid, is_support, support_api_ver_range = self._check_plugin_support_api_version(required_api_version) + if not is_valid or support_api_ver_range is None: + raise ValueError("Plugin support api version range is invalid") + elif not is_support: + raise ValueError("Plugin does not support the current API version.") + + entrypoint = plugin_config.get("entrypoint", "") + if not entrypoint: + raise ValueError("Plugin entrypoint is missing.") + + module_spec = self._check_and_return_plugin_endpoint_spec(entrypoint, plugin_dir) + + icon_path = None + icon = plugin_config.get("icon", "") + if icon: + candidate = (plugin_dir / icon).resolve() + if (not Path(icon).is_absolute() + and candidate.is_relative_to(plugin_dir.resolve()) + and candidate.suffix.lower() in (".gif", ".png", ".jpg", ".jpeg", ".bmp") + and candidate.is_file()): + icon_path = candidate + + description = plugin_config.get("description", None) + + plugin = Plugin( + name=name, + version=version, + entrypoint=entrypoint, + api_version_range=support_api_ver_range, + group=group, + path=plugin_dir, + plugin_id=plugin_id, + module_spec=module_spec, + icon_path=icon_path, + description=description + ) + + return plugin + except Exception as e: + message = f"Failed to load plugin config: {plugin_config_path}\n{e}" + self._show_error(message, e) + return None + + @staticmethod + def _check_plugin_version(plugin_version: str) -> bool: + pattern = r"[0-9]+\.[0-9]+\.[0-9]+" + + if isinstance(plugin_version, str) and re.fullmatch(pattern, plugin_version): + return True + + return False + + @staticmethod + def _check_plugin_support_api_version(required_api_version: str) -> tuple[bool, bool, SpecifierSet | None]: + """ + Check plugin support api version + :param required_api_version: + :return: + parse_result: bool + support_current_api_version: bool + required_api_version: SpecifierSet + """ + try: + required = SpecifierSet(required_api_version) + + if WHEEL_PLUGIN_API_VERSION in required: + return True, True, required + except InvalidSpecifier: + return False, False, None + + return True, False, required + + @staticmethod + def _check_and_return_plugin_endpoint_spec(endpoint: str, plugin_dir: Path) -> ModuleSpec: + """ + Check plugin endpoint + :param endpoint: + :param plugin_dir: + :return: Module spec for the validated Python file. Does not execute the module. + """ + path = plugin_dir + + parts = endpoint.split(":") + + if len(parts) < 2: + raise ValueError(f"Invalid plugin endpoint \"{endpoint}\". At least two parts are required.") + + for index, part in enumerate(parts[:-1]): + if not part or part in (".", "..") or "/" in part or "\\" in part: + raise ValueError(f"Invalid plugin endpoint \"{endpoint}\". Invalid path part \"{part}\".") + + path = path / part + + if not path.resolve().is_relative_to(plugin_dir.resolve()): + raise ValueError(f"Invalid plugin endpoint \"{endpoint}\". Path must be inside the plugin directory.") + + if index != len(parts) - 2: + if not path.is_dir(): + raise ValueError(f"Invalid plugin endpoint \"{endpoint}\". Directory \"{path}\" does not exist.") + continue + + if not path.is_file() or path.suffix != ".py": + raise ValueError(f"Invalid plugin endpoint \"{endpoint}\". Python file \"{path}\" does not exist.") + + # dira:dirb:file.py:entry + entry = parts[-1] + + if not entry.isidentifier(): + raise ValueError(f"Invalid plugin endpoint \"{endpoint}\". Entry must be a valid identifier.") + + # Check if the entry is in file + is_success, existing = is_function_in_file(path, entry) + if not is_success: + raise ValueError(f"Failed to check if function \"{entry}\" exists in file \"{path}\".") + + if not existing: + raise ValueError(f"Function \"{entry}\" does not exist in file \"{path}\".") + + # Use the resolved path to keep module names distinct across plugins. + path = path.resolve() + module_name = "_wheel_plugin_" + sha256(str(path).encode("utf-8")).hexdigest() + spec = spec_from_file_location(module_name, path) + if spec is None or spec.loader is None: + raise ValueError(f"Failed to create module spec for plugin endpoint \"{endpoint}\".") + + return spec + + # + # API + # + def register_api(self, name: str, callback: Callable): + if not isinstance(name, str): + raise TypeError("Plugin API name must be a string.") + if not name or name != name.strip(): + raise ValueError("Plugin API name must be non-empty and have no surrounding whitespace.") + if not callable(callback): + raise TypeError(f'Plugin API "{name}" must be callable.') + if name in self._apis: + raise ValueError(f'Plugin API "{name}" is already registered.') + + self._apis[name] = callback + + def list_apis(self) -> tuple[str, ...]: + return tuple(sorted(self._apis)) + + def get_api(self, name: str) -> Callable: + try: + return self._apis[name] + except KeyError: + raise LookupError(f'Plugin API "{name}" is not available.') from None diff --git a/manager/profile.py b/manager/profile.py index 441d6f0..c95a0cc 100644 --- a/manager/profile.py +++ b/manager/profile.py @@ -114,6 +114,14 @@ class ProfileManager(QObject): def default_profile_path(self): return Path(self.app.work_dir, DEFAuLT_PROFILE_RELATIVE_PATH) + def register_plugin_apis(self, plugin_manager): + plugin_manager.register_api("launcher.profiles.list", self.list_profiles) + plugin_manager.register_api("launcher.profiles.get", self.get_profile) + plugin_manager.register_api("launcher.profiles.contains", self.contains) + plugin_manager.register_api("launcher.profiles.current_id", self.get_current_profile_id) + plugin_manager.register_api("launcher.profiles.set_current", self.set_current_profile) + plugin_manager.register_api("launcher.profiles.reload", self.reload) + # File lifetime def create_profiles(self, path: str | Path | None=None) -> bool: path = Path(path) if path is not None else self.default_profile_path diff --git a/manager/settings.py b/manager/settings.py index bf1852c..31ef374 100644 --- a/manager/settings.py +++ b/manager/settings.py @@ -34,6 +34,11 @@ class SettingsManager: def registered_sections(self) -> tuple[str, ...]: return tuple(self._models) + def register_plugin_apis(self, plugin_manager): + plugin_manager.register_api("launcher.settings.sections", lambda: self.registered_sections) + plugin_manager.register_api("launcher.settings.get", lambda section: self.get(section).model_dump(mode="python")) + plugin_manager.register_api("launcher.settings.choices", self.choices) + def register(self, section: str, model: type[ModelT], *, replace: bool = False) -> type[ModelT]: """ Register a new model diff --git a/manager/settings_models.py b/manager/settings_models.py index 07c6eed..37a8a45 100644 --- a/manager/settings_models.py +++ b/manager/settings_models.py @@ -3,7 +3,7 @@ import warnings from typing import Literal, Any from uuid import UUID -from pydantic import BaseModel, ConfigDict, field_validator, model_validator +from pydantic import BaseModel, ConfigDict, field_validator, model_validator, Field from constant import CLIENT_ID @@ -74,4 +74,7 @@ class AccountSettings(WarnExtraModel): def validate_token_refresh_interval(cls, value: int) -> int: if value < 60 or value > 86400: raise ValueError("token refresh interval must be at least 60 seconds and at most 1 day") - return value \ No newline at end of file + return value + +class PluginSettings(WarnExtraModel): + enabled: list[str] = Field(default_factory=list) \ No newline at end of file diff --git a/manager/widgets.py b/manager/widgets.py index 03cae19..ee0cfa4 100644 --- a/manager/widgets.py +++ b/manager/widgets.py @@ -41,6 +41,11 @@ class WidgetManager(QObject): self.signal = self.WidgetSignal(self) self.download_signal = self.DownloadSignal(self) + def register_plugin_apis(self, plugin_manager): + plugin_manager.register_api("launcher.ui.show_info", self.signal.show_info_message.emit) + plugin_manager.register_api("launcher.ui.show_warning", self.signal.show_warning_message.emit) + plugin_manager.register_api("launcher.ui.show_error", self.signal.show_error_message.emit) + class DownloadSignal(QObject): started = Signal(str, str) # task_id, display_name progress = Signal(str, str, float) # task_id, status, percent @@ -58,4 +63,4 @@ class WidgetManager(QObject): enable_widget = Signal(object) disable_widget = Signal(object) askyesno = Signal(object) - ask_for_path = Signal(object) \ No newline at end of file + ask_for_path = Signal(object) diff --git a/pages/account.py b/pages/account.py index 89225cb..1f92d20 100644 --- a/pages/account.py +++ b/pages/account.py @@ -20,7 +20,7 @@ from PySide6.QtWidgets import ( from constant import MICROSOFT_VERIFY_ENDPOINT, CLIENT_ID from core_lib.qt.hack import move_window_to_center -from manager.account import AccountManager, AccountSummary, AccountLoginStatus +from manager.account import AccountLoginStatus, AccountSummary, AccountManager from manager.settings_models import AccountSettings @@ -195,12 +195,17 @@ class AccountPage(QWidget): self.refresh_button = QPushButton(self.app.tr_text("Refresh all")) self.reload_button = QPushButton(self.app.tr_text("Reload accounts")) self.delete_all_button = QPushButton(self.app.tr_text("Delete All")) + self.refresh_avatar_cache_button = QPushButton(self.app.tr_text("Refresh avatar cache")) # Button click handle self.add_account_button.clicked.connect(self.start_login_page) self.refresh_button.clicked.connect(self.refresh_accounts) self.reload_button.clicked.connect(self.reload_accounts) self.delete_all_button.clicked.connect(self.account_manager.delete_all_accounts) + self.refresh_avatar_cache_button.clicked.connect(self.refresh_accounts_head) + + # Size + self.avatar_size = QSize(32, 32) # Bind widget main_layout.addWidget(self.account_list) @@ -208,6 +213,7 @@ class AccountPage(QWidget): right_layout.addWidget(self.refresh_button) right_layout.addWidget(self.reload_button) right_layout.addWidget(self.delete_all_button) + right_layout.addWidget(self.refresh_avatar_cache_button) right_layout.addStretch() layout.addLayout(main_layout, 1) @@ -298,12 +304,11 @@ class AccountPage(QWidget): list_item = QListWidgetItem() list_item.setData(Qt.ItemDataRole.UserRole, account.id) - head_size = QSize(32, 32) widget = AccountWidget( self.app, account.id, account.display_name, - self.account_manager.get_head_pixmap(account.avatar, head_size), + self.account_manager.get_head_pixmap(account.avatar, self.avatar_size), self.app.tr_text("Current" if is_current else "Available"), self, delete_account_callback=lambda: self._delete_account(account.id), @@ -317,11 +322,31 @@ class AccountPage(QWidget): self.account_list.setItemWidget(list_item, widget) if not self.account_manager.has_saved_head(account.avatar): - self.account_manager.request_account_head( - account.id, - account.minecraft_name or account.username, - max(head_size.width(), head_size.height()), - ) + self._update_account_head(account.id, account.minecraft_name or account.username) + + def refresh_accounts_head(self): + for row in range(self.account_list.count()): + item = self.account_list.item(row) + widget = self.account_list.itemWidget(item) + if isinstance(widget, AccountWidget): + related_account = self.account_manager.get_account(widget.account_id) + + if not related_account: + continue + + self._update_account_head( + related_account.id, + related_account.minecraft_name or related_account.username, + force=True, + ) + + def _update_account_head(self, account_id: str, username: str, *, force: bool = False): + self.account_manager.request_account_head( + account_id, + username, + max(self.avatar_size.width(), self.avatar_size.height()), + force=force, + ) def _account_head_updated(self, account_id: str): account = self.account_manager.get_account(account_id) @@ -383,9 +408,9 @@ class AccountPage(QWidget): def start_login_page(self): # Active existing login dialog if self.login_dialog is not None: - self.login_dialog.raise_() - self.login_dialog.activateWindow() - return + self.app.logger.info("Destroying existing login dialog...") + self.login_dialog.close() + self.login_dialog.deleteLater() # Create login dialog self.add_account_button.setEnabled(False) @@ -427,6 +452,14 @@ class AccountPage(QWidget): if created_id is not None: self.account_authenticated.emit({"account_id": created_id}) + account = self.account_manager.get_account(created_id) + + if not account: + return + + # Update head image + self._update_account_head(created_id, account.username) + def _login_failed(self, message: str): if self.login_dialog is not None: self.login_dialog.set_error_message(message) diff --git a/pages/launch_profile.py b/pages/launch_profile.py index 564777a..c8e255c 100644 --- a/pages/launch_profile.py +++ b/pages/launch_profile.py @@ -5,6 +5,7 @@ from PySide6.QtGui import QIcon, QMouseEvent, QHideEvent, QPixmap, QPainter from PySide6.QtWidgets import (QWidget, QVBoxLayout, QLabel, QHBoxLayout, QPushButton, QScrollArea, QFrame, QSizePolicy, QApplication) +from core_lib.qt.item_button import ItemButton from manager.game import LaunchManager, LaunchResult from core_lib.game.version_info import LATEST_VERSION_ALIASES from manager.profile import ProfileSummary, LaunchProfile, ProfileManager @@ -86,7 +87,8 @@ class ProfileButton(QFrame): self.clicked.emit() super().mousePressEvent(event) -class ProfileListItem(QPushButton): + +class ProfileListItem(ItemButton): selected = Signal(object) def __init__(self, profile: ProfileSummary, parent: QWidget | None = None) -> None: @@ -475,6 +477,7 @@ class LaunchProfilePage(QWidget): if not request.wait(60): self.widget_mgr.signal.show_error_message.emit( + + self.app.tr_text("Time out waiting for request for launch.") ) return diff --git a/pages/manage_profile.py b/pages/manage_profile.py index 40a9319..69b37aa 100644 --- a/pages/manage_profile.py +++ b/pages/manage_profile.py @@ -1,20 +1,22 @@ import shutil from pathlib import Path +from typing import Callable from PySide6.QtCore import Qt, QUrl, Signal from PySide6.QtGui import QDesktopServices, QIcon from PySide6.QtWidgets import ( QFileDialog, QFormLayout, QFrame, QHBoxLayout, QLabel, QLineEdit, QMessageBox, QPushButton, QScrollArea, QSizePolicy, QSpinBox, - QVBoxLayout, QWidget, QMenu, QComboBox, + QVBoxLayout, QWidget, QMenu, QComboBox, QTabWidget, ) +from core_lib.qt.item_button import ItemButton from manager.profile import ProfileDetail, ProfileManager, ProfileSummary, UpdateProfileRequest from manager.game import AvailableVersion from pages.add_modded_version import AddModdedVersionDialog -class ManageProfileItem(QPushButton): +class ManageProfileItem(ItemButton): selected = Signal(object) def __init__(self, app, profile: ProfileSummary, @@ -94,6 +96,8 @@ class ManageProfilePage(QWidget): Profile manage page """ + selected_profile_changed = Signal(object) + VERSION_CATEGORIES = ( ("Vanilla", "vanilla"), ("Modded", "modded"), @@ -136,12 +140,14 @@ class ManageProfilePage(QWidget): self.options_layout.setContentsMargins(20, 16, 20, 20) self.options_layout.setSpacing(14) self.options_scroll.setWidget(self.options_content) - columns.addWidget(self.options_scroll, 3) + # Tabs + self.profile_tabs = QTabWidget() self.empty_label = QLabel(self.app.tr_text("Select a profile from the list to edit its settings.")) self.empty_label.setAlignment(Qt.AlignmentFlag.AlignCenter) self.empty_label.setWordWrap(True) self.options_layout.addWidget(self.empty_label, 1) + columns.addWidget(self.profile_tabs, 3) self.editor = QFrame() self.editor.setObjectName("profileEditor") @@ -222,6 +228,21 @@ class ManageProfilePage(QWidget): self._load_type_dropdown() self.refresh_profiles() + self._tabs = { + "Profile settings": self.options_scroll + } + + self.app.i18n.language_changed.connect(self.load_profile_page_for_tabs) + self.load_profile_page_for_tabs() + + def load_profile_page_for_tabs(self, *_args): + for tab_name, page in self._tabs.items(): + index = self.profile_tabs.indexOf(page) + if index < 0: + self.profile_tabs.addTab(page, self.app.tr_text(tab_name)) + else: + self.profile_tabs.setTabText(index, self.app.tr_text(tab_name)) + @staticmethod def _scroll_area(name: str) -> QScrollArea: area = QScrollArea() @@ -303,6 +324,7 @@ class ManageProfilePage(QWidget): else: self.editor.hide() self.empty_label.show() + self.selected_profile_changed.emit(None) def select_profile(self, profile: ProfileSummary) -> None: detail = self.profile_manager.get_profile(profile.id) @@ -318,6 +340,7 @@ class ManageProfilePage(QWidget): self._set_detail(detail) self.empty_label.hide() self.editor.show() + self.selected_profile_changed.emit(detail) def _select_version(self, version_id: str) -> None: for index in range(self.version_dropdown.count()): @@ -496,3 +519,66 @@ class ManageProfilePage(QWidget): if answer == QMessageBox.StandardButton.Yes: if self.profile_manager.remove_profile(profile_id): self.selected_profile_id = None + + def add_page(self, page_name: str, page: QScrollArea) -> Callable[[], None]: + """Add a plugin tab and return an idempotent cleanup callback.""" + if not isinstance(page_name, str) or not page_name.strip(): + raise ValueError("Invalid page name") + + if not isinstance(page, QScrollArea): + raise ValueError("Page must be a QScrollArea") + + if page_name in self._tabs: + raise ValueError("Page name already exists") + if page in self._tabs.values(): + raise ValueError("Page is already registered") + + self._tabs[page_name] = page + self.load_profile_page_for_tabs() + + def remove_page(): + # An old cleanup callback must not remove a replacement tab. + if self._tabs.get(page_name) is page: + self.remove_page(page_name) + + return remove_page + + def remove_page(self, page_name: str) -> bool: + if page_name == "Profile settings": + raise ValueError("The profile settings page cannot be removed") + page = self._tabs.pop(page_name, None) + if page is None: + return False + index = self.profile_tabs.indexOf(page) + if index >= 0: + self.profile_tabs.removeTab(index) + page.hide() + page.deleteLater() + return True + + def register_plugin_apis(self, plugin_manager): + plugin_manager.register_api("launcher.manage_profile_page.add_page", self.add_page) + plugin_manager.register_api("launcher.manage_profile_page.remove_page", self.remove_page) + plugin_manager.register_api("launcher.manage_profile_page.subscribe_profile", self.subscribe_profile) + + def subscribe_profile(self, callback: Callable) -> Callable[[], None]: + """Send saved details for the editor selection, including the initial state.""" + if not callable(callback): + raise TypeError("Profile callback must be callable") + self.selected_profile_changed.connect(callback) + connected = True + + def cleanup(): + nonlocal connected + if connected: + self.selected_profile_changed.disconnect(callback) + connected = False + + try: + detail = (self.profile_manager.get_profile(self.selected_profile_id) + if self.selected_profile_id is not None else None) + callback(detail) + except BaseException: + cleanup() + raise + return cleanup diff --git a/pages/plugins.py b/pages/plugins.py new file mode 100644 index 0000000..c32070c --- /dev/null +++ b/pages/plugins.py @@ -0,0 +1,413 @@ +from pathlib import Path + +from PySide6.QtCore import Qt, QSize, QUrl +from PySide6.QtGui import QDesktopServices, QIcon, QPixmap, QMovie +from PySide6.QtWidgets import ( + QWidget, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, + QListWidget, QListWidgetItem, QPushButton, QComboBox, QSplitter, + QStackedWidget, QScrollArea, QFormLayout, QDialogButtonBox, QSizePolicy, QTextBrowser, QFrame, +) + +from manager.plugins import Plugin + + +class PluginsDialog(QDialog): + def __init__(self, app, plugin_manager, parent=None): + super().__init__(parent) + self.app = app + self.plugin_manager = plugin_manager + self.icon_movies: list[QMovie] = [] + self.default_plugin_icon = self.app.get_icon(Path(self.app.icon_dir, "plugin.png")) + self.setWindowIcon(self.default_plugin_icon) + self.setObjectName("pluginsDialog") + self.resize(960, 620) + self.setMinimumSize(720, 480) + + layout = QVBoxLayout(self) + layout.setContentsMargins(20, 16, 20, 16) + layout.setSpacing(14) + + header = QHBoxLayout() + self.title_label = QLabel() + self.title_label.setObjectName("pluginsTitle") + self.reload_button = QPushButton() + self.reload_button.setIcon(self.app.get_icon(Path(self.app.icon_dir, "refresh.png"))) + self.folder_button = QPushButton() + self.folder_button.setIcon(self.app.get_icon(Path(self.app.icon_dir, "file.png"))) + + header.addWidget(self.title_label) + header.addStretch() + header.addWidget(self.folder_button) + header.addWidget(self.reload_button) + layout.addLayout(header) + + # Split plugin list and details + splitter = QSplitter(Qt.Orientation.Horizontal) + splitter.setChildrenCollapsible(False) + + sidebar = QWidget() + sidebar.setMinimumWidth(260) + sidebar_layout = QVBoxLayout(sidebar) + sidebar_layout.setContentsMargins(0, 0, 12, 0) + sidebar_layout.setSpacing(10) + + # Label + self.installed_label = QLabel() + self.installed_label.setObjectName("pluginsSectionTitle") + + self.search_edit = QLineEdit() + self.search_edit.setClearButtonEnabled(True) + self.filter_combo = QComboBox() + # Plugin state filter + for state in ("all", "enabled", "disabled"): + self.filter_combo.addItem("", state) + + # Plugin list + self.plugin_list = QListWidget() + self.plugin_list.setObjectName("pluginList") + self.plugin_list.setIconSize(QSize(32, 32)) + self.plugin_list.setSpacing(3) + self.plugin_list.setWordWrap(True) + self.plugin_list.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + + self.count_label = QLabel() + self.count_label.setObjectName("pluginsMuted") + + # Bind widgets + sidebar_layout.addWidget(self.installed_label) + sidebar_layout.addWidget(self.search_edit) + sidebar_layout.addWidget(self.filter_combo) + sidebar_layout.addWidget(self.plugin_list, 1) + sidebar_layout.addWidget(self.count_label) + splitter.addWidget(sidebar) + + # Stack widget (For plugin details) + self.details_stack = QStackedWidget() + + empty_page = QWidget() + empty_layout = QVBoxLayout(empty_page) + empty_layout.addStretch() + + self.empty_title = QLabel() + self.empty_title.setObjectName("pluginsEmptyTitle") + self.empty_title.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.empty_text = QLabel() + self.empty_text.setObjectName("pluginsMuted") + self.empty_text.setWordWrap(True) + self.empty_text.setAlignment(Qt.AlignmentFlag.AlignCenter) + + empty_layout.addWidget(self.empty_title) + empty_layout.addWidget(self.empty_text) + empty_layout.addStretch() + self.details_stack.addWidget(empty_page) + + # Scroll area for plugin details + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + scroll.setFrameShape(QScrollArea.Shape.NoFrame) + + details = QWidget() + details_layout = QVBoxLayout(details) + details_layout.setContentsMargins(24, 20, 20, 20) + details_layout.setSpacing(18) + + # Plugin identity inside the details layout + identity = QHBoxLayout() + self.plugin_icon = QLabel() + self.plugin_icon.setObjectName("pluginIcon") + self.plugin_icon.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.plugin_icon.setFixedSize(56, 56) + self.plugin_icon.setPixmap(self.default_plugin_icon.pixmap(QSize(48, 48))) + + identity.addWidget(self.plugin_icon) + identity_text = QVBoxLayout() + + self.name_label = QLabel() + self.name_label.setObjectName("pluginName") + self.name_label.setWordWrap(True) + self.group_label = QLabel() + self.group_label.setObjectName("pluginsMuted") + self.group_label.setWordWrap(True) + + identity_text.addWidget(self.name_label) + identity_text.addWidget(self.group_label) + identity.addLayout(identity_text, 1) + details_layout.addLayout(identity) + + # Status of the plugin + self.status_label = QLabel() + self.status_label.setObjectName("pluginsMuted") + details_layout.addWidget(self.status_label) + + # Plugin description + self.overview_label = QLabel() + self.overview_label.setObjectName("pluginsSectionTitle") + self.description_browser = QTextBrowser() # use QTextBrowser for Markdown support + self.description_browser.setFrameShape(QFrame.Shape.NoFrame) + details_layout.addWidget(self.overview_label) + details_layout.addWidget(self.description_browser) + + # Metadata + metadata = QFormLayout() + metadata.setHorizontalSpacing(24) + metadata.setVerticalSpacing(14) + metadata.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) + metadata.setRowWrapPolicy(QFormLayout.RowWrapPolicy.WrapLongRows) + + self.field_labels = {} + self.field_values = {} + + for key in ("Version", "Plugin ID", "Group", "Required API version", "Location"): + title = QLabel() + title.setObjectName("pluginsMuted") + value = QLabel() + value.setWordWrap(True) + value.setMinimumWidth(0) + value.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) + value.setTextFormat(Qt.TextFormat.PlainText) + value.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + metadata.addRow(title, value) + self.field_labels[key] = title + self.field_values[key] = value + + details_layout.addLayout(metadata) + + # Buttons + self.open_plugin_button = QPushButton() + self.open_plugin_button.setIcon(self.app.get_icon(Path(self.app.icon_dir, "file.png"))) + self.toggle_plugin_button = QPushButton() + + details_layout.addWidget(self.open_plugin_button, 0, Qt.AlignmentFlag.AlignLeft) + details_layout.addWidget(self.toggle_plugin_button, 0, Qt.AlignmentFlag.AlignLeft) + details_layout.addStretch() + + scroll.setWidget(details) + self.details_stack.addWidget(scroll) + + splitter.addWidget(self.details_stack) + splitter.setStretchFactor(0, 0) + splitter.setStretchFactor(1, 1) + splitter.setSizes([310, 610]) + layout.addWidget(splitter, 1) + self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + self.buttons.rejected.connect(self.reject) + layout.addWidget(self.buttons) + + # Plugin metadata is plain text, never HTML. + for label in (self.name_label, self.group_label, self.plugin_icon): + label.setTextFormat(Qt.TextFormat.PlainText) + + # Bind events + self.search_edit.textChanged.connect(self.refresh_plugins) + self.filter_combo.currentIndexChanged.connect(self.refresh_plugins) + self.plugin_list.currentItemChanged.connect(self._show_plugin_details) + self.reload_button.clicked.connect(self.reload_plugins) + self.folder_button.clicked.connect(self._open_plugins_directory) + self.open_plugin_button.clicked.connect(self._open_selected_directory) + self.toggle_plugin_button.clicked.connect(self._toggle_selected_plugin) + self.plugin_manager.signals.plugins_loaded.connect(self.refresh_plugins) + self.plugin_manager.signals.plugin_state_changed.connect(self.refresh_plugins) + self.app.i18n.language_changed.connect(self.retranslate_ui) + + # Apply qss + self.app.apply_qss(Path("plugins.qss"), self.setStyleSheet) + + # Apply translations + self.retranslate_ui() + + def retranslate_ui(self, *_args): + tr = self.app.tr_text + + self.setWindowTitle(tr("Plugins")) + + self.title_label.setText(tr("Plugins")) + self.installed_label.setText(tr("Installed")) + self.reload_button.setText(tr("Reload plugins")) + self.folder_button.setText(tr("Plugins folder")) + + self.search_edit.setPlaceholderText(tr("Search plugins…")) + self.search_edit.setAccessibleName(tr("Search plugins…")) + self.filter_combo.setAccessibleName(tr("Filter plugins")) + + for index, text in enumerate(("All plugins", "Enabled", "Disabled")): + self.filter_combo.setItemText(index, tr(text)) + + self.overview_label.setText(tr("Overview")) + self.description_browser.setText(tr("This plugin does not provide a description.")) + + self.open_plugin_button.setText(tr("Open plugin folder")) + self.buttons.button(QDialogButtonBox.StandardButton.Close).setText(tr("Close")) + + for key, label in self.field_labels.items(): + label.setText(tr(key)) + + self.refresh_plugins() + + def refresh_plugins(self, *_args): + current = self.plugin_list.currentItem() + + selected_path = current.data(Qt.ItemDataRole.UserRole).path if current else None + query = self.search_edit.text().strip().casefold() + state = self.filter_combo.currentData() + + plugins = sorted(self.plugin_manager.plugins, key=lambda entry: entry.name.casefold()) + for movie in self.icon_movies: + movie.stop() + movie.frameChanged.disconnect() + movie.error.disconnect() + movie.deleteLater() + self.icon_movies.clear() + self.plugin_list.blockSignals(True) + self.plugin_list.clear() + + selected_item = None + for plugin in plugins: + if query and query not in f"{plugin.name} {plugin.group} {plugin.id}".casefold(): + continue + if (state == "enabled" and not plugin.enabled) or (state == "disabled" and plugin.enabled): + continue + item = QListWidgetItem(f"{plugin.name}\n{plugin.group} · {plugin.version}") + item.setIcon(self.default_plugin_icon) + item.setSizeHint(QSize(240, 70)) + item.setData(Qt.ItemDataRole.UserRole, plugin) + self.plugin_list.addItem(item) + self._load_plugin_icon(item, plugin) + if plugin.path == selected_path: + selected_item = item + + if self.plugin_list.count(): + self.plugin_list.setCurrentItem(selected_item or self.plugin_list.item(0)) + + self.plugin_list.blockSignals(False) + self.count_label.setText(self.app.tr_text( + "{visible} of {total} plugins", visible=self.plugin_list.count(), total=len(plugins), + )) + self._show_plugin_details(self.plugin_list.currentItem()) + + def _show_plugin_details(self, item, _previous=None): + tr = self.app.tr_text + if item is None: + self.toggle_plugin_button.setEnabled(False) + self.details_stack.setCurrentIndex(0) + if self.plugin_manager.plugins: + self.empty_title.setText(tr("No matching plugins")) + self.empty_text.setText(tr("Try another search or change the filter.")) + else: + self.empty_title.setText(tr("No plugins loaded")) + self.empty_text.setText(tr("Add plugins to your plugins folder, then click Reload plugins.")) + return + + plugin: Plugin = item.data(Qt.ItemDataRole.UserRole) + + if plugin.description: + self.description_browser.setMarkdown(plugin.description) + else: + self.description_browser.setText(tr("This plugin does not provide a description.")) + + self.toggle_plugin_button.setText(tr("Disable plugin") if plugin.enabled else tr("Enable plugin")) + self.toggle_plugin_button.setEnabled(not plugin.is_changing_state) + self.details_stack.setCurrentIndex(1) + self.plugin_icon.setPixmap(item.icon().pixmap(QSize(48, 48))) + self.name_label.setText(plugin.name) + self.group_label.setText(plugin.group) + self.status_label.setText(tr("Enabled") if plugin.enabled else tr("Disabled")) + values = { + "Version": plugin.version, + "Plugin ID": plugin.id, + "Group": plugin.group, + "Required API version": str(plugin.api_version_range), + "Location": str(plugin.path), + } + + for key, value in values.items(): + self.field_values[key].setText(value) + + def _toggle_selected_plugin(self): + item: QListWidgetItem | None = self.plugin_list.currentItem() + if item is None: + return + plugin: Plugin = item.data(Qt.ItemDataRole.UserRole) + self.toggle_plugin_button.setEnabled(False) + try: + self.plugin_manager.set_plugin_enabled(plugin, not plugin.enabled) + finally: + self._show_plugin_details(self.plugin_list.currentItem()) + + def _load_plugin_icon(self, item: QListWidgetItem, plugin: Plugin): + path = plugin.icon_path + if path is None or path.suffix.lower() not in (".gif", ".png", ".jpg", ".jpeg", ".bmp"): + return + + # Load custom artwork directly to preserve its original colors. + pixmap = QPixmap(str(path)) + if pixmap.isNull(): + return + item.setIcon(QIcon(pixmap)) + if path.suffix.lower() != ".gif": + return + + movie = QMovie(str(path), parent=self) + if not movie.isValid(): + movie.deleteLater() + return + movie.setScaledSize(pixmap.size().scaled(QSize(48, 48), Qt.AspectRatioMode.KeepAspectRatio)) + movie.frameChanged.connect(lambda _frame, target=item, animation=movie: + self._update_plugin_movie(target, animation)) + movie.error.connect(lambda _error, target=item, animation=movie: + self._stop_plugin_movie(target, animation)) + self.icon_movies.append(movie) + movie.jumpToFrame(0) + if self.isVisible(): + movie.start() + + def _update_plugin_movie(self, item: QListWidgetItem, movie: QMovie): + pixmap = movie.currentPixmap() + if pixmap.isNull(): + return + item.setIcon(QIcon(pixmap)) + if self.plugin_list.currentItem() is item: + self.plugin_icon.setPixmap(pixmap) + + def _stop_plugin_movie(self, item: QListWidgetItem, movie: QMovie): + movie.stop() + item.setIcon(self.default_plugin_icon) + if self.plugin_list.currentItem() is item: + self.plugin_icon.setPixmap(self.default_plugin_icon.pixmap(QSize(48, 48))) + + def showEvent(self, event): + super().showEvent(event) + for movie in self.icon_movies: + movie.start() + + def hideEvent(self, event): + for movie in self.icon_movies: + movie.stop() + super().hideEvent(event) + + def reload_plugins(self): + self.reload_button.setEnabled(False) + try: + self.plugin_manager.signals.reload_plugins.emit() + finally: + self.reload_button.setEnabled(True) + + def _open_directory(self, path: Path): + try: + path.mkdir(parents=True, exist_ok=True) + if not QDesktopServices.openUrl(QUrl.fromLocalFile(str(path.resolve()))): + raise OSError(self.app.tr_text("Unable to open folder: {path}", path=path)) + except OSError as e: + self.app.widget_manager.signal.show_and_print_error_message.emit({ + "title": self.app.tr_text("Plugin Error"), + "message": str(e), + "error": str(e), + }) + + def _open_plugins_directory(self): + self._open_directory(self.app.plugins_dir) + + def _open_selected_directory(self): + item = self.plugin_list.currentItem() + if item: + self._open_directory(item.data(Qt.ItemDataRole.UserRole).path) diff --git a/pages/settings.py b/pages/settings.py index cf684ee..a1f192b 100644 --- a/pages/settings.py +++ b/pages/settings.py @@ -15,9 +15,10 @@ from PySide6.QtWidgets import ( QWidget, QScrollArea, QSizePolicy, QSpinBox, ) -from constant import LAUNCHER_DESCRIPTION, LAUNCHER_NAME, LAUNCHER_VERSION +from constant import LAUNCHER_DESCRIPTION, LAUNCHER_NAME, LAUNCHER_VERSION, LAUNCHER_DESCRIPTION_KEYWORD from core_lib.qt import messagebox from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings +from pages.plugins import PluginsDialog LANGUAGE_LABELS = { "en": "English", @@ -201,10 +202,20 @@ class SettingsPage(QWidget): ) scroll_layout.addWidget(button) + plugins_button = SettingsItem(tr("Plugins"), tr("Browse installed plugins")) + plugins_button.clicked.connect(self._open_plugins_dialog) + scroll_layout.addWidget(plugins_button) scroll_layout.addStretch() layout.addWidget(scroll_area) return page + def _open_plugins_dialog(self): + dialog = PluginsDialog(self.app, self.app.plugin_manager, self) + try: + dialog.exec() + finally: + dialog.deleteLater() + def _create_general_page(self) -> QWidget: tr = self.app.tr_text page = SettingsSubPage(tr("General"), self._go_back) @@ -309,7 +320,9 @@ class SettingsPage(QWidget): brand_label.setObjectName("settingsBrand") version_label = QLabel(tr("Version: {version}", version=LAUNCHER_VERSION)) version_label.setObjectName("settingsVersion") - description = QPlainTextEdit(LAUNCHER_DESCRIPTION) + + description_text = self.app.tr_text(LAUNCHER_DESCRIPTION_KEYWORD) + description = QPlainTextEdit(description_text if description_text != LAUNCHER_DESCRIPTION_KEYWORD else LAUNCHER_DESCRIPTION) description.setObjectName("settingsDescription") description.setReadOnly(True) diff --git a/pyproject.toml b/pyproject.toml index fbccbb5..3105535 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "testlauncher" -version = "0.0.9a0" +version = "0.1.0a0" description = "A lightweight Minecraft launcher." readme = "README.md" requires-python = ">=3.10" diff --git a/resources/builtin_plugins/experimental_farm/__init__.py b/resources/builtin_plugins/experimental_farm/__init__.py index 99ec4c3..4666e5b 100644 --- a/resources/builtin_plugins/experimental_farm/__init__.py +++ b/resources/builtin_plugins/experimental_farm/__init__.py @@ -1,7 +1,10 @@ -from TapLauncher import Plugin +from TapLauncher import Plugin, PluginContext class ExperimentalFarm(Plugin): pass -def entry(context: dict) -> None: - pass \ No newline at end of file +def entry(context: PluginContext) -> None: + context.data_dir.mkdir(parents=True, exist_ok=True) + context.logger.info("Experimental Farm initialized") + list_apis = context.get_api("launcher.apis.list") + context.logger.debug("Available launcher APIs: %s", list_apis()) \ No newline at end of file diff --git a/resources/builtin_plugins/experimental_farm/nugget.gif b/resources/builtin_plugins/experimental_farm/nugget.gif new file mode 100644 index 0000000..654f95f Binary files /dev/null and b/resources/builtin_plugins/experimental_farm/nugget.gif differ diff --git a/resources/builtin_plugins/experimental_farm/plugin.toml b/resources/builtin_plugins/experimental_farm/plugin.toml index 22dff0a..5c4b7d0 100644 --- a/resources/builtin_plugins/experimental_farm/plugin.toml +++ b/resources/builtin_plugins/experimental_farm/plugin.toml @@ -1,5 +1,8 @@ group = "net.wei" id = "experimentalfarm" -name = "Experimental Farm" -version = ">=1" -entrypoint = "__init__.py:entry" \ No newline at end of file +name = "實驗田" +version = "1.0.0" +api_version = ">=0.0.1" +entrypoint = "__init__.py:entry" # Python file name:endpoint +icon = "nugget.gif" # Relative to this plugin directory; GIF, PNG, JPG or BMP +description = "A experimental plugin!" \ No newline at end of file diff --git a/resources/icons/COPYRIGHT.md b/resources/icons/COPYRIGHT.md index 32074c8..58d8793 100644 --- a/resources/icons/COPYRIGHT.md +++ b/resources/icons/COPYRIGHT.md @@ -7,4 +7,5 @@ - modLoader/fabric.png : [Source](https://fabricmc.net/assets/logo.png) - modLoader/neoforged.png : [Source](https://raw.githubusercontent.com/neoforged/.github/refs/heads/main/art/neoforged.ico) - vanilla.png : [Source](https://en.wikipedia.org/wiki/File:Updated_Minecraft_cube.svg) +- refresh.png (modified) : [Source](https://uxwing.com/reload-icon/) ## For the icon owner: If you want to take down icon that infringing upon your copyright. Contact us with this [link](https://repo.weispace.net/wei/Launcher) \ No newline at end of file diff --git a/resources/icons/file.png b/resources/icons/file.png new file mode 100644 index 0000000..e6d8d01 Binary files /dev/null and b/resources/icons/file.png differ diff --git a/resources/icons/refresh.png b/resources/icons/refresh.png new file mode 100644 index 0000000..1f11be6 Binary files /dev/null and b/resources/icons/refresh.png differ diff --git a/resources/translations/en.json b/resources/translations/en.json index 3884526..3b50f94 100644 --- a/resources/translations/en.json +++ b/resources/translations/en.json @@ -1,4 +1,31 @@ { + "Profile settings": "Profile settings", + "Enable plugin": "Enable plugin", + "Disable plugin": "Disable plugin", + "Plugins": "Plugins", + "Installed": "Installed", + "Reload plugins": "Reload plugins", + "Plugins folder": "Plugins folder", + "Search plugins…": "Search plugins…", + "Filter plugins": "Filter plugins", + "All plugins": "All plugins", + "Enabled": "Enabled", + "Disabled": "Disabled", + "Overview": "Overview", + "This plugin does not provide a description.": "This plugin does not provide a description.", + "Open plugin folder": "Open plugin folder", + "Plugin ID": "Plugin ID", + "Group": "Group", + "Required API version": "Required API version", + "Location": "Location", + "{visible} of {total} plugins": "{visible} of {total} plugins", + "No matching plugins": "No matching plugins", + "Try another search or change the filter.": "Try another search or change the filter.", + "No plugins loaded": "No plugins loaded", + "Add plugins to your plugins folder, then click Reload plugins.": "Add plugins to your plugins folder, then click Reload plugins.", + "Unable to open folder: {path}": "Unable to open folder: {path}", + "Plugin Error": "Plugin Error", + "Browse installed plugins": "Browse installed plugins", "About": "About", "Account": "Account", "Account status": "Account status", @@ -131,6 +158,7 @@ "Redownload": "Redownload", "Refresh": "Refresh", "Refresh all": "Refresh all", + "Refresh avatar cache": "Refresh avatar cache", "Refresh failed": "Refresh failed", "Refresh token": "Refresh token", "Refresh versions": "Refresh versions", @@ -276,6 +304,7 @@ "An unexpected error occurred while fetching version manifest: {error}": "An unexpected error occurred while fetching version manifest: {error}", "Unable to launch profile {profile}: {error}": "Unable to launch profile {profile}: {error}", "To make all page apply new language. Is recommend to restart the launcher after change it.": "To make all page apply new language. Is recommend to restart the launcher after change it.", + "To make all page apply new theme. Is recommend to restart the launcher after change it.": "To make all page apply new theme. Is recommend to restart the launcher after change it.", "Save Log": "Save Log", "Select where to save the log file": "Select where to save the log file", "Text Files (*.txt);;All Files (*)": "Text Files (*.txt);;All Files (*)", @@ -306,5 +335,6 @@ "Vanilla": "Vanilla", "minutes": "minutes", "{account} is currently signed in.": "{account} is currently signed in.", - "{account}'s session has expired.": "{account}'s session has expired." + "{account}'s session has expired.": "{account}'s session has expired.", + "$ABOUT_THIS_LAUNCHER": "" } diff --git a/resources/translations/zh-TW.json b/resources/translations/zh-TW.json index 7b6f1e7..81f6839 100644 --- a/resources/translations/zh-TW.json +++ b/resources/translations/zh-TW.json @@ -1,4 +1,31 @@ { + "Profile settings": "設定檔設定", + "Enable plugin": "啟用插件", + "Disable plugin": "停用插件", + "Plugins": "插件", + "Installed": "已安裝", + "Reload plugins": "重新載入插件", + "Plugins folder": "插件資料夾", + "Search plugins…": "搜尋插件…", + "Filter plugins": "篩選插件", + "All plugins": "所有插件", + "Enabled": "已啟用", + "Disabled": "已停用", + "Overview": "概覽", + "This plugin does not provide a description.": "此插件未提供說明。", + "Open plugin folder": "開啟插件資料夾", + "Plugin ID": "插件 ID", + "Group": "群組", + "Required API version": "所需 API 版本", + "Location": "位置", + "{visible} of {total} plugins": "顯示 {visible} / {total} 個插件", + "No matching plugins": "找不到符合條件的插件", + "Try another search or change the filter.": "請嘗試其他搜尋文字或變更篩選條件。", + "No plugins loaded": "尚未載入插件", + "Add plugins to your plugins folder, then click Reload plugins.": "將插件放入插件資料夾,然後按「重新載入插件」。", + "Unable to open folder: {path}": "無法開啟資料夾:{path}", + "Plugin Error": "插件錯誤", + "Browse installed plugins": "瀏覽已安裝的插件", "About": "關於", "Account": "帳號", "Account status": "帳號狀態", @@ -130,6 +157,7 @@ "Redownload": "重新下載", "Refresh": "重新整理", "Refresh all": "全部重新整理", + "Refresh avatar cache": "重新整理頭像快取", "Refresh failed": "更新令牌失敗", "Refresh token": "重新整理", "Refresh versions": "重新整理版本", @@ -276,6 +304,7 @@ "An unexpected error occurred while fetching version manifest: {error}": "取得版本資訊時發生非預期錯誤:{error}", "Unable to launch profile {profile}: {error}": "無法啟動設定檔 {profile}:{error}", "To make all page apply new language. Is recommend to restart the launcher after change it.": "為了讓所有頁面套用語言更新,建議在修改後重新啟動啟動器。", + "To make all page apply new theme. Is recommend to restart the launcher after change it.": "為了讓所有頁面套用新的佈景主題,建議在修改後重新啟動啟動器。", "Save Log": "儲存紀錄", "Select where to save the log file": "選擇紀錄檔的儲存位置", "Text Files (*.txt);;All Files (*)": "文字檔案 (*.txt);;所有檔案 (*)", @@ -306,5 +335,6 @@ "Vanilla": "原版", "minutes": "分鐘", "{account} is currently signed in.": "{account} 目前已登入。", - "{account}'s session has expired.": "{account} 的工作階段已過期。" + "{account}'s session has expired.": "{account} 的工作階段已過期。", + "$ABOUT_THIS_LAUNCHER": "一個使用Python編寫的非官方 Minecraft 啟動器。旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\n本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開開發的專案。" } diff --git a/tests/test_plugins.py b/tests/test_plugins.py new file mode 100644 index 0000000..98c8644 --- /dev/null +++ b/tests/test_plugins.py @@ -0,0 +1,600 @@ +import sys +from types import SimpleNamespace, ModuleType +from importlib.machinery import ModuleSpec +from unittest.mock import Mock + +import pytest + +from manager.plugins import PluginManager +from manager.settings import SettingsManager +from manager.settings_models import PluginSettings +from manager.widgets import WidgetManager + + +@pytest.fixture +def plugin_manager(tmp_path): + settings = SettingsManager(tmp_path.parent / (tmp_path.name + "-settings.toml")) + settings.register("plugins", PluginSettings) + settings.load_defaults() + widget_manager = WidgetManager() + messages = [] + contexts = [] + widget_manager.signal.show_and_print_error_message.connect(contexts.append) + widget_manager.signal.show_and_print_error_message.connect(lambda context: messages.append(context["message"])) + app = SimpleNamespace( + plugins_dir=tmp_path, + data_dir=tmp_path.parent / (tmp_path.name + "-data"), + aboutToQuit=Mock(), + internal_plugins_dir=tmp_path.parent / (tmp_path.name + "-builtin"), + widget_manager=widget_manager, + logger=Mock(), + error_contexts=contexts, + settings_manager=settings, + ) + previous_modules = set(sys.modules) + manager = PluginManager(app) + yield manager, messages + manager.shutdown_plugins() + for name in set(sys.modules) - previous_modules: + if name.startswith("_wheel_plugin_"): + sys.modules.pop(name, None) + + +def write_plugin(path, **values): + path.mkdir(exist_ok=True) + config = dict( + group="net.test", id="sample", name="Sample", version="1.0.0", + api_version=">=0.0.1", entrypoint="main.py:entry", + ) + config.update(values) + (path / "plugin.toml").write_text( + "\n".join(f'{key} = {value!r}' for key, value in config.items()), + encoding="utf-8", + ) + (path / "main.py").write_text("def entry(context):\n pass\n", encoding="utf-8") + + +def test_load_plugins_continues_after_error_and_reloads(plugin_manager): + manager, messages = plugin_manager + invalid = manager.app.plugins_dir / "invalid" + invalid.mkdir() + write_plugin(manager.app.plugins_dir / "valid") + + manager.load_plugins() + + assert [plugin.id for plugin in manager.plugins] == ["sample"] + assert len(messages) == 1 + assert str(invalid) in messages[0] + manager.app.logger.error.assert_not_called() + assert len(manager.app.error_contexts) == 1 + + manager.load_plugins() + + assert len(manager.plugins) == 1 + + +@pytest.mark.parametrize("values, error", [ + ({"version": "1.0.0junk"}, "Plugin version is invalid"), + ({"group": 123}, "Plugin group must be a string"), + ({"icon": 123}, "Plugin icon must be a string"), + ({"api_version": "invalid"}, "version range is invalid"), + ({"api_version": ">=999.0.0"}, "does not support"), + ({"entrypoint": "missing.py:entry"}, "Python file"), + ({"entrypoint": "main.py:missing"}, "does not exist in file"), + ({"entrypoint": "main.py:"}, "valid identifier"), + ({"entrypoint": "..:main.py:entry"}, "Invalid path part"), + ({"entrypoint": "main.py"}, "At least two parts"), +]) +def test_invalid_config_emits_error(plugin_manager, values, error): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir, **values) + + assert manager._load_plugin_config(plugin_dir) is None + assert len(messages) == 1 + assert str(plugin_dir / "plugin.toml") in messages[0] + assert error in messages[0] + + +def test_nested_entrypoint(plugin_manager): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir, entrypoint="nested:main.py:entry") + (plugin_dir / "nested").mkdir() + (plugin_dir / "main.py").rename(plugin_dir / "nested" / "main.py") + + assert manager._load_plugin_config(plugin_dir) is not None + assert messages == [] + + +def test_invalid_toml_emits_error(plugin_manager): + manager, messages = plugin_manager + (manager.app.plugins_dir / "plugin.toml").write_text("id = [", encoding="utf-8") + + assert manager._load_plugin_config(manager.app.plugins_dir) is None + assert len(messages) == 1 + assert "Failed to load plugin config" in messages[0] + + +def test_missing_plugins_directory_is_empty(plugin_manager): + manager, messages = plugin_manager + manager.app.plugins_dir /= "missing" + + manager.load_plugins() + + assert manager.plugins == [] + assert messages == [] + + +def test_plugins_directory_error_emits_error(plugin_manager): + manager, messages = plugin_manager + manager.app.plugins_dir /= "file" + manager.app.plugins_dir.write_text("", encoding="utf-8") + + manager.load_plugins() + + assert len(messages) == 1 + assert str(manager.app.plugins_dir) in messages[0] + + +@pytest.mark.parametrize("filename", ["main.py", "__init__.py"]) +def test_endpoint_returns_spec_without_executing_plugin(plugin_manager, filename): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir, entrypoint=f"{filename}:entry") + source = plugin_dir / filename + source.write_text( + 'raise RuntimeError("Must not execute during validation")\n' + 'def entry(context):\n pass\n', + encoding="utf-8", + ) + + plugin = manager._load_plugin_config(plugin_dir) + + assert plugin is not None + assert isinstance(plugin.module_spec, ModuleSpec) + assert plugin.module_spec.origin == str(source.resolve()) + assert plugin.module_spec.loader is not None + if filename == "__init__.py": + assert plugin.module_spec.submodule_search_locations == [str(plugin_dir.resolve())] + assert messages == [] + + +def test_specs_for_same_filename_in_different_plugins_have_distinct_names(plugin_manager): + manager, _ = plugin_manager + specs = [] + for name in ("first", "second"): + plugin_dir = manager.app.plugins_dir / name + write_plugin(plugin_dir) + specs.append(manager._check_and_return_plugin_endpoint_spec("main.py:entry", plugin_dir)) + + assert specs[0].name != specs[1].name + + +def test_init_registers_spec_name_and_supports_relative_imports(plugin_manager): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir, entrypoint="__init__.py:entry") + (plugin_dir / "__init__.py").write_text( + "from .helper import value\ndef entry(context):\n return value\n", + encoding="utf-8", + ) + (plugin_dir / "helper.py").write_text("value = 42\n", encoding="utf-8") + plugin = manager._load_plugin_config(plugin_dir) + assert plugin is not None + assert plugin.module_spec is not None + + assert manager._init_plugin_entry(plugin) + module = sys.modules[plugin.module_spec.name] + assert module.entry({}) == 42 + assert module.__name__ == plugin.module_spec.name + assert messages == [] + + +@pytest.mark.parametrize("source, error", [ + ('raise RuntimeError("broken plugin")\n', "broken plugin"), + ('raise SystemExit("plugin exit")\n', "plugin exit"), + ('entry = None\n', "not callable"), + ('del entry\n', "missing"), +]) +def test_init_failure_reports_once_and_cleans_module(plugin_manager, source, error): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir) + plugin = manager._load_plugin_config(plugin_dir) + assert plugin is not None + assert plugin.module_spec is not None + (plugin_dir / "main.py").write_text( + "def entry(context):\n pass\n" + source, encoding="utf-8", + ) + + assert not manager._init_plugin_entry(plugin) + assert plugin.module_spec.name not in sys.modules + assert len(messages) == 1 + assert plugin.id in messages[0] + assert error in messages[0] + context = manager.app.error_contexts[0] + assert context["title"] == "Plugin Error" + assert "Traceback" in context["error"] + if source.startswith("raise "): + assert str(plugin_dir / "main.py") in context["error"] + + +@pytest.mark.parametrize("missing_loader", [False, True]) +def test_init_missing_spec_or_loader_reports_error(plugin_manager, missing_loader): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir) + plugin = manager._load_plugin_config(plugin_dir) + assert plugin is not None + assert plugin.module_spec is not None + if missing_loader: + plugin.module_spec.loader = None + else: + plugin.module_spec = None + + assert not manager._init_plugin_entry(plugin) + assert len(messages) == 1 + assert "Module spec or loader is missing" in messages[0] + + +def test_failed_reload_restores_modules(plugin_manager, monkeypatch): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir, entrypoint="__init__.py:entry") + (plugin_dir / "__init__.py").write_text( + 'from . import helper\nraise RuntimeError("broken reload")\n' + 'def entry(context):\n pass\n', encoding="utf-8", + ) + (plugin_dir / "helper.py").write_text("value = 42\n", encoding="utf-8") + plugin = manager._load_plugin_config(plugin_dir) + assert plugin is not None + assert plugin.module_spec is not None + previous = ModuleType(plugin.module_spec.name) + monkeypatch.setitem(sys.modules, plugin.module_spec.name, previous) + + assert not manager._init_plugin_entry(plugin) + assert sys.modules[plugin.module_spec.name] is previous + assert plugin.module_spec.name + ".helper" not in sys.modules + assert len(messages) == 1 + + +def test_load_skips_failed_initialization_and_continues(plugin_manager): + manager, messages = plugin_manager + write_plugin(manager.app.plugins_dir / "valid") + broken_dir = manager.app.plugins_dir / "broken" + write_plugin(broken_dir, id="broken") + (broken_dir / "main.py").write_text( + 'raise RuntimeError("broken plugin")\ndef entry(context):\n pass\n', + encoding="utf-8", + ) + + manager.load_plugins() + + assert [plugin.id for plugin in manager.plugins] == ["sample"] + assert len(messages) == 1 + assert "broken plugin" in messages[0] + + +def test_incompatible_api_range_is_valid(plugin_manager): + manager, _ = plugin_manager + + valid, supported, required = manager._check_plugin_support_api_version(">=999.0.0") + + assert valid + assert not supported + assert str(required) == ">=999.0.0" + + +@pytest.mark.parametrize("user_plugins", ["missing", "empty", "installed"]) +def test_load_preserves_builtin_plugins(plugin_manager, user_plugins): + manager, messages = plugin_manager + root = manager.app.plugins_dir + manager.app.internal_plugins_dir = root / "builtin" + manager.app.plugins_dir = root / "user" + manager.app.internal_plugins_dir.mkdir() + write_plugin(manager.app.internal_plugins_dir / "internal", id="internal") + if user_plugins != "missing": + manager.app.plugins_dir.mkdir() + if user_plugins == "installed": + write_plugin(manager.app.plugins_dir / "external", id="external") + completed = [] + manager.signals.plugins_loaded.connect(lambda: completed.append(True)) + + manager.load_plugins() + + expected = ["internal", "external"] if user_plugins == "installed" else ["internal"] + assert [plugin.id for plugin in manager.plugins] == expected + assert completed == [True] + assert messages == [] + manager.load_plugins() + assert [plugin.id for plugin in manager.plugins] == expected + + +@pytest.mark.parametrize("filename", ["icon.gif", "icon.png", "icon.jpg", "icon.bmp", "ICON.PNG", "icon.jpeg"]) +def test_custom_icon_path_is_relative_to_plugin(plugin_manager, filename): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir, icon=f"images/{filename}") + (plugin_dir / "images").mkdir() + path = plugin_dir / "images" / filename + path.write_bytes(b"image validation happens in the UI") + + plugin = manager._load_plugin_config(plugin_dir) + + assert plugin is not None + assert plugin.icon_path == path.resolve() + assert messages == [] + + +@pytest.mark.parametrize("icon", ["", "missing.png", "icon.txt", "../outside.png"]) +def test_invalid_optional_icon_keeps_plugin_loadable(plugin_manager, icon): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir, icon=icon) + (plugin_dir / "icon.txt").write_text("not an image", encoding="utf-8") + (manager.app.plugins_dir / "outside.png").write_bytes(b"outside plugin") + + plugin = manager._load_plugin_config(plugin_dir) + + assert plugin is not None + assert plugin.icon_path is None + assert messages == [] + + +@pytest.fixture +def loaded_plugin(plugin_manager): + manager, _ = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir) + manager.load_plugins() + return manager.plugins[0] + + +def test_enable_provides_context_and_runs_entry_once(plugin_manager, loaded_plugin): + manager, messages = plugin_manager + plugin = loaded_plugin + entry = Mock() + plugin.entry = entry + + assert manager.enable_plugin(plugin) + assert manager.enable_plugin(plugin) + + entry.assert_called_once() + context = entry.call_args.args[0] + assert context.plugin_id == "net.test:sample" + assert context.plugin_dir == plugin.path + assert context.data_dir == (manager.app.data_dir / "plugins/net.test/sample").resolve() + assert context.data_dir.is_dir() + manager.app.logger.getChild.assert_called_once_with("plugins.net.test.sample") + info = [] + manager.widget_manager.signal.show_info_message.connect(info.append) + context.show_info("hello") + context.show_error("problem") + assert info == ["[net.test:sample] hello"] + assert messages == ["[net.test:sample] problem"] + assert plugin.enabled + + +def test_disable_runs_cleanup_in_reverse_order_once(plugin_manager, loaded_plugin): + manager, messages = plugin_manager + calls = [] + def entry(context): + context.on_cleanup(lambda: calls.append("first")) + context.on_cleanup(lambda: calls.append("second")) + loaded_plugin.entry = entry + + assert manager.enable_plugin(loaded_plugin) + assert manager.disable_plugin(loaded_plugin) + assert manager.disable_plugin(loaded_plugin) + + assert calls == ["second", "first"] + assert not loaded_plugin.enabled + assert messages == [] + + +@pytest.mark.parametrize("error", [RuntimeError("entry failed"), SystemExit("entry exited")]) +def test_entry_failure_cleans_partial_initialization(plugin_manager, loaded_plugin, error): + manager, messages = plugin_manager + cleanup = Mock() + def entry(context): + context.on_cleanup(cleanup) + raise error + loaded_plugin.entry = entry + + assert not manager.enable_plugin(loaded_plugin) + + cleanup.assert_called_once() + assert not loaded_plugin.enabled + assert not loaded_plugin._changing_state + assert len(messages) == 1 + assert str(error) in messages[0] + assert "Traceback" in manager.app.error_contexts[0]["error"] + + +def test_cleanup_failure_can_be_retried_without_repeating_successful_callbacks(plugin_manager, loaded_plugin): + manager, messages = plugin_manager + success = Mock() + failure = Mock(side_effect=[RuntimeError("cleanup failed"), None]) + def entry(context): + context.on_cleanup(success) + context.on_cleanup(failure) + loaded_plugin.entry = entry + assert manager.enable_plugin(loaded_plugin) + + assert not manager.disable_plugin(loaded_plugin) + assert loaded_plugin.enabled + success.assert_called_once() + assert len(messages) == 1 + assert manager.disable_plugin(loaded_plugin) + assert not loaded_plugin.enabled + success.assert_called_once() + assert failure.call_count == 2 + + +def test_reload_cleans_old_entry_and_restarts_only_enabled_plugin(plugin_manager): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir) + (plugin_dir / "main.py").write_text( + 'def entry(context):\n' + ' path = context.data_dir / "events.txt"\n' + ' def record(text):\n' + ' with path.open("a", encoding="utf-8") as f:\n' + ' f.write(text + "\\n")\n' + ' record("start")\n' + ' context.on_cleanup(lambda: record("stop"))\n', encoding="utf-8", + ) + write_plugin(manager.app.plugins_dir / "inactive", id="inactive") + manager.load_plugins() + old = next(plugin for plugin in manager.plugins if plugin.id == "sample") + assert manager.enable_plugin(old) + + manager.load_plugins() + + current = next(plugin for plugin in manager.plugins if plugin.id == "sample") + assert current is not old + assert not old.enabled + assert current.enabled + assert not next(plugin for plugin in manager.plugins if plugin.id == "inactive").enabled + path = manager.app.data_dir / "plugins/net.test/sample/events.txt" + assert path.read_text(encoding="utf-8").splitlines() == ["start", "stop", "start"] + assert manager.shutdown_plugins() + assert path.read_text(encoding="utf-8").splitlines() == ["start", "stop", "start", "stop"] + assert messages == [] + + +def test_enable_missing_entry_reports_error(plugin_manager, loaded_plugin): + manager, messages = plugin_manager + loaded_plugin.entry = None + + assert not manager.enable_plugin(loaded_plugin) + assert not loaded_plugin.enabled + assert len(messages) == 1 + assert "not been initialized" in messages[0] + + +def test_reload_does_not_replace_plugin_when_cleanup_fails(plugin_manager, loaded_plugin): + manager, messages = plugin_manager + cleanup = Mock(side_effect=RuntimeError("still running")) + loaded_plugin.entry = lambda context: context.on_cleanup(cleanup) + assert manager.enable_plugin(loaded_plugin) + + manager.load_plugins() + + assert manager.plugins == [loaded_plugin] + assert loaded_plugin.enabled + assert len(messages) == 1 + cleanup.side_effect = None + + +def test_set_plugin_enabled_persists_and_restores_after_restart(plugin_manager, loaded_plugin): + manager, messages = plugin_manager + settings = manager.app.settings_manager + settings.set("plugins", PluginSettings(enabled=["missing:plugin"])) + entry = Mock() + loaded_plugin.entry = entry + assert manager.set_plugin_enabled(loaded_plugin, True) + assert manager.set_plugin_enabled(loaded_plugin, True) + entry.assert_called_once() + assert settings.get("plugins", PluginSettings).enabled == ["missing:plugin", "net.test:sample"] + saved = settings.path.read_bytes() + assert manager.shutdown_plugins() + assert settings.path.read_bytes() == saved + + restored_settings = SettingsManager(settings.path) + restored_settings.register("plugins", PluginSettings) + restored_settings.load() + manager.app.settings_manager = restored_settings + restarted = PluginManager(manager.app) + try: + restarted.load_plugins() + plugin = restarted.plugins[0] + assert plugin.enabled + assert restarted.set_plugin_enabled(plugin, False) + restored_settings.load() + assert restored_settings.get("plugins", PluginSettings).enabled == ["missing:plugin"] + restarted.load_plugins() + assert not restarted.plugins[0].enabled + assert messages == [] + finally: + restarted.shutdown_plugins() + + +def test_failed_entry_does_not_persist_enabled_preference(plugin_manager, loaded_plugin): + manager, messages = plugin_manager + settings = manager.app.settings_manager + settings.save() + saved = settings.path.read_bytes() + loaded_plugin.entry = Mock(side_effect=RuntimeError("cannot start")) + + assert not manager.set_plugin_enabled(loaded_plugin, True) + + assert not loaded_plugin.enabled + assert settings.get("plugins", PluginSettings).enabled == [] + assert settings.path.read_bytes() == saved + assert len(messages) == 1 + + +def test_failed_cleanup_preserves_enabled_preference(plugin_manager, loaded_plugin): + manager, messages = plugin_manager + cleanup = Mock(side_effect=RuntimeError("cannot stop")) + loaded_plugin.entry = lambda context: context.on_cleanup(cleanup) + assert manager.set_plugin_enabled(loaded_plugin, True) + settings = manager.app.settings_manager + saved = settings.path.read_bytes() + + assert not manager.set_plugin_enabled(loaded_plugin, False) + + assert loaded_plugin.enabled + assert settings.get("plugins", PluginSettings).enabled == ["net.test:sample"] + assert settings.path.read_bytes() == saved + assert len(messages) == 1 + cleanup.side_effect = None + + +@pytest.mark.parametrize("was_enabled", [False, True]) +def test_save_failure_restores_runtime_and_preferences(plugin_manager, loaded_plugin, monkeypatch, was_enabled): + manager, messages = plugin_manager + settings = manager.app.settings_manager + settings.set("plugins", PluginSettings(enabled=["missing:plugin"])) + settings.save() + cleanup = Mock() + loaded_plugin.entry = lambda context: context.on_cleanup(cleanup) + if was_enabled: + assert manager.set_plugin_enabled(loaded_plugin, True) + before = list(settings.get("plugins", PluginSettings).enabled) + saved = settings.path.read_bytes() + monkeypatch.setattr(SettingsManager, "save", Mock(side_effect=PermissionError("read only"))) + + assert not manager.set_plugin_enabled(loaded_plugin, not was_enabled) + + assert loaded_plugin.enabled == was_enabled + assert settings.get("plugins", PluginSettings).enabled == before + assert settings.path.read_bytes() == saved + cleanup.assert_called_once() + assert len(messages) == 1 + assert "Failed to save enabled state" in messages[0] + + +def test_auto_enable_failure_keeps_saved_preference(plugin_manager): + manager, messages = plugin_manager + plugin_dir = manager.app.plugins_dir / "sample" + write_plugin(plugin_dir) + (plugin_dir / "main.py").write_text( + 'def entry(context):\n raise RuntimeError("startup failure")\n', encoding="utf-8", + ) + settings = manager.app.settings_manager + settings.set("plugins", PluginSettings(enabled=["net.test:sample", "missing:plugin"])) + settings.save() + saved = settings.path.read_bytes() + + manager.load_plugins() + + plugin = manager.plugins[0] + assert not plugin.enabled + assert settings.get("plugins", PluginSettings).enabled == ["net.test:sample", "missing:plugin"] + assert settings.path.read_bytes() == saved + assert len(messages) == 1 + assert manager.set_plugin_enabled(plugin, False) + assert settings.get("plugins", PluginSettings).enabled == ["missing:plugin"] diff --git a/tests/test_plugins_dialog.py b/tests/test_plugins_dialog.py new file mode 100644 index 0000000..8d28d2d --- /dev/null +++ b/tests/test_plugins_dialog.py @@ -0,0 +1,263 @@ +import logging +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from packaging.specifiers import SpecifierSet +from PySide6.QtCore import Qt +from PySide6.QtGui import QIcon, QImage, QColor, QMovie +from PySide6.QtWidgets import QApplication + +from core_lib.i18n import TranslationManager +from manager.plugins import Plugin, PluginManager +from manager.settings import SettingsManager +from manager.settings_models import PluginSettings +from manager.widgets import WidgetManager +from pages.plugins import PluginsDialog + + +@pytest.fixture +def plugin_dialog(tmp_path): + qt_app = QApplication.instance() or QApplication([]) + root = Path(__file__).resolve().parents[1] + i18n = TranslationManager(root / "resources/translations", "en") + settings = SettingsManager(tmp_path.parent / (tmp_path.name + "-settings.toml")) + settings.register("plugins", PluginSettings) + settings.load_defaults() + app = SimpleNamespace( + plugins_dir=tmp_path, i18n=i18n, tr_text=i18n.translate, + data_dir=tmp_path.parent / (tmp_path.name + "-data"), aboutToQuit=qt_app.aboutToQuit, + icon_dir=root / "resources/icons", get_icon=lambda path: QIcon(str(path)), + internal_plugins_dir=tmp_path.parent / (tmp_path.name + "-builtin"), + widget_manager=WidgetManager(), logger=logging.getLogger(__name__), + settings_manager=settings, + apply_qss=lambda path, callback: callback((root / "resources/styles" / path).read_text(encoding="utf-8")), + ) + manager = PluginManager(app) + for name, enabled in (("Zulu Tools", False), ("Alpha Tools", True)): + plugin = Plugin(name.lower().replace(" ", "-"), name, "net.test", "1.0.0", + SpecifierSet(">=0.0.1"), "main.py:entry", tmp_path / name) + plugin.enabled = enabled + manager.plugins.append(plugin) + dialog = PluginsDialog(app, manager) + yield dialog + manager.shutdown_plugins() + app.aboutToQuit.disconnect(manager.shutdown_plugins) + dialog.close() + dialog.deleteLater() + qt_app.processEvents() + + +def test_search_filter_and_selection(plugin_dialog): + dialog = plugin_dialog + assert dialog.plugin_list.count() == 2 + assert dialog.name_label.text() == "Alpha Tools" + dialog.plugin_list.setCurrentRow(1) + dialog.refresh_plugins() + assert dialog.name_label.text() == "Zulu Tools" + dialog.search_edit.setText("NET.TEST") + assert dialog.plugin_list.count() == 2 + dialog.filter_combo.setCurrentIndex(1) + assert dialog.plugin_list.count() == 1 + assert dialog.name_label.text() == "Alpha Tools" + dialog.search_edit.setText("no match") + assert dialog.plugin_list.count() == 0 + assert dialog.details_stack.currentIndex() == 0 + assert dialog.empty_title.text() == "No matching plugins" + dialog.search_edit.clear() + dialog.filter_combo.setCurrentIndex(2) + assert dialog.name_label.text() == "Zulu Tools" + + +def test_reload_signal_refreshes_empty_state(plugin_dialog): + dialog = plugin_dialog + dialog.reload_button.click() + assert dialog.plugin_manager.plugins == [] + assert dialog.plugin_list.count() == 0 + assert dialog.empty_title.text() == "No plugins loaded" + assert dialog.reload_button.isEnabled() + + +def test_language_change_preserves_selection(plugin_dialog): + dialog = plugin_dialog + dialog.plugin_list.setCurrentRow(1) + dialog.app.i18n.set_language("zh-TW") + assert dialog.windowTitle() == "插件" + assert dialog.name_label.text() == "Zulu Tools" + assert dialog.reload_button.text() == "重新載入插件" + + +def test_open_folder_failure_uses_widget_signal(plugin_dialog, monkeypatch): + dialog = plugin_dialog + messages = [] + urls = [] + dialog.app.widget_manager.signal.show_and_print_error_message.connect(messages.append) + monkeypatch.setattr("pages.plugins.QDesktopServices.openUrl", lambda url: urls.append(url) or False) + dialog.open_plugin_button.click() + assert len(urls) == 1 + assert urls[0].isLocalFile() + assert len(messages) == 1 + assert "Unable to open folder" in messages[0]["message"] + + +def test_metadata_is_plain_text(plugin_dialog): + dialog = plugin_dialog + plugin = dialog.plugin_manager.plugins[0] + plugin.name = "Plugin name" + dialog.refresh_plugins() + item = next(dialog.plugin_list.item(i) for i in range(dialog.plugin_list.count()) + if dialog.plugin_list.item(i).data(Qt.ItemDataRole.UserRole) is plugin) + dialog.plugin_list.setCurrentItem(item) + assert dialog.name_label.textFormat() == Qt.TextFormat.PlainText + assert dialog.name_label.text() == plugin.name + + +def test_reload_displays_builtin_plugin_when_user_directory_is_missing(plugin_dialog): + dialog = plugin_dialog + dialog.app.internal_plugins_dir = Path(__file__).resolve().parents[1] / "resources/builtin_plugins" + dialog.app.plugins_dir /= "missing-user-plugins" + errors = [] + dialog.app.widget_manager.signal.show_and_print_error_message.connect(errors.append) + + dialog.reload_button.click() + + assert errors == [] + plugin_ids = [dialog.plugin_list.item(i).data(Qt.ItemDataRole.UserRole).id + for i in range(dialog.plugin_list.count())] + assert "experimentalfarm" in plugin_ids + assert dialog.details_stack.currentIndex() == 1 + + +@pytest.mark.parametrize("extension", ["png", "jpg", "bmp"]) +def test_custom_icon_preserves_color_and_aspect_ratio(plugin_dialog, extension): + dialog = plugin_dialog + plugin = dialog.plugin_manager.plugins[1] + path = dialog.app.plugins_dir / f"custom.{extension}" + image = QImage(80, 40, QImage.Format.Format_RGB32) + image.fill(QColor("red")) + assert image.save(str(path)) + plugin.icon_path = path + + dialog.refresh_plugins() + + pixmap = dialog.plugin_icon.pixmap() + assert pixmap.width() == 48 + assert pixmap.height() == 24 + assert pixmap.toImage().pixelColor(24, 12).red() > 240 + assert dialog.icon_movies == [] + + +@pytest.mark.parametrize("filename", ["missing.png", "broken.png", "broken.gif"]) +def test_unreadable_custom_icon_uses_default(plugin_dialog, filename): + dialog = plugin_dialog + plugin = dialog.plugin_manager.plugins[1] + plugin.icon_path = dialog.app.plugins_dir / filename + if filename != "missing.png": + plugin.icon_path.write_bytes(b"not an image") + + dialog.refresh_plugins() + + assert dialog.plugin_list.currentItem().icon().cacheKey() == dialog.default_plugin_icon.cacheKey() + assert not dialog.plugin_icon.pixmap().isNull() + assert dialog.icon_movies == [] + + +def test_gif_animates_list_and_details_and_stops_when_hidden(plugin_dialog): + dialog = plugin_dialog + dialog.plugin_manager.plugins[1].icon_path = ( + Path(__file__).resolve().parents[1] / "resources/builtin_plugins/experimental_farm/nugget.gif" + ) + dialog.refresh_plugins() + assert len(dialog.icon_movies) == 1 + movie = dialog.icon_movies[0] + dialog.show() + assert movie.state() == QMovie.MovieState.Running + first_icon = dialog.plugin_list.currentItem().icon().cacheKey() + assert movie.jumpToNextFrame() + assert dialog.plugin_list.currentItem().icon().cacheKey() != first_icon + assert dialog.plugin_icon.pixmap().toImage() == movie.currentPixmap().toImage() + dialog.hide() + assert movie.state() == QMovie.MovieState.NotRunning + dialog.refresh_plugins() + assert movie.state() == QMovie.MovieState.NotRunning + assert len(dialog.icon_movies) == 1 + + +def test_dialog_enables_and_disables_entry_with_context(plugin_dialog): + dialog = plugin_dialog + plugin = dialog.plugin_manager.plugins[0] + contexts = [] + cleanup = Mock() + def entry(context): + contexts.append(context) + context.on_cleanup(cleanup) + plugin.entry = entry + dialog.plugin_list.setCurrentRow(1) + assert dialog.toggle_plugin_button.text() == "Enable plugin" + + dialog.toggle_plugin_button.click() + + assert plugin.enabled + assert len(contexts) == 1 + assert contexts[0].plugin_id == "net.test:zulu-tools" + assert dialog.status_label.text() == "Enabled" + assert dialog.toggle_plugin_button.text() == "Disable plugin" + assert "net.test:zulu-tools" in dialog.app.settings_manager.get("plugins", PluginSettings).enabled + dialog.toggle_plugin_button.click() + assert not plugin.enabled + cleanup.assert_called_once() + assert dialog.toggle_plugin_button.text() == "Enable plugin" + assert "net.test:zulu-tools" not in dialog.app.settings_manager.get("plugins", PluginSettings).enabled + + +def test_failed_enable_keeps_dialog_disabled_state(plugin_dialog): + dialog = plugin_dialog + plugin = dialog.plugin_manager.plugins[0] + errors = [] + dialog.app.widget_manager.signal.show_and_print_error_message.connect(errors.append) + plugin.entry = Mock(side_effect=RuntimeError("entry failed")) + dialog.plugin_list.setCurrentRow(1) + + dialog.toggle_plugin_button.click() + + assert not plugin.enabled + assert dialog.status_label.text() == "Disabled" + assert dialog.toggle_plugin_button.text() == "Enable plugin" + assert dialog.toggle_plugin_button.isEnabled() + assert len(errors) == 1 + + +def test_toggling_updates_disabled_filter(plugin_dialog): + dialog = plugin_dialog + plugin = dialog.plugin_manager.plugins[0] + plugin.entry = Mock() + dialog.filter_combo.setCurrentIndex(2) + assert dialog.plugin_list.count() == 1 + + dialog.toggle_plugin_button.click() + + assert plugin.enabled + assert dialog.plugin_list.count() == 0 + assert dialog.details_stack.currentIndex() == 0 + assert not dialog.toggle_plugin_button.isEnabled() + + +def test_builtin_entry_is_called_from_dialog(plugin_dialog, caplog): + dialog = plugin_dialog + dialog.app.internal_plugins_dir = Path(__file__).resolve().parents[1] / "resources/builtin_plugins" + dialog.app.plugins_dir /= "missing-user-plugins" + caplog.set_level(logging.INFO) + errors = [] + dialog.app.widget_manager.signal.show_and_print_error_message.connect(errors.append) + dialog.reload_button.click() + plugin = dialog.plugin_list.currentItem().data(Qt.ItemDataRole.UserRole) + + dialog.toggle_plugin_button.click() + + assert plugin.enabled + assert "Experimental Farm initialized" in caplog.text + assert (dialog.app.data_dir / "plugins/net.wei/experimentalfarm").is_dir() + assert errors == [] + dialog.toggle_plugin_button.click() + assert not plugin.enabled diff --git a/window.py b/window.py index e9f9444..d06ba8f 100644 --- a/window.py +++ b/window.py @@ -458,7 +458,8 @@ class LauncherMainWindow(QMainWindow): ) widget_signal.show_and_print_error_message.connect( - self.show_and_print_error + self.show_and_print_error, + Qt.ConnectionType.QueuedConnection, ) widget_signal.enable_widget.connect( @@ -524,3 +525,7 @@ class LauncherMainWindow(QMainWindow): about_action.setMenuRole(QAction.MenuRole.AboutRole) about_action.triggered.connect(show_about) help_menu.addAction(about_action) + + def register_plugin_apis(self, plugin_manager): + plugin_manager.register_api("launcher.window.add_toolbar_button", self.toolbar.add_button) + self.manage_profile_page.register_plugin_apis(plugin_manager)