From 9c3b7ea293bd5c43026d62bd66b09441fcfa71cd Mon Sep 17 00:00:00 2001 From: wei Date: Thu, 12 Nov 2026 11:49:21 +0800 Subject: [PATCH] Update to 0.1.6-alpha - Introduced offline account creation with plugin support. - Enhanced manage profile page layout design. --- manager/plugins.py | 234 +++++++++++++++++- pages/account.py | 23 +- pages/manage_profile.py | 26 +- pyproject.toml | 3 +- .../offline_support/__init__.py | 81 ++++++ .../offline_support/plugin.toml | 7 + window.py | 6 +- 7 files changed, 348 insertions(+), 32 deletions(-) create mode 100644 resources/builtin_plugins/offline_support/__init__.py create mode 100644 resources/builtin_plugins/offline_support/plugin.toml diff --git a/manager/plugins.py b/manager/plugins.py index e14479a..9258352 100644 --- a/manager/plugins.py +++ b/manager/plugins.py @@ -12,8 +12,9 @@ from hashlib import sha256 from importlib.machinery import ModuleSpec from importlib.util import spec_from_file_location from logging import Logger +from optparse import Option from pathlib import Path -from typing import Callable, Any +from typing import Callable, Any, Protocol from PySide6.QtCore import QObject, Signal @@ -39,6 +40,7 @@ OPERATORS = { "===": "same", } + def describe_specifier(spec: SpecifierSet) -> str: if not spec: return "No version limit" @@ -48,8 +50,58 @@ def describe_specifier(spec: SpecifierSet) -> str: for item in sorted(spec, key=str) ) + +class WheelAccessDenied(AttributeError): + def __init__(self, root: str, name: str): + super().__init__(f"Access denied while accessing instance {name} in {root}") + + +def get_attribute(obj, name): + attributes = vars(obj) + + if name in attributes: + return attributes[name] + + if name.startswith("__") and not name.endswith("__"): + for cls in type(obj).__mro__: + mangled = f"_{cls.__name__.lstrip('_')}{name}" + + if mangled in attributes: + return attributes[mangled] + + raise AttributeError(name) + + +def find_instance_by_path(root, name: str) -> Any: + """ + Find instance by path + Example: find_instance_by_path(A(), "b.c.d.__hidden") + :param root: + :param name: + :return: + """ + parts = name.split(".") + + if any(not part or part != part.strip() for part in parts): + raise ValueError("Invalid path.") + + current = root + current_path = "" + + for part in parts: + current_path = ( + f"{current_path}.{part}" + if current_path else part + ) + + current = get_attribute(current, part) + + return current + + class Plugin: - def __init__(self, plugin_id: str, name: str, group: str, version: str, api_version_range: SpecifierSet, entrypoint: str, path: Path, + 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 @@ -83,6 +135,19 @@ class Plugin: """ return self.entrypoint.rsplit(":", 1)[-1] + +@dataclass(frozen=True) +class PluginPatch: + replace: Callable[..., Any] + set: Callable[..., Any] + wrap: Callable[..., Any] + + +class GetInstance(Protocol): + def __call__(self, address: str, allow_private: bool = True) -> Any: + ... + + @dataclass(frozen=True) class PluginContext: api_version: str @@ -93,15 +158,20 @@ class PluginContext: # callback get_api: Callable[[str], Callable] + get_instance: GetInstance show_info: Callable[[str], None] show_error: Callable[[str], None] on_cleanup: Callable[[Callable[[], None]], None] override_api: Callable[[str, Callable], Callable[[], None]] + patch: PluginPatch + + 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 @@ -133,6 +203,7 @@ class PluginHook: 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): QObject.__init__(self) @@ -153,7 +224,7 @@ class PluginManager(QObject): class Signals(QObject): load_plugins = Signal() reload_plugins = Signal() - plugins_loaded = Signal() # For gui + plugins_loaded = Signal() # For gui plugin_state_changed = Signal(object) def _show_error(self, message: str, error: BaseException | None = None): @@ -342,11 +413,15 @@ class PluginManager(QObject): 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, @@ -357,7 +432,18 @@ 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, + get_instance=self.get_instance, override_api=lambda name, callback: self._override_plugin_api(plugin, name, callback), + patch=PluginPatch( + set=lambda address, name, value: self._patch_set( + plugin, address, name, value + ), + replace=lambda address, name, replacement: self._patch_replace( + plugin, address, name, replacement + ), + wrap=lambda address, name, wrapper: self._patch_wrap( + plugin, address, name, wrapper + )) ) def _override_plugin_api(self, plugin: Plugin, name: str, callback: Callable) -> Callable[[], None]: @@ -425,7 +511,8 @@ class PluginManager(QObject): 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) + 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: @@ -606,3 +693,142 @@ class PluginManager(QObject): return self._apis[name] except KeyError: raise LookupError(f'Plugin API "{name}" is not available.') from None + + def get_instance(self, address: str, allow_private: bool = True): + """ + Get the instance object by its instance address. + :param address: + :param allow_private: + :return: + """ + for name in address.split("."): + if name != name.strip() or (name.startswith("__") and not allow_private): + raise ValueError("Invalid or protected attribute name.") + + target = find_instance_by_path(self.app, address) + + try: + hidden = get_attribute(target, "__wheel_hidden") + except AttributeError: + hidden = [] + + address_name, _, instance_name = address.rpartition(".") + if instance_name in hidden or address in hidden: + raise WheelAccessDenied(address_name or "app", instance_name) + + return target + + def _locate_patch_target(self, instance_address: str, name: str, allow_private: bool = True): + """ + Locate the target object by its instance address and attribute name. + :param instance_address: + :param name: + :param allow_private: + :return: + """ + # Check instance address and private state + if not isinstance(name, str) or not name or "." in name: + raise ValueError("Attribute name must be a non-empty simple name.") + + if name != name.strip() or (name.startswith("__") and not allow_private): + raise ValueError("Invalid or protected attribute name.") + + target = find_instance_by_path(self.app, instance_address) + + try: + hidden = get_attribute(target, "__wheel_hidden") + except AttributeError: + hidden = [] + + full_path = f"{instance_address}.{name}" + if name in hidden or full_path in hidden: + raise WheelAccessDenied(instance_address, name) + + return target + + def _apply_patch(self, plugin: Plugin, target, name: str, value): + attributes = vars(target) + had_local_value = name in attributes + original_value = attributes.get(name) + + setattr(target, name, value) + restored = False + + def restore(): + nonlocal restored + + if restored: + return + + if had_local_value: + setattr(target, name, original_value) + else: + delattr(target, name) + + restored = True + + self._register_plugin_cleanup(plugin, restore) # ensure all processes can be restored after plugin disabled + return restore + + def _patch_set(self, plugin: Plugin, address: str, name: str, value): + """ + Set the target instance attribute to the provided value. + :param plugin: + :param address: + :param name: + :param value: + :return: + """ + target = self._locate_patch_target(address, name) + return self._apply_patch(plugin, target, name, value) + + def _patch_replace(self, plugin: Plugin, address: str, name: str, replacement): + """ + Replace the target method with the provided replacement. + :param plugin: + :param address: + :param name: + :param replacement: + :return: + """ + if not callable(replacement): + raise TypeError("Replacement must be callable.") + + target = self._locate_patch_target(address, name) + + if not callable(getattr(target, name)): + raise TypeError("Target attribute must be callable.") + + return self._apply_patch(plugin, target, name, replacement) + + def _patch_wrap(self, plugin: Plugin, address: str, name: str, wrapper): + """ + Wrap a method with the provided wrapper. + :param plugin: + :param address: + :param name: + :param wrapper: + :return: + Examples: + A method is at root.example_manager.spam + it looks like this: def span(self, *args, **kwargs): return ["spam"] + + Define the wrapper function. + def (original, *args, **kwargs): return original(*args, **kwargs).append("eggs") + + Wrapping it with context.patch.wrap("example_manager", "spam", wrapper) # associated instance address + # method name, wrapper function + """ + if not callable(wrapper): + raise TypeError("Wrapper must be callable.") + + target = self._locate_patch_target(address, name) + original = getattr(target, name) + + if not callable(original): + raise TypeError("Target attribute is not callable.") + + def wrapped(*args, **kwargs): + return wrapper(original, *args, **kwargs) + + return self._apply_patch(plugin, target, name, wrapped) diff --git a/pages/account.py b/pages/account.py index 1f92d20..637f09a 100644 --- a/pages/account.py +++ b/pages/account.py @@ -185,8 +185,8 @@ class AccountPage(QWidget): self.login_dialog = None # Layout - main_layout = QVBoxLayout() - right_layout = QVBoxLayout() + self.main_layout = QVBoxLayout() + self.right_layout = QVBoxLayout() layout = QHBoxLayout(self) # Widgets @@ -208,16 +208,16 @@ class AccountPage(QWidget): self.avatar_size = QSize(32, 32) # Bind widget - main_layout.addWidget(self.account_list) - right_layout.addWidget(self.add_account_button) - 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() + self.main_layout.addWidget(self.account_list) + self.right_layout.addWidget(self.add_account_button) + self.right_layout.addWidget(self.refresh_button) + self.right_layout.addWidget(self.reload_button) + self.right_layout.addWidget(self.delete_all_button) + self.right_layout.addWidget(self.refresh_avatar_cache_button) + self.right_layout.addStretch() - layout.addLayout(main_layout, 1) - layout.addLayout(right_layout) + layout.addLayout(self.main_layout, 1) + layout.addLayout(self.right_layout) self.related_button : QToolButton = None @@ -375,6 +375,7 @@ class AccountPage(QWidget): def _switch_account(self, account_id: str): self.account_manager.set_current_account(account_id) self.account_manager.save() + self._account_head_updated(account_id) def _current_account_changed(self, _account_id): self._render_accounts() diff --git a/pages/manage_profile.py b/pages/manage_profile.py index 73f87ec..12723cc 100644 --- a/pages/manage_profile.py +++ b/pages/manage_profile.py @@ -5,7 +5,7 @@ from typing import Callable from PySide6.QtCore import Qt, QUrl, Signal from PySide6.QtGui import QDesktopServices, QImageReader from PySide6.QtWidgets import ( - QFileDialog, QFormLayout, QFrame, QHBoxLayout, QLabel, QLineEdit, + QFileDialog, QFormLayout, QFrame, QGridLayout, QHBoxLayout, QLabel, QLineEdit, QMessageBox, QPushButton, QScrollArea, QSizePolicy, QSpinBox, QVBoxLayout, QWidget, QMenu, QComboBox, QTabWidget, ) @@ -130,14 +130,14 @@ class ManageProfilePage(QWidget): self.list_layout.setSpacing(4) self.list_layout.setAlignment(Qt.AlignmentFlag.AlignTop) self.list_scroll.setWidget(self.list_content) - self.list_scroll.setMinimumWidth(260) - self.list_scroll.setMaximumWidth(380) - columns.addWidget(self.list_scroll, 2) + self.list_scroll.setMinimumWidth(220) + self.list_scroll.setMaximumWidth(320) + columns.addWidget(self.list_scroll, 1) self.options_scroll = self._scroll_area("manageProfileOptionsScroll") self.options_content = QWidget() self.options_layout = QVBoxLayout(self.options_content) - self.options_layout.setContentsMargins(20, 16, 20, 20) + self.options_layout.setContentsMargins(10, 16, 10, 10) self.options_layout.setSpacing(14) self.options_scroll.setWidget(self.options_content) @@ -147,7 +147,7 @@ class ManageProfilePage(QWidget): 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) + columns.addWidget(self.profile_tabs, 2) self.editor = QFrame() self.editor.setObjectName("profileEditor") @@ -155,6 +155,7 @@ class ManageProfilePage(QWidget): editor_layout.setSpacing(14) form = QFormLayout() form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow) + form.setRowWrapPolicy(QFormLayout.RowWrapPolicy.WrapAllRows) form.setVerticalSpacing(12) # Icon & Name @@ -209,17 +210,20 @@ class ManageProfilePage(QWidget): editor_layout.addLayout(profile_head_h_layout) editor_layout.addLayout(form) - file_actions = QHBoxLayout() + file_actions = QGridLayout() + file_actions.setHorizontalSpacing(10) + file_actions.setVerticalSpacing(8) add_version_button = QPushButton(self.app.tr_text("Add Modded Version")) add_version_button.clicked.connect(self.open_add_modded_version_dialog) open_button = QPushButton(self.app.tr_text("Open Profile Folder")) open_button.clicked.connect(self.open_profile_folder) import_button = QPushButton(self.app.tr_text("Import Mods…")) import_button.clicked.connect(self.import_mods) - file_actions.addWidget(add_version_button) - file_actions.addWidget(open_button) - file_actions.addWidget(import_button) - file_actions.addStretch() + file_actions.addWidget(add_version_button, 0, 0) + file_actions.addWidget(open_button, 0, 1) + file_actions.addWidget(import_button, 1, 0, 1, 2) + file_actions.setColumnStretch(0, 1) + file_actions.setColumnStretch(1, 1) editor_layout.addLayout(file_actions) self.plugin_actions = QHBoxLayout() diff --git a/pyproject.toml b/pyproject.toml index 01dc2ff..c083ac6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "testlauncher" -version = "0.1.5a0" +version = "0.1.6a0" description = "A lightweight Minecraft launcher." readme = "README.md" requires-python = ">=3.10" @@ -17,6 +17,7 @@ dependencies = [ "requests>=2.32,<3", "tomli>=2.2,<3; python_version < '3.11'", "tomli-w>=1.2,<2", + "uuid>=1.30", ] [dependency-groups] diff --git a/resources/builtin_plugins/offline_support/__init__.py b/resources/builtin_plugins/offline_support/__init__.py new file mode 100644 index 0000000..58769c5 --- /dev/null +++ b/resources/builtin_plugins/offline_support/__init__.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import uuid +from collections.abc import Callable, Iterable + +from PySide6.QtWidgets import QInputDialog, QPushButton + +from TapLauncher import PluginContext +from manager.account import AccountSummary, CreateAccountRequest + +MSA_ACCOUNT_TYPE = "msa" +OFFLINE_ACCOUNT_TYPE = "offline" + + +def has_msa_account(accounts: Iterable[AccountSummary]) -> bool: + return any(account.account_type.casefold() == MSA_ACCOUNT_TYPE for account in accounts) + + +def build_offline_account_request(username: str) -> CreateAccountRequest: + account_id = uuid.uuid4().hex + return CreateAccountRequest( + account_id=account_id, + username=username, + account_type=OFFLINE_ACCOUNT_TYPE, + access_token=account_id, + refresh_token=account_id, + access_token_expires_at=OFFLINE_ACCOUNT_TYPE, + refresh_token_expires_at=OFFLINE_ACCOUNT_TYPE, + avatar="", + minecraft_uuid=account_id, + minecraft_name=username, + user_properties=[], + xuid=None, + ) + + +def create_add_offline_handler(account_manager, context: PluginContext) -> Callable[[], None]: + def add_offline() -> None: + if not has_msa_account(account_manager.list_accounts()): + context.show_error("Add a Microsoft account before creating an offline account.") + return + + username, accepted = QInputDialog.getText( + None, + "Add Offline Account", + "Account Name", + ) + username = username.strip() + if not accepted: + return + if not username: + context.show_error("Offline account name cannot be empty.") + return + + account_id = account_manager.create_account(build_offline_account_request(username)) + if account_id: + context.show_info(f"Offline account {username} created") + + return add_offline + + +def setup(context: PluginContext) -> None: + account_manager = context.get_instance("account_manager") + account_page = context.get_instance("main_window.account_page") + + if not callable(getattr(account_manager, "list_accounts", None)) or not callable( + getattr(account_manager, "create_account", None) + ): + context.logger.error("AccountManager not found") + return + + add_offline = create_add_offline_handler(account_manager, context) + context.patch.set("main_window.account_page", "add_offline", add_offline) + + add_offline_button = QPushButton("Add Offline Account", account_page) + account_page.right_layout.insertWidget( + max(0, account_page.right_layout.count() - 1), + add_offline_button, + ) + add_offline_button.clicked.connect(add_offline) + context.on_cleanup(add_offline_button.deleteLater) diff --git a/resources/builtin_plugins/offline_support/plugin.toml b/resources/builtin_plugins/offline_support/plugin.toml new file mode 100644 index 0000000..96572fb --- /dev/null +++ b/resources/builtin_plugins/offline_support/plugin.toml @@ -0,0 +1,7 @@ +group = "net.wei" +id = "offline-support" +name = "Offline Support" +version = "1.1.0" +api_version = ">=0.0.1" +entrypoint = "__init__.py:setup" +description = "Adds offline accounts after at least one Microsoft account is signed in." diff --git a/window.py b/window.py index 46a2359..0d52c46 100644 --- a/window.py +++ b/window.py @@ -96,7 +96,7 @@ class ToolBar(QtWidgets.QToolBar): ) button.setMinimumWidth(60) - def add_button(self, button_id: str, text=None,icon: QIcon=None) -> QToolButton: + def add_button(self, button_id: str, text=None,icon: QIcon=None) -> PageButton: if not isinstance(button_id, str) or not button_id.strip(): raise ValueError("Button id must be a non-empty string") if button_id in self.buttons: @@ -319,13 +319,9 @@ class LauncherMainWindow(QMainWindow): self.bind_page_button(self.open_test_page, self.test_page) self.bind_page_button(self.open_launch_profile_page, self.launch_profile_page) - self.bind_page_button(self.open_settings_page, self.settings_page) - self.bind_page_button(self.open_account_page, self.account_page) - self.bind_page_button(self.open_create_profile_page, self.create_profile_page) - self.bind_page_button(self.open_manage_profile_page, self.manage_profile_page) # Apply page bar settings