diff --git a/constant.py b/constant.py index 40cc289..036fb73 100644 --- a/constant.py +++ b/constant.py @@ -1,4 +1,4 @@ -LAUNCHER_VERSION = "0.1.0-alpha" +LAUNCHER_VERSION = "0.1.1-alpha" LAUNCHER_NAME = "TapLauncher" LAUNCHER_DIR_NAME = "TapLauncher" MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/" diff --git a/manager/plugins.py b/manager/plugins.py index 55c8a99..e14479a 100644 --- a/manager/plugins.py +++ b/manager/plugins.py @@ -13,7 +13,7 @@ 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 typing import Callable, Any from PySide6.QtCore import QObject, Signal @@ -96,6 +96,42 @@ class PluginContext: show_info: Callable[[str], None] show_error: Callable[[str], None] on_cleanup: Callable[[Callable[[], None]], None] + override_api: Callable[[str, Callable], Callable[[], None]] + +class PluginHook: + """ + A callable instance that used by plugin to calling the target API. + """ + def __init__(self, name: str, target: Callable[..., Any]): + self.name = name + self._target = target + self._original_target = target + self._overrides: list[tuple[object, Callable]] = [] + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self._target(*args, **kwargs) + + def set_target(self, target: Callable[..., Any]) -> Callable[[], None]: + """Set/Override the target API.""" + if not callable(target): + raise TypeError(f'Plugin API "{self.name}" must be callable.') + + token = object() + self._overrides.append((token, target)) + self._target = target + + return lambda: self.restore(token) + + def restore(self, token: object | None = None) -> None: + """Remove an override and restore the latest remaining target.""" + if token is None: + if not self._overrides: + return + + token = self._overrides[-1][0] + + self._overrides = [entry for entry in self._overrides if entry[0] is not token] + self._target = self._overrides[-1][1] if self._overrides else self._original_target class PluginManager(QObject): def __init__(self, app): @@ -105,6 +141,7 @@ class PluginManager(QObject): self.plugins: list[Plugin] = [] self._apis: dict[str, Callable] = {} self._updating_plugin_state = False + self._hooks: dict[str, PluginHook] = {} self.register_api("launcher.apis.list", self.list_apis) self.signals = PluginManager.Signals() @@ -320,8 +357,14 @@ class PluginManager(QObject): 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, + override_api=lambda name, callback: self._override_plugin_api(plugin, name, callback), ) + def _override_plugin_api(self, plugin: Plugin, name: str, callback: Callable) -> Callable[[], None]: + restore = self.override_api(name, callback) + self._register_plugin_cleanup(plugin, restore) + return restore + @staticmethod def _register_plugin_cleanup(plugin: Plugin, callback: Callable[[], None]): if not callable(callback): @@ -512,7 +555,7 @@ class PluginManager(QObject): # # API # - def register_api(self, name: str, callback: Callable): + def register_api(self, name: str, callback: Callable, overridable: bool = True): if not isinstance(name, str): raise TypeError("Plugin API name must be a string.") if not name or name != name.strip(): @@ -524,11 +567,42 @@ class PluginManager(QObject): self._apis[name] = callback + if overridable: + self._create_hook(name, callback) + + def _create_hook(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.') + + self._hooks[name] = PluginHook(name, callback) + + def override_api(self, name: str, callback: Callable): + if not isinstance(name, str): + raise TypeError("Plugin API name must be a string.") + + if name not in self._apis: + raise ValueError(f'Plugin API "{name}" is not registered.') + + if name not in self._hooks: + raise ValueError(f'Plugin API "{name}" does not allow overrides.') + + hook = self._hooks[name] + return hook.set_target(callback) + def list_apis(self) -> tuple[str, ...]: return tuple(sorted(self._apis)) def get_api(self, name: str) -> Callable: try: + if name in self._hooks: + return self._hooks[name] + return self._apis[name] except KeyError: raise LookupError(f'Plugin API "{name}" is not available.') from None diff --git a/manager/settings_models.py b/manager/settings_models.py index 37a8a45..6ebef66 100644 --- a/manager/settings_models.py +++ b/manager/settings_models.py @@ -77,4 +77,5 @@ class AccountSettings(WarnExtraModel): return value class PluginSettings(WarnExtraModel): - enabled: list[str] = Field(default_factory=list) \ No newline at end of file + enabled: list[str] = Field(default_factory=list) + is_plugin_warning_shown: bool = False \ No newline at end of file diff --git a/pages/plugins.py b/pages/plugins.py index c32070c..90f16e6 100644 --- a/pages/plugins.py +++ b/pages/plugins.py @@ -1,6 +1,6 @@ from pathlib import Path -from PySide6.QtCore import Qt, QSize, QUrl +from PySide6.QtCore import Qt, QSize, QUrl, QTimer from PySide6.QtGui import QDesktopServices, QIcon, QPixmap, QMovie from PySide6.QtWidgets import ( QWidget, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, @@ -9,6 +9,7 @@ from PySide6.QtWidgets import ( ) from manager.plugins import Plugin +from manager.settings_models import PluginSettings class PluginsDialog(QDialog): @@ -379,6 +380,23 @@ class PluginsDialog(QDialog): super().showEvent(event) for movie in self.icon_movies: movie.start() + QTimer.singleShot(0, self._show_plugin_warning) + + def _show_plugin_warning(self): + settings_manager = self.app.settings_manager + settings = settings_manager.get("plugins", PluginSettings) + if settings.is_plugin_warning_shown: + return + + settings_manager.set("plugins", settings.model_copy(update={"is_plugin_warning_shown": True})) + self.app.widget_manager.signal.show_warning_message.emit(self.app.tr_text( + "Plugins can run code on your computer and access your files and account data. " + "Only enable plugins from sources you trust." + )) + try: + settings_manager.save() + except OSError as error: + self.app.logger.warning("Failed to save plugin warning preference: %s", error) def hideEvent(self, event): for movie in self.icon_movies: diff --git a/pages/settings.py b/pages/settings.py index a1f192b..7748558 100644 --- a/pages/settings.py +++ b/pages/settings.py @@ -211,10 +211,9 @@ class SettingsPage(QWidget): def _open_plugins_dialog(self): dialog = PluginsDialog(self.app, self.app.plugin_manager, self) - try: - dialog.exec() - finally: - dialog.deleteLater() + dialog.setWindowFlags(Qt.Window) + dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True) + dialog.show() def _create_general_page(self) -> QWidget: tr = self.app.tr_text diff --git a/pyproject.toml b/pyproject.toml index 3105535..168625e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "testlauncher" -version = "0.1.0a0" +version = "0.1.1a0" description = "A lightweight Minecraft launcher." readme = "README.md" requires-python = ">=3.10" @@ -10,6 +10,7 @@ authors = [ dependencies = [ "colorlog>=6.9,<7", "keyring>=25.6,<26", + "packaging>=26.2", "pydantic>=2.11,<3", "PySide6>=6.8,<7", "requests>=2.32,<3", diff --git a/resources/themes/it-looks-like-official-launcher/palette.toml b/resources/themes/it-looks-like-official-launcher/palette.toml new file mode 100644 index 0000000..6cc2efd --- /dev/null +++ b/resources/themes/it-looks-like-official-launcher/palette.toml @@ -0,0 +1,14 @@ +[palette] +window = "#262626" +window_text = "#ffffff" +base = "#181818" +alternate_base = "#303030" +text = "#ffffff" +button = "#3c3c3c" +button_text = "#ffffff" +mid = "#505050" +midlight = "#454545" +dark = "#111111" +highlight = "#3c8527" +highlighted_text = "#ffffff" +placeholder_text = "#b1b1b1" diff --git a/resources/themes/it-looks-like-official-launcher/styles/main.qss b/resources/themes/it-looks-like-official-launcher/styles/main.qss new file mode 100644 index 0000000..10632bf --- /dev/null +++ b/resources/themes/it-looks-like-official-launcher/styles/main.qss @@ -0,0 +1,64 @@ +QMainWindow, QDialog { + background: palette(window); + color: palette(window-text); +} +QPushButton, QToolButton { + background: palette(button); + color: palette(button-text); + border: 1px solid #595959; + border-bottom: 3px solid #171717; + border-radius: 0; + padding: 6px 12px; + min-height: 22px; +} +QPushButton:hover, QToolButton:hover { background: #4c4c4c; border-top-color: #858585; } +QPushButton:pressed, QToolButton:pressed, +QPushButton:checked, QToolButton:checked { background: #252525; border-bottom-color: #595959; } +QPushButton:focus, QToolButton:focus { border-color: #a0e081; } +QPushButton:disabled, QToolButton:disabled { background: #303030; color: #858585; border-color: #414141; } +QLineEdit, QPlainTextEdit, QTextEdit, QSpinBox, QDoubleSpinBox, +QComboBox, QListView, QTreeView, QTableView { + background: palette(base); + color: palette(text); + border: 1px solid palette(mid); + border-radius: 0; + padding: 6px; + selection-background-color: palette(highlight); + selection-color: palette(highlighted-text); +} +QLineEdit:focus, QPlainTextEdit:focus, QTextEdit:focus, +QSpinBox:focus, QDoubleSpinBox:focus, QComboBox:focus { border-color: #86d562; } +QComboBox { padding-right: 28px; min-height: 22px; } +QComboBox QAbstractItemView { + background: palette(base); + color: palette(text); + selection-background-color: palette(highlight); + selection-color: palette(highlighted-text); +} +QGroupBox { border: 1px solid palette(mid); margin-top: 12px; padding-top: 10px; } +QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 4px; } +QProgressBar { + background: palette(base); + color: palette(text); + border: 1px solid palette(mid); + border-radius: 0; + min-height: 18px; + text-align: center; +} +QProgressBar::chunk { background: #3c8527; } +QProgressBar[failed="true"]::chunk { background: #c62828; } +QTabWidget::pane { border: 1px solid palette(mid); } +QTabBar::tab { background: #202020; color: #b1b1b1; padding: 10px 16px; border-bottom: 3px solid transparent; } +QTabBar::tab:selected { color: #ffffff; border-bottom-color: #6cc349; } +QTabBar::tab:hover { background: #383838; color: #ffffff; } +QMenu { background: #202020; color: #ffffff; border: 1px solid #505050; padding: 4px; } +QMenu::item { padding: 7px 24px; } +QMenu::item:selected { background: #3c8527; } +QMenu::item:disabled { color: #858585; } +QToolTip { background: #181818; color: #ffffff; border: 1px solid #606060; padding: 5px; } +QLabel#dev_info_box { font-size: 20pt; font-weight: bold; } +QLabel#dev_info_message { font-size: 10pt; } +QLabel#version_label { font-weight: bold; } +QMessageBox { background: #262626; } +QMessageBox QLabel { color: #ffffff; background: transparent; } +QMessageBox QPushButton { min-width: 72px; } diff --git a/resources/themes/it-looks-like-official-launcher/styles/manage_profile.qss b/resources/themes/it-looks-like-official-launcher/styles/manage_profile.qss new file mode 100644 index 0000000..04f6f0e --- /dev/null +++ b/resources/themes/it-looks-like-official-launcher/styles/manage_profile.qss @@ -0,0 +1,24 @@ +QLabel#manageTitle { font-size: 24px; font-weight: bold; padding: 4px 2px 8px 2px; } +QScrollArea#manageProfileListScroll, QScrollArea#manageProfileOptionsScroll { + background: #181818; + border: 1px solid #505050; + border-radius: 0; +} +QPushButton#manageProfileItem { + min-height: 62px; + padding: 0; + background: transparent; + border: 1px solid transparent; + border-left: 4px solid transparent; + border-radius: 0; + text-align: left; +} +QLabel#itemName { color: #ffffff; font-size: 15px; font-weight: bold; } +QLabel#itemVersion { color: #b1b1b1; font-size: 12px; } +QPushButton#manageProfileItem:hover { background: #303030; } +QPushButton#manageProfileItem:checked { background: #3c8527; border-left-color: #86d562; color: #ffffff; } +QPushButton#manageProfileItem:focus { border-color: #a0e081; } +QPushButton#manageProfileItem QLabel[itemChecked="true"] { color: #ffffff; background: transparent; } +QFrame#profileEditor { background: transparent; } +QPushButton#saveProfileButton { min-width: 130px; font-weight: bold; } +QPushButton#dangerButton { color: #ff9090; } diff --git a/resources/themes/it-looks-like-official-launcher/styles/profile.qss b/resources/themes/it-looks-like-official-launcher/styles/profile.qss new file mode 100644 index 0000000..eed80d6 --- /dev/null +++ b/resources/themes/it-looks-like-official-launcher/styles/profile.qss @@ -0,0 +1,38 @@ +QFrame#profileButton { background: #303030; border: 1px solid #505050; border-radius: 0; } +QFrame#profileButton:hover { background: #3c3c3c; border-color: #86d562; } +QLabel#profileName, QLabel#itemName { color: #ffffff; font-size: 16px; font-weight: bold; } +QLabel#profileVersion, QLabel#itemVersion { color: #b1b1b1; font-size: 12px; } +QLabel#profileArrow { color: #ffffff; background: transparent; font-size: 18px; } +QLabel#launchStatus { color: #ffffff; font-size: 12px; font-weight: bold; } +QFrame#profilePopup { background: #202020; border: 1px solid #505050; border-radius: 0; } +QWidget#profileListContent { background: #202020; } +QPushButton#profileItem { + min-height: 60px; + padding: 0; + background: #202020; + border: 1px solid transparent; + border-radius: 0; + text-align: left; +} +QPushButton#profileItem:hover { background: #3c8527; } +QPushButton#profileItem:focus { border-color: #a0e081; } +QPushButton#profileItem QLabel[itemHovered="true"] { color: #ffffff; background: transparent; } +QPushButton#launchButton { + min-width: 150px; + min-height: 32px; + font-size: 18px; + font-weight: bold; + color: #ffffff; + background: #3c8527; + border: 2px solid #1d4d13; + border-top: 2px solid #86d562; + border-bottom: 5px solid #1d4d13; + border-radius: 0; +} +QPushButton#launchButton:hover { background: #4f9f30; } +QPushButton#launchButton:pressed { background: #2f6b1f; border-top-color: #1d4d13; border-bottom-color: #3c8527; } +QPushButton#launchButton:focus { border-left-color: #b5f293; border-right-color: #b5f293; } +QPushButton#launchButton:disabled { background: #3c3c3c; color: #858585; border-color: #505050; } +QFrame#profileFrame { background: #202020; border: 1px solid #505050; border-radius: 0; } +QFrame#header { background: #202020; border-bottom: 1px solid #505050; } +QLabel#headerLabel { color: #ffffff; background: transparent; font-size: 22px; font-weight: bold; } diff --git a/resources/themes/it-looks-like-official-launcher/styles/settings.qss b/resources/themes/it-looks-like-official-launcher/styles/settings.qss new file mode 100644 index 0000000..6f28f46 --- /dev/null +++ b/resources/themes/it-looks-like-official-launcher/styles/settings.qss @@ -0,0 +1,34 @@ +QWidget#settingsPage, QWidget#settingsMainPage, QWidget#settingsScrollContent { + background: #262626; +} +QScrollArea#settingsScrollArea { border: none; background: #262626; } +QScrollArea#settingsScrollArea > QWidget > QWidget { background: #262626; } +QLabel#settingsPageTitle { color: #ffffff; font-size: 20px; font-weight: bold; } +QLabel#settingsSubPageTitle { color: #ffffff; font-size: 18px; font-weight: bold; } +QPushButton#settingsItem { + min-height: 68px; + border: 1px solid #505050; + border-left: 4px solid #505050; + border-radius: 0; + background: #303030; + text-align: left; +} +QPushButton#settingsItem:hover { background: #3c3c3c; border-left-color: #6cc349; } +QPushButton#settingsItem:pressed { background: #202020; } +QPushButton#settingsItem:focus { border-color: #86d562; } +QLabel#settingsItemTitle { color: #ffffff; font-size: 14px; font-weight: bold; } +QLabel#settingsItemDescription, QLabel#settingsHelpText { color: #b1b1b1; font-size: 12px; } +QPushButton#settingsBackButton { min-height: 0; padding: 0; border: none; border-radius: 0; font-size: 22px; } +QPushButton#settingsBackButton:focus { border: 1px solid #86d562; } +QLabel#settingsBrand { color: #ffffff; font-size: 20px; font-weight: bold; } +QLabel#settingsVersion { color: #b1b1b1; font-size: 12px; } +QPlainTextEdit#settingsDescription { font-size: 13px; } +QWidget#settingsPage QComboBox { + min-height: 22px; + padding: 6px 32px 6px 10px; + border: 1px solid #505050; + border-radius: 0; + background: #181818; + color: #ffffff; +} +QWidget#settingsPage QComboBox:hover, QWidget#settingsPage QComboBox:focus { border-color: #86d562; } diff --git a/resources/themes/it-looks-like-official-launcher/styles/toolbar.qss b/resources/themes/it-looks-like-official-launcher/styles/toolbar.qss new file mode 100644 index 0000000..74d78ea --- /dev/null +++ b/resources/themes/it-looks-like-official-launcher/styles/toolbar.qss @@ -0,0 +1,31 @@ +QToolBar { + margin: 0; + spacing: 0; + background: #181818; + border: none; +} +QToolBar::separator { background: #3c3c3c; width: 1px; height: 1px; } +QToolBar QPushButton, QToolBar QToolButton { + margin: 0; + padding: 14px; + min-height: 28px; + border: none; + border-left: 4px solid transparent; + border-radius: 0; + background: #181818; + color: #b1b1b1; + font-size: 13px; + font-weight: bold; +} +QToolBar:left QPushButton, QToolBar:right QPushButton, +QToolBar:left QToolButton, QToolBar:right QToolButton { padding: 14px 6px; min-width: 0; } +QToolBar QPushButton:hover, QToolBar QToolButton:hover { background: #303030; color: #ffffff; } +QToolBar QPushButton:pressed, QToolBar QToolButton:pressed, +QToolBar QPushButton:checked, QToolBar QToolButton:checked { + background: #303030; + color: #ffffff; + border-left-color: #6cc349; +} +QToolBar QPushButton:focus, QToolBar QToolButton:focus { border-left-color: #6cc349; } +QToolBar QPushButton:disabled, QToolBar QToolButton:disabled { color: #757575; } +QToolBar::handle { background: #3c3c3c; } diff --git a/resources/themes/it-looks-like-official-launcher/theme.toml b/resources/themes/it-looks-like-official-launcher/theme.toml new file mode 100644 index 0000000..ed40cb8 --- /dev/null +++ b/resources/themes/it-looks-like-official-launcher/theme.toml @@ -0,0 +1 @@ +name = "ItLooksLikeOfficial" diff --git a/resources/translations/en.json b/resources/translations/en.json index 3b50f94..1d0da08 100644 --- a/resources/translations/en.json +++ b/resources/translations/en.json @@ -112,6 +112,7 @@ "Launched!": "Launched!", "Launcher error occurred.": "Launcher error occurred.", "Launcher theme": "Launcher theme", + "Minecraft Launcher": "Minecraft Launcher", "Light": "Light", "Loading all types...": "Loading all types...", "Loading all versions...": "Loading all versions...", @@ -336,5 +337,6 @@ "minutes": "minutes", "{account} is currently signed in.": "{account} is currently signed in.", "{account}'s session has expired.": "{account}'s session has expired.", + "Plugins can run code on your computer and access your files and account data. Only enable plugins from sources you trust.": "Plugins can run code on your computer and access your files and account data. Only enable plugins from sources you trust.", "$ABOUT_THIS_LAUNCHER": "" } diff --git a/resources/translations/zh-TW.json b/resources/translations/zh-TW.json index 81f6839..04e9982 100644 --- a/resources/translations/zh-TW.json +++ b/resources/translations/zh-TW.json @@ -111,6 +111,7 @@ "Launched!": "已啟動!", "Launcher error occurred.": "啟動器發生錯誤。", "Launcher theme": "啟動器佈景主題", + "Minecraft Launcher": "Minecraft 官方啟動器風格", "Light": "淺色", "Loading all types...": "正在載入所有類型……", "Loading all versions...": "正在載入所有版本……", @@ -320,6 +321,7 @@ "Credential migration failed": "憑證移轉失敗", "Credentials save method": "憑證儲存方式", "Custom": "自訂", + "Plugins can run code on your computer and access your files and account data. Only enable plugins from sources you trust.": "插件可以在你的電腦上執行程式碼,並存取檔案與帳號資料。請只啟用來自可信來源的插件。", "Expired": "已過期", "Invalid Client ID": "無效的 Client ID", "Launcher log": "啟動器紀錄", diff --git a/tests/test_plugins_dialog.py b/tests/test_plugins_dialog.py index 8d28d2d..05688e5 100644 --- a/tests/test_plugins_dialog.py +++ b/tests/test_plugins_dialog.py @@ -49,6 +49,31 @@ def plugin_dialog(tmp_path): qt_app.processEvents() +def test_plugin_warning_is_translated_and_saved_once(plugin_dialog): + dialog = plugin_dialog + dialog.app.i18n.set_language("zh-TW") + messages = [] + dialog.app.widget_manager.signal.show_warning_message.connect(messages.append) + dialog._show_plugin_warning() + dialog._show_plugin_warning() + assert len(messages) == 1 + assert "可信來源" in messages[0] + dialog.app.settings_manager.load() + assert dialog.app.settings_manager.get("plugins", PluginSettings).is_plugin_warning_shown + dialog._show_plugin_warning() + assert len(messages) == 1 + + +def test_plugin_warning_save_failure_does_not_repeat(plugin_dialog, monkeypatch): + dialog = plugin_dialog + monkeypatch.setattr(dialog.app.settings_manager, "save", Mock(side_effect=OSError("read only"))) + messages = [] + dialog.app.widget_manager.signal.show_warning_message.connect(messages.append) + dialog._show_plugin_warning() + dialog._show_plugin_warning() + assert len(messages) == 1 + + def test_search_filter_and_selection(plugin_dialog): dialog = plugin_dialog assert dialog.plugin_list.count() == 2 diff --git a/tests/test_stylesheets.py b/tests/test_stylesheets.py index 9957da3..d21d073 100644 --- a/tests/test_stylesheets.py +++ b/tests/test_stylesheets.py @@ -85,7 +85,7 @@ def test_invalid_theme_falls_back_to_default_styles(style_app): assert style_app.locate_styles_path(Path("main.qss")) == default -@pytest.mark.parametrize("theme, background", [("aqua", "#f1f3f7"), ("windows-9x", "#c0c0c0"), ("bliss", "#ece9d8")]) +@pytest.mark.parametrize("theme, background", [("aqua", "#f1f3f7"), ("windows-9x", "#c0c0c0"), ("bliss", "#ece9d8"), ("it-looks-like-official-launcher", "#262626")]) def test_message_boxes_follow_application_theme(style_app, theme, background): style_app.theme_dir = Path(__file__).resolve().parents[1] / "resources/themes" / theme style_app.apply_theme("custom") @@ -146,7 +146,7 @@ def test_detailed_dialogs_inherit_aqua(style_app, monkeypatch, question): assert checked == [True] -@pytest.mark.parametrize("theme, normal_color", [("aqua", "#626d7e"), ("windows-9x", "#404040"), ("bliss", "#555d69")]) +@pytest.mark.parametrize("theme, normal_color", [("aqua", "#626d7e"), ("windows-9x", "#404040"), ("bliss", "#555d69"), ("it-looks-like-official-launcher", "#b1b1b1")]) @pytest.mark.parametrize("managed", [False, True]) def test_profile_label_colors_follow_button_state(style_app, theme, normal_color, managed): root = Path(__file__).resolve().parents[1] diff --git a/window.py b/window.py index d06ba8f..02c5c1d 100644 --- a/window.py +++ b/window.py @@ -7,8 +7,8 @@ from PySide6.QtCore import QSize from PySide6.QtGui import QIcon, Qt, QPixmap, QAction from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QToolButton, \ QStackedWidget -from PySide6.QtCore import Slot -from PySide6.QtWidgets import QMessageBox, QFileDialog +from PySide6.QtCore import Slot, QThread +from PySide6.QtWidgets import QMessageBox, QFileDialog, QInputDialog from core_lib.qt import messagebox from core_lib.qt.progress_dialog import ProgressDialog @@ -528,4 +528,113 @@ class LauncherMainWindow(QMainWindow): def register_plugin_apis(self, plugin_manager): plugin_manager.register_api("launcher.window.add_toolbar_button", self.toolbar.add_button) + plugin_manager.register_api("launcher.window.add_page", self.plugin_add_page) + plugin_manager.register_api("launcher.window.replace_homepage", self.plugin_replace_homepage) + plugin_manager.register_api("launcher.ui.confirm", self.plugin_confirm) + plugin_manager.register_api("launcher.ui.prompt_text", self.plugin_prompt_text) + plugin_manager.register_api("launcher.ui.select_file", self.plugin_select_file) + plugin_manager.register_api("launcher.ui.select_directory", self.plugin_select_directory) self.manage_profile_page.register_plugin_apis(plugin_manager) + + def plugin_replace_homepage(self, page: QWidget): + self._check_plugin_gui_thread() + if self.central.indexOf(page) >= 0: + raise ValueError("Homepage must be a new widget.") + if not hasattr(self, "_plugin_homepages"): + self._original_homepage = self.home_page + self._plugin_homepages = [] + previous = self.home_page + self.central.addWidget(page) + self._plugin_homepages.append(page) + self.home_page = page + if self.central.currentWidget() is previous: + self.central.setCurrentWidget(page) + removed = False + + def restore(): + nonlocal removed + self._check_plugin_gui_thread() + if removed: + return + removed = True + self._plugin_homepages.remove(page) + self.home_page = (self._plugin_homepages[-1] if self._plugin_homepages + else self._original_homepage) + if self.central.currentWidget() is page: + self.central.setCurrentWidget(self.home_page) + self.central.removeWidget(page) + page.hide() + page.deleteLater() + + return restore + + def plugin_add_page(self, title: str, page: QWidget, icon: QIcon = None): + self._check_plugin_gui_thread() + button = self.toolbar.add_button(title, icon) + button.setToolTip(title) + self.central.addWidget(page) + spacer_action = next( + action for action in self.toolbar.actions() + if self.toolbar.widgetForAction(action) is self.toolbar.spacer + ) + action = self.toolbar.insertWidget(spacer_action, button) + def show_page(): + self.set_current_page(page, button) + page.setFocus() + + button.clicked.connect(show_page) + self.toolbar.update_all() + removed = False + + def remove(): + nonlocal removed + self._check_plugin_gui_thread() + + if removed: + return + + removed = True + if self.central.currentWidget() is page: + self.set_current_page(self.home_page, self.home_button) + + self.central.removeWidget(page) + page.hide() + self.toolbar.removeAction(action) + action.deleteLater() + button.deleteLater() + page.deleteLater() + + return remove + + def _check_plugin_gui_thread(self): + if QThread.currentThread() != self.thread(): + raise RuntimeError("Plugin GUI APIs must be called on the GUI thread.") + + def plugin_confirm(self, title: str, message: str) -> bool: + self._check_plugin_gui_thread() + dialog = QMessageBox(self) + try: + dialog.setWindowTitle(title) + dialog.setTextFormat(Qt.TextFormat.PlainText) + dialog.setText(message) + dialog.setIcon(QMessageBox.Icon.Question) + dialog.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) + dialog.setDefaultButton(QMessageBox.StandardButton.No) + return dialog.exec() == QMessageBox.StandardButton.Yes + finally: + dialog.deleteLater() + + def plugin_prompt_text(self, title: str, label: str, text: str = "") -> str | None: + self._check_plugin_gui_thread() + value, accepted = QInputDialog.getText(self, title, label, text=text) + return value if accepted else None + + def plugin_select_file(self, title: str, directory: str = "", file_filter: str = "") -> Path | None: + self._check_plugin_gui_thread() + filename, _ = QFileDialog.getOpenFileName(self, title, directory, file_filter) + return Path(filename) if filename else None + + def plugin_select_directory(self, title: str, directory: str = "") -> Path | None: + self._check_plugin_gui_thread() + selected = QFileDialog.getExistingDirectory(self, title, directory) + return Path(selected) if selected else None