Add override api support.

More apis are added in this version.
This commit is contained in:
wei committed 2026-10-30 23:24:28 +08:00
1 parent f029ba425b
commit e3e406a5bc
18 files changed
+451 -14

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
LAUNCHER_VERSION = "0.1.0-alpha" LAUNCHER_VERSION = "0.1.1-alpha"
LAUNCHER_NAME = "TapLauncher" LAUNCHER_NAME = "TapLauncher"
LAUNCHER_DIR_NAME = "TapLauncher" LAUNCHER_DIR_NAME = "TapLauncher"
MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/" MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/"
+76 -2
View File
@@ -13,7 +13,7 @@ from importlib.machinery import ModuleSpec
from importlib.util import spec_from_file_location from importlib.util import spec_from_file_location
from logging import Logger from logging import Logger
from pathlib import Path from pathlib import Path
from typing import Callable from typing import Callable, Any
from PySide6.QtCore import QObject, Signal from PySide6.QtCore import QObject, Signal
@@ -96,6 +96,42 @@ class PluginContext:
show_info: Callable[[str], None] show_info: Callable[[str], None]
show_error: Callable[[str], None] show_error: Callable[[str], None]
on_cleanup: Callable[[Callable[[], None]], 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): class PluginManager(QObject):
def __init__(self, app): def __init__(self, app):
@@ -105,6 +141,7 @@ class PluginManager(QObject):
self.plugins: list[Plugin] = [] self.plugins: list[Plugin] = []
self._apis: dict[str, Callable] = {} self._apis: dict[str, Callable] = {}
self._updating_plugin_state = False self._updating_plugin_state = False
self._hooks: dict[str, PluginHook] = {}
self.register_api("launcher.apis.list", self.list_apis) self.register_api("launcher.apis.list", self.list_apis)
self.signals = PluginManager.Signals() self.signals = PluginManager.Signals()
@@ -320,8 +357,14 @@ class PluginManager(QObject):
show_error=lambda message: self._show_error(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), on_cleanup=lambda callback: self._register_plugin_cleanup(plugin, callback),
get_api=self.get_api, 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 @staticmethod
def _register_plugin_cleanup(plugin: Plugin, callback: Callable[[], None]): def _register_plugin_cleanup(plugin: Plugin, callback: Callable[[], None]):
if not callable(callback): if not callable(callback):
@@ -512,7 +555,7 @@ class PluginManager(QObject):
# #
# API # 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): if not isinstance(name, str):
raise TypeError("Plugin API name must be a string.") raise TypeError("Plugin API name must be a string.")
if not name or name != name.strip(): if not name or name != name.strip():
@@ -524,11 +567,42 @@ class PluginManager(QObject):
self._apis[name] = callback 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, ...]: def list_apis(self) -> tuple[str, ...]:
return tuple(sorted(self._apis)) return tuple(sorted(self._apis))
def get_api(self, name: str) -> Callable: def get_api(self, name: str) -> Callable:
try: try:
if name in self._hooks:
return self._hooks[name]
return self._apis[name] return self._apis[name]
except KeyError: except KeyError:
raise LookupError(f'Plugin API "{name}" is not available.') from None raise LookupError(f'Plugin API "{name}" is not available.') from None
+2 -1
View File
@@ -77,4 +77,5 @@ class AccountSettings(WarnExtraModel):
return value return value
class PluginSettings(WarnExtraModel): class PluginSettings(WarnExtraModel):
enabled: list[str] = Field(default_factory=list) enabled: list[str] = Field(default_factory=list)
is_plugin_warning_shown: bool = False
+19 -1
View File
@@ -1,6 +1,6 @@
from pathlib import Path 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.QtGui import QDesktopServices, QIcon, QPixmap, QMovie
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
QWidget, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QWidget, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit,
@@ -9,6 +9,7 @@ from PySide6.QtWidgets import (
) )
from manager.plugins import Plugin from manager.plugins import Plugin
from manager.settings_models import PluginSettings
class PluginsDialog(QDialog): class PluginsDialog(QDialog):
@@ -379,6 +380,23 @@ class PluginsDialog(QDialog):
super().showEvent(event) super().showEvent(event)
for movie in self.icon_movies: for movie in self.icon_movies:
movie.start() 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): def hideEvent(self, event):
for movie in self.icon_movies: for movie in self.icon_movies:
+3 -4
View File
@@ -211,10 +211,9 @@ class SettingsPage(QWidget):
def _open_plugins_dialog(self): def _open_plugins_dialog(self):
dialog = PluginsDialog(self.app, self.app.plugin_manager, self) dialog = PluginsDialog(self.app, self.app.plugin_manager, self)
try: dialog.setWindowFlags(Qt.Window)
dialog.exec() dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
finally: dialog.show()
dialog.deleteLater()
def _create_general_page(self) -> QWidget: def _create_general_page(self) -> QWidget:
tr = self.app.tr_text tr = self.app.tr_text
+2 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "testlauncher" name = "testlauncher"
version = "0.1.0a0" version = "0.1.1a0"
description = "A lightweight Minecraft launcher." description = "A lightweight Minecraft launcher."
readme = "README.md" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
@@ -10,6 +10,7 @@ authors = [
dependencies = [ dependencies = [
"colorlog>=6.9,<7", "colorlog>=6.9,<7",
"keyring>=25.6,<26", "keyring>=25.6,<26",
"packaging>=26.2",
"pydantic>=2.11,<3", "pydantic>=2.11,<3",
"PySide6>=6.8,<7", "PySide6>=6.8,<7",
"requests>=2.32,<3", "requests>=2.32,<3",
@@ -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"
@@ -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; }
@@ -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; }
@@ -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; }
@@ -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; }
@@ -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; }
@@ -0,0 +1 @@
name = "ItLooksLikeOfficial"
+2
View File
@@ -112,6 +112,7 @@
"Launched!": "Launched!", "Launched!": "Launched!",
"Launcher error occurred.": "Launcher error occurred.", "Launcher error occurred.": "Launcher error occurred.",
"Launcher theme": "Launcher theme", "Launcher theme": "Launcher theme",
"Minecraft Launcher": "Minecraft Launcher",
"Light": "Light", "Light": "Light",
"Loading all types...": "Loading all types...", "Loading all types...": "Loading all types...",
"Loading all versions...": "Loading all versions...", "Loading all versions...": "Loading all versions...",
@@ -336,5 +337,6 @@
"minutes": "minutes", "minutes": "minutes",
"{account} is currently signed in.": "{account} is currently signed in.", "{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.",
"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": "<ORIGINAL>" "$ABOUT_THIS_LAUNCHER": "<ORIGINAL>"
} }
+2
View File
@@ -111,6 +111,7 @@
"Launched!": "已啟動!", "Launched!": "已啟動!",
"Launcher error occurred.": "啟動器發生錯誤。", "Launcher error occurred.": "啟動器發生錯誤。",
"Launcher theme": "啟動器佈景主題", "Launcher theme": "啟動器佈景主題",
"Minecraft Launcher": "Minecraft 官方啟動器風格",
"Light": "淺色", "Light": "淺色",
"Loading all types...": "正在載入所有類型……", "Loading all types...": "正在載入所有類型……",
"Loading all versions...": "正在載入所有版本……", "Loading all versions...": "正在載入所有版本……",
@@ -320,6 +321,7 @@
"Credential migration failed": "憑證移轉失敗", "Credential migration failed": "憑證移轉失敗",
"Credentials save method": "憑證儲存方式", "Credentials save method": "憑證儲存方式",
"Custom": "自訂", "Custom": "自訂",
"Plugins can run code on your computer and access your files and account data. Only enable plugins from sources you trust.": "插件可以在你的電腦上執行程式碼,並存取檔案與帳號資料。請只啟用來自可信來源的插件。",
"Expired": "已過期", "Expired": "已過期",
"Invalid Client ID": "無效的 Client ID", "Invalid Client ID": "無效的 Client ID",
"Launcher log": "啟動器紀錄", "Launcher log": "啟動器紀錄",
+25
View File
@@ -49,6 +49,31 @@ def plugin_dialog(tmp_path):
qt_app.processEvents() 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): def test_search_filter_and_selection(plugin_dialog):
dialog = plugin_dialog dialog = plugin_dialog
assert dialog.plugin_list.count() == 2 assert dialog.plugin_list.count() == 2
+2 -2
View File
@@ -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 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): 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.theme_dir = Path(__file__).resolve().parents[1] / "resources/themes" / theme
style_app.apply_theme("custom") style_app.apply_theme("custom")
@@ -146,7 +146,7 @@ def test_detailed_dialogs_inherit_aqua(style_app, monkeypatch, question):
assert checked == [True] 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]) @pytest.mark.parametrize("managed", [False, True])
def test_profile_label_colors_follow_button_state(style_app, theme, normal_color, managed): def test_profile_label_colors_follow_button_state(style_app, theme, normal_color, managed):
root = Path(__file__).resolve().parents[1] root = Path(__file__).resolve().parents[1]
+111 -2
View File
@@ -7,8 +7,8 @@ from PySide6.QtCore import QSize
from PySide6.QtGui import QIcon, Qt, QPixmap, QAction from PySide6.QtGui import QIcon, Qt, QPixmap, QAction
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QToolButton, \ from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QToolButton, \
QStackedWidget QStackedWidget
from PySide6.QtCore import Slot from PySide6.QtCore import Slot, QThread
from PySide6.QtWidgets import QMessageBox, QFileDialog from PySide6.QtWidgets import QMessageBox, QFileDialog, QInputDialog
from core_lib.qt import messagebox from core_lib.qt import messagebox
from core_lib.qt.progress_dialog import ProgressDialog from core_lib.qt.progress_dialog import ProgressDialog
@@ -528,4 +528,113 @@ class LauncherMainWindow(QMainWindow):
def register_plugin_apis(self, plugin_manager): 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_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) 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