Update to 0.1.6-alpha

- Introduced offline account creation with plugin support.
- Enhanced manage profile page layout design.
This commit is contained in:
wei committed 2026-11-12 11:49:21 +08:00
1 parent 9d8a78e83c
commit 9c3b7ea293
7 files changed
+348 -32

No files matched your search

+230 -4
View File
@@ -12,8 +12,9 @@ from hashlib import sha256
from importlib.machinery import ModuleSpec 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 optparse import Option
from pathlib import Path from pathlib import Path
from typing import Callable, Any from typing import Callable, Any, Protocol
from PySide6.QtCore import QObject, Signal from PySide6.QtCore import QObject, Signal
@@ -39,6 +40,7 @@ OPERATORS = {
"===": "same", "===": "same",
} }
def describe_specifier(spec: SpecifierSet) -> str: def describe_specifier(spec: SpecifierSet) -> str:
if not spec: if not spec:
return "No version limit" return "No version limit"
@@ -48,8 +50,58 @@ def describe_specifier(spec: SpecifierSet) -> str:
for item in sorted(spec, key=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: 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 = ""): icon_path: Path | None = None, module_spec: ModuleSpec | None = None, description: str = ""):
self.id: str = plugin_id self.id: str = plugin_id
self.name: str = name self.name: str = name
@@ -83,6 +135,19 @@ class Plugin:
""" """
return self.entrypoint.rsplit(":", 1)[-1] 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) @dataclass(frozen=True)
class PluginContext: class PluginContext:
api_version: str api_version: str
@@ -93,15 +158,20 @@ class PluginContext:
# callback # callback
get_api: Callable[[str], Callable] get_api: Callable[[str], Callable]
get_instance: GetInstance
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]] override_api: Callable[[str, Callable], Callable[[], None]]
patch: PluginPatch
class PluginHook: class PluginHook:
""" """
A callable instance that used by plugin to calling the target API. A callable instance that used by plugin to calling the target API.
""" """
def __init__(self, name: str, target: Callable[..., Any]): def __init__(self, name: str, target: Callable[..., Any]):
self.name = name self.name = name
self._target = target self._target = target
@@ -133,6 +203,7 @@ class PluginHook:
self._overrides = [entry for entry in self._overrides if entry[0] is not token] 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 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):
QObject.__init__(self) QObject.__init__(self)
@@ -153,7 +224,7 @@ class PluginManager(QObject):
class Signals(QObject): class Signals(QObject):
load_plugins = Signal() load_plugins = Signal()
reload_plugins = Signal() reload_plugins = Signal()
plugins_loaded = Signal() # For gui plugins_loaded = Signal() # For gui
plugin_state_changed = Signal(object) plugin_state_changed = Signal(object)
def _show_error(self, message: str, error: BaseException | None = None): 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: def _create_plugin_context(self, plugin: Plugin) -> PluginContext:
plugin_id = f"{plugin.group}:{plugin.id}" plugin_id = f"{plugin.group}:{plugin.id}"
data_root = (self.app.data_dir / "plugins").resolve() data_root = (self.app.data_dir / "plugins").resolve()
data_dir = (data_root / plugin.group / plugin.id).resolve() data_dir = (data_root / plugin.group / plugin.id).resolve()
if data_dir == data_root or not data_dir.is_relative_to(data_root): if data_dir == data_root or not data_dir.is_relative_to(data_root):
raise ValueError(f"Invalid plugin data directory: {plugin_id}") raise ValueError(f"Invalid plugin data directory: {plugin_id}")
data_dir.mkdir(parents=True, exist_ok=True) data_dir.mkdir(parents=True, exist_ok=True)
return PluginContext( return PluginContext(
plugin_id=plugin_id, plugin_id=plugin_id,
plugin_dir=plugin.path, plugin_dir=plugin.path,
@@ -357,7 +432,18 @@ 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,
get_instance=self.get_instance,
override_api=lambda name, callback: self._override_plugin_api(plugin, name, callback), 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]: 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: if not required_api_version:
raise ValueError("Required API version is missing.") 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: if not is_valid or support_api_ver_range is None:
raise ValueError("Plugin support api version range is invalid") raise ValueError("Plugin support api version range is invalid")
elif not is_support: elif not is_support:
@@ -606,3 +693,142 @@ class PluginManager(QObject):
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
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)
+12 -11
View File
@@ -185,8 +185,8 @@ class AccountPage(QWidget):
self.login_dialog = None self.login_dialog = None
# Layout # Layout
main_layout = QVBoxLayout() self.main_layout = QVBoxLayout()
right_layout = QVBoxLayout() self.right_layout = QVBoxLayout()
layout = QHBoxLayout(self) layout = QHBoxLayout(self)
# Widgets # Widgets
@@ -208,16 +208,16 @@ class AccountPage(QWidget):
self.avatar_size = QSize(32, 32) self.avatar_size = QSize(32, 32)
# Bind widget # Bind widget
main_layout.addWidget(self.account_list) self.main_layout.addWidget(self.account_list)
right_layout.addWidget(self.add_account_button) self.right_layout.addWidget(self.add_account_button)
right_layout.addWidget(self.refresh_button) self.right_layout.addWidget(self.refresh_button)
right_layout.addWidget(self.reload_button) self.right_layout.addWidget(self.reload_button)
right_layout.addWidget(self.delete_all_button) self.right_layout.addWidget(self.delete_all_button)
right_layout.addWidget(self.refresh_avatar_cache_button) self.right_layout.addWidget(self.refresh_avatar_cache_button)
right_layout.addStretch() self.right_layout.addStretch()
layout.addLayout(main_layout, 1) layout.addLayout(self.main_layout, 1)
layout.addLayout(right_layout) layout.addLayout(self.right_layout)
self.related_button : QToolButton = None self.related_button : QToolButton = None
@@ -375,6 +375,7 @@ class AccountPage(QWidget):
def _switch_account(self, account_id: str): def _switch_account(self, account_id: str):
self.account_manager.set_current_account(account_id) self.account_manager.set_current_account(account_id)
self.account_manager.save() self.account_manager.save()
self._account_head_updated(account_id)
def _current_account_changed(self, _account_id): def _current_account_changed(self, _account_id):
self._render_accounts() self._render_accounts()
+15 -11
View File
@@ -5,7 +5,7 @@ from typing import Callable
from PySide6.QtCore import Qt, QUrl, Signal from PySide6.QtCore import Qt, QUrl, Signal
from PySide6.QtGui import QDesktopServices, QImageReader from PySide6.QtGui import QDesktopServices, QImageReader
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
QFileDialog, QFormLayout, QFrame, QHBoxLayout, QLabel, QLineEdit, QFileDialog, QFormLayout, QFrame, QGridLayout, QHBoxLayout, QLabel, QLineEdit,
QMessageBox, QPushButton, QScrollArea, QSizePolicy, QSpinBox, QMessageBox, QPushButton, QScrollArea, QSizePolicy, QSpinBox,
QVBoxLayout, QWidget, QMenu, QComboBox, QTabWidget, QVBoxLayout, QWidget, QMenu, QComboBox, QTabWidget,
) )
@@ -130,14 +130,14 @@ class ManageProfilePage(QWidget):
self.list_layout.setSpacing(4) self.list_layout.setSpacing(4)
self.list_layout.setAlignment(Qt.AlignmentFlag.AlignTop) self.list_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
self.list_scroll.setWidget(self.list_content) self.list_scroll.setWidget(self.list_content)
self.list_scroll.setMinimumWidth(260) self.list_scroll.setMinimumWidth(220)
self.list_scroll.setMaximumWidth(380) self.list_scroll.setMaximumWidth(320)
columns.addWidget(self.list_scroll, 2) columns.addWidget(self.list_scroll, 1)
self.options_scroll = self._scroll_area("manageProfileOptionsScroll") self.options_scroll = self._scroll_area("manageProfileOptionsScroll")
self.options_content = QWidget() self.options_content = QWidget()
self.options_layout = QVBoxLayout(self.options_content) 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_layout.setSpacing(14)
self.options_scroll.setWidget(self.options_content) self.options_scroll.setWidget(self.options_content)
@@ -147,7 +147,7 @@ class ManageProfilePage(QWidget):
self.empty_label.setAlignment(Qt.AlignmentFlag.AlignCenter) self.empty_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.empty_label.setWordWrap(True) self.empty_label.setWordWrap(True)
self.options_layout.addWidget(self.empty_label, 1) 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 = QFrame()
self.editor.setObjectName("profileEditor") self.editor.setObjectName("profileEditor")
@@ -155,6 +155,7 @@ class ManageProfilePage(QWidget):
editor_layout.setSpacing(14) editor_layout.setSpacing(14)
form = QFormLayout() form = QFormLayout()
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow) form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
form.setRowWrapPolicy(QFormLayout.RowWrapPolicy.WrapAllRows)
form.setVerticalSpacing(12) form.setVerticalSpacing(12)
# Icon & Name # Icon & Name
@@ -209,17 +210,20 @@ class ManageProfilePage(QWidget):
editor_layout.addLayout(profile_head_h_layout) editor_layout.addLayout(profile_head_h_layout)
editor_layout.addLayout(form) 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 = QPushButton(self.app.tr_text("Add Modded Version"))
add_version_button.clicked.connect(self.open_add_modded_version_dialog) add_version_button.clicked.connect(self.open_add_modded_version_dialog)
open_button = QPushButton(self.app.tr_text("Open Profile Folder")) open_button = QPushButton(self.app.tr_text("Open Profile Folder"))
open_button.clicked.connect(self.open_profile_folder) open_button.clicked.connect(self.open_profile_folder)
import_button = QPushButton(self.app.tr_text("Import Mods…")) import_button = QPushButton(self.app.tr_text("Import Mods…"))
import_button.clicked.connect(self.import_mods) import_button.clicked.connect(self.import_mods)
file_actions.addWidget(add_version_button) file_actions.addWidget(add_version_button, 0, 0)
file_actions.addWidget(open_button) file_actions.addWidget(open_button, 0, 1)
file_actions.addWidget(import_button) file_actions.addWidget(import_button, 1, 0, 1, 2)
file_actions.addStretch() file_actions.setColumnStretch(0, 1)
file_actions.setColumnStretch(1, 1)
editor_layout.addLayout(file_actions) editor_layout.addLayout(file_actions)
self.plugin_actions = QHBoxLayout() self.plugin_actions = QHBoxLayout()
+2 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "testlauncher" name = "testlauncher"
version = "0.1.5a0" version = "0.1.6a0"
description = "A lightweight Minecraft launcher." description = "A lightweight Minecraft launcher."
readme = "README.md" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
@@ -17,6 +17,7 @@ dependencies = [
"requests>=2.32,<3", "requests>=2.32,<3",
"tomli>=2.2,<3; python_version < '3.11'", "tomli>=2.2,<3; python_version < '3.11'",
"tomli-w>=1.2,<2", "tomli-w>=1.2,<2",
"uuid>=1.30",
] ]
[dependency-groups] [dependency-groups]
@@ -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)
@@ -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."
+1 -5
View File
@@ -96,7 +96,7 @@ class ToolBar(QtWidgets.QToolBar):
) )
button.setMinimumWidth(60) 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(): if not isinstance(button_id, str) or not button_id.strip():
raise ValueError("Button id must be a non-empty string") raise ValueError("Button id must be a non-empty string")
if button_id in self.buttons: 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_test_page, self.test_page)
self.bind_page_button(self.open_launch_profile_page, self.launch_profile_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_settings_page, self.settings_page)
self.bind_page_button(self.open_account_page, self.account_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_create_profile_page, self.create_profile_page)
self.bind_page_button(self.open_manage_profile_page, self.manage_profile_page) self.bind_page_button(self.open_manage_profile_page, self.manage_profile_page)
# Apply page bar settings # Apply page bar settings