From c55f559989b8a59189add67cce6aad9e7ccc97c1 Mon Sep 17 00:00:00 2001 From: wei Date: Sat, 31 Oct 2026 15:22:47 +0800 Subject: [PATCH] Add PageBarSettings, enhance toolbar functionality with page focus/position persistence, and add multi-platform build scripts --- README.md | 14 +++ app.py | 3 +- build_linux.sh | 76 ++++++++++++ build_macos.sh | 75 ++++++++++++ build_windows.ps1 | 75 ++++++++++++ constant.py | 18 ++- manager/settings_models.py | 7 +- pages/settings.py | 13 ++- pyproject.toml | 1 + resources/translations/en.json | 3 +- resources/translations/zh-TW.json | 3 +- window.py | 185 ++++++++++++++++++++++-------- 12 files changed, 419 insertions(+), 54 deletions(-) create mode 100755 build_linux.sh create mode 100755 build_macos.sh create mode 100644 build_windows.ps1 diff --git a/README.md b/README.md index 4b6bc3c..303e67e 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,20 @@ uv run python main.py uv run python main.py --work-dir path_to_work_dir # With custom working directory ``` +### Build the project + +1. Install `uv` and sync the project with `uv sync`. +2. Install platform-specific dependencies: + - macOS: Install Xcode Command Line Tools (`xcode-select --install`) + - Windows: MSVC Build Tools (https://visualstudio.microsoft.com/downloads/) or MinGW (https://www.mingw.org/) + - Linux: Install GCC and `patchelf` using your distribution's package manager. +3. Build from source + - macOS: use `./build_macos.sh`. + - Windows: use `.\build_windows.ps1`. + - Linux: use `./build_linux.sh`. +4. Check the `build` directory for the launcher executable. All necessary files should be put in `build/TapLauncher` + (On macOS is `build/TapLauncher.app/`). + ### Themes You can customize the appearance of the launcher by adding a new theme to the `data/themes` under working directory. diff --git a/app.py b/app.py index 5a51c0f..da4f4b4 100644 --- a/app.py +++ b/app.py @@ -26,7 +26,7 @@ from manager.account import AccountManager from manager.game import GameManager from manager.profile import ProfileManager from manager.settings import SettingsManager -from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings, PluginSettings +from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings, PluginSettings, PageBarSettings from manager.widgets import WidgetManager from window import LauncherMainWindow @@ -71,6 +71,7 @@ class Launcher(QApplication, LauncherObject): self.settings_manager.register("appearance", AppearanceSettings) self.settings_manager.register("account", AccountSettings) self.settings_manager.register("plugins", PluginSettings) + self.settings_manager.register("page-bar", PageBarSettings) if self.root_settings_dir.is_file(): self.load_settings() else: diff --git a/build_linux.sh b/build_linux.sh new file mode 100755 index 0000000..4265455 --- /dev/null +++ b/build_linux.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# Build the native Linux application using the project's Nuitka configuration. +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: ./build_linux.sh [--dry-run] [Nuitka options...] + +Sync build dependencies and create build/TapLauncher.dist/TapLauncher (executable). +Requires uv, GCC, and patchelf. + + --dry-run Print the build command without syncing or compiling. + --help Show this help. + +Additional arguments are passed directly to Nuitka, for example: + ./build_linux.sh --jobs=4 +EOF +} + +dry_run=false +if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then + usage + exit 0 +fi +if [[ "${1:-}" == "--dry-run" ]]; then + dry_run=true + shift +fi + +if [[ "$(uname -s)" != "Linux" ]]; then + echo "Error: this script must run on Linux." >&2 + exit 1 +fi +if ! command -v uv >/dev/null 2>&1; then + echo "Error: uv is required. See https://docs.astral.sh/uv/getting-started/installation/" >&2 + exit 1 +fi + +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +cd "$project_dir" + +# Plugins load source files by path and import the public API dynamically. +build_command=( + uv run --no-sync python -m nuitka + --standalone + --output-filename=TapLauncher.bin + --output-folder-name=TapLauncher + --include-package=TapLauncher + --include-package=keyring.backends + --include-module=PySide6.QtNetwork + --include-module=xml.etree.ElementTree + --include-raw-dir=resources/builtin_plugins=resources/builtin_plugins + '--noinclude-data-files=**/__pycache__/**' + '--noinclude-data-files=**/.DS_Store' + "$@" + main.py +) + +if "$dry_run"; then + printf 'Working directory: %s\n' "$project_dir" + printf '%s\n' 'uv sync --group build' + printf '%q ' "${build_command[@]}" + printf '\n' + exit 0 +fi + +for dependency in gcc patchelf; do + if ! command -v "$dependency" >/dev/null 2>&1; then + printf 'Error: install %s using your Linux distribution package manager.\n' "$dependency" >&2 + exit 1 + fi +done + +uv sync --group build +"${build_command[@]}" +printf '\nBuild completed. Default executable path: %s/build/TapLauncher.dist/TapLauncher.bin\n' "$project_dir" diff --git a/build_macos.sh b/build_macos.sh new file mode 100755 index 0000000..62fb9f5 --- /dev/null +++ b/build_macos.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# Build the native macOS application using the project's Nuitka configuration. +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: ./build_macos.sh [--dry-run] [Nuitka options...] + +Sync build dependencies and create build/TapLauncher.app for the current +Python architecture (Apple Silicon or Intel). Requires uv and Xcode Command +Line Tools (install with: xcode-select --install). + + --dry-run Print the build command without syncing or compiling. + --help Show this help. + +Additional arguments are passed directly to Nuitka, for example: + ./build_macos.sh --jobs=4 + ./build_macos.sh --macos-sign-identity="Developer ID Application: ..." +EOF +} + +dry_run=false +if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then + usage + exit 0 +fi +if [[ "${1:-}" == "--dry-run" ]]; then + dry_run=true + shift +fi + +if [[ "$(uname -s)" != "Darwin" ]]; then + echo "Error: this script must run on macOS." >&2 + exit 1 +fi +if ! command -v uv >/dev/null 2>&1; then + echo "Error: uv is required. See https://docs.astral.sh/uv/getting-started/installation/" >&2 + exit 1 +fi + +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +cd "$project_dir" + +# Plugins load source files by path and import the public API dynamically. +# Keep their sources as raw data and explicitly compile the public API package. +build_command=( + uv run --no-sync python -m nuitka + --standalone + --include-package=TapLauncher + --include-package=keyring.backends + --include-module=PySide6.QtNetwork + --include-module=xml.etree.ElementTree + --include-raw-dir=resources/builtin_plugins=resources/builtin_plugins + '--noinclude-data-files=**/__pycache__/**' + '--noinclude-data-files=**/.DS_Store' + "$@" + main.py +) + +if "$dry_run"; then + printf 'Working directory: %s\n' "$project_dir" + printf '%s\n' 'uv sync --group build' + printf '%q ' "${build_command[@]}" + printf '\n' + exit 0 +fi + +if ! xcrun --find clang >/dev/null 2>&1; then + echo "Error: install Xcode Command Line Tools with: xcode-select --install" >&2 + exit 1 +fi + +uv sync --group build +"${build_command[@]}" +printf '\nBuild completed. Default application path: %s/build/TapLauncher.app\n' "$project_dir" diff --git a/build_windows.ps1 b/build_windows.ps1 new file mode 100644 index 0000000..5e26008 --- /dev/null +++ b/build_windows.ps1 @@ -0,0 +1,75 @@ +param( + [switch]$DryRun, + [switch]$Help, + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$NuitkaOptions = @() +) + +$ErrorActionPreference = 'Stop' + +if ($Help) { + @' +Usage: .\build_windows.ps1 [-DryRun] [Nuitka options...] + +Sync build dependencies and create build\TapLauncher.dist\TapLauncher.exe. +Requires uv, and Visual Studio 2022 Build Tools with the Desktop +development with C++ workload and Windows SDK. + + -DryRun Print the build command without syncing or compiling. + -Help Show this help. + +Examples: + .\build_windows.ps1 + .\build_windows.ps1 -DryRun + .\build_windows.ps1 --jobs=4 +'@ | Write-Output + exit 0 +} + +if ($env:OS -ne 'Windows_NT') { + Write-Error 'This script must run on Windows.' + exit 1 +} +if (-not (Get-Command uv -CommandType Application -ErrorAction SilentlyContinue)) { + Write-Error 'uv is required. See https://docs.astral.sh/uv/getting-started/installation/' + exit 1 +} + +# Reuse main.py's PySide6, resources, icon, and GUI console settings. +# Plugins load source files by path and import the public API dynamically. +$buildArgs = @( + 'run', '--no-sync', 'python', '-m', 'nuitka', + '--standalone', + '--msvc=latest', + '--output-filename=TapLauncher.exe', + '--output-folder-name=TapLauncher', + '--include-package=TapLauncher', + '--include-package=keyring.backends', + '--include-module=PySide6.QtNetwork', + '--include-module=xml.etree.ElementTree', + '--include-raw-dir=resources/builtin_plugins=resources/builtin_plugins', + '--noinclude-data-files=**/__pycache__/**', + '--noinclude-data-files=**/.DS_Store' +) + @($NuitkaOptions) + @('main.py') + +Push-Location -LiteralPath $PSScriptRoot +try { + if ($DryRun) { + Write-Output "Working directory: $PSScriptRoot" + Write-Output 'uv sync --group build' + $quotedArgs = $buildArgs | ForEach-Object { "'" + $_.Replace("'", "''") + "'" } + Write-Output ('& uv ' + ($quotedArgs -join ' ')) + } + else { + & uv sync --group build + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + & uv @buildArgs + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + Write-Output "Build completed. Default executable path: $PSScriptRoot\build\TapLauncher.dist\TapLauncher.exe" + } +} +finally { + Pop-Location +} diff --git a/constant.py b/constant.py index 036fb73..ea0d242 100644 --- a/constant.py +++ b/constant.py @@ -16,5 +16,21 @@ Launcher while being more lightweight and easier to use. This launcher is not associated with Mojang Studios or Microsoft. Is a personal project that just for fun. """ +LAUNCHER_DESCRIPTION_MARKDOWN = \ +""" +An unofficial Minecraft launcher written in Python. +It aims to maintain maximum compatibility with the official Minecraft +\n +*This launcher is not associated with Mojang Studios or Microsoft. Is a personal project that just for fun.* +\n\n +### Credits +- [PySide6](https://pypi.org/project/PySide6/): GUI framework +- [Nuitka](https://nuitka.net/): Build tool +- [Minecraft Wiki](https://minecraft.fandom.com/wiki/Main_Page): Account system and launcher development reference +\n +### Developer +- [Wei](https://repo.weispace.net/wei): Main developer + """ LAUNCHER_DESCRIPTION_KEYWORD = "$ABOUT_THIS_LAUNCHER" -WHEEL_PLUGIN_API_VERSION = "0.0.1" \ No newline at end of file +LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD = "$ABOUT_THIS_LAUNCHER_MARKDOWN" +WHEEL_PLUGIN_API_VERSION = "0.0.2" \ No newline at end of file diff --git a/manager/settings_models.py b/manager/settings_models.py index 6ebef66..aa02e2e 100644 --- a/manager/settings_models.py +++ b/manager/settings_models.py @@ -78,4 +78,9 @@ class AccountSettings(WarnExtraModel): class PluginSettings(WarnExtraModel): enabled: list[str] = Field(default_factory=list) - is_plugin_warning_shown: bool = False \ No newline at end of file + is_plugin_warning_shown: bool = False + +class PageBarSettings(WarnExtraModel): + focus_at_after_restart: bool = False + last_focused_page: str = "" + page_bar_position: Literal["left", "right", "top", "bottom"] = "left" \ No newline at end of file diff --git a/pages/settings.py b/pages/settings.py index 7748558..80a2502 100644 --- a/pages/settings.py +++ b/pages/settings.py @@ -12,10 +12,11 @@ from PySide6.QtWidgets import ( QPushButton, QStackedWidget, QVBoxLayout, - QWidget, QScrollArea, QSizePolicy, QSpinBox, + QWidget, QScrollArea, QSizePolicy, QSpinBox, QTextBrowser, ) -from constant import LAUNCHER_DESCRIPTION, LAUNCHER_NAME, LAUNCHER_VERSION, LAUNCHER_DESCRIPTION_KEYWORD +from constant import LAUNCHER_NAME, LAUNCHER_VERSION, LAUNCHER_DESCRIPTION_KEYWORD, \ + LAUNCHER_DESCRIPTION_MARKDOWN, LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD from core_lib.qt import messagebox from manager.settings_models import AccountSettings, AppearanceSettings, GeneralSettings from pages.plugins import PluginsDialog @@ -320,10 +321,14 @@ class SettingsPage(QWidget): version_label = QLabel(tr("Version: {version}", version=LAUNCHER_VERSION)) version_label.setObjectName("settingsVersion") - description_text = self.app.tr_text(LAUNCHER_DESCRIPTION_KEYWORD) - description = QPlainTextEdit(description_text if description_text != LAUNCHER_DESCRIPTION_KEYWORD else LAUNCHER_DESCRIPTION) + description_text = self.app.tr_text(LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD) + description = QTextBrowser() description.setObjectName("settingsDescription") description.setReadOnly(True) + description.setOpenExternalLinks(True) + + data = description_text if description_text != LAUNCHER_DESCRIPTION_MARKDOWN_KEYWORD else LAUNCHER_DESCRIPTION_MARKDOWN + description.setMarkdown(data) page.content_layout.addWidget(brand_label) page.content_layout.addWidget(version_label) diff --git a/pyproject.toml b/pyproject.toml index 168625e..4b9f43e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,6 +11,7 @@ dependencies = [ "colorlog>=6.9,<7", "keyring>=25.6,<26", "packaging>=26.2", + "platformdirs>=4,<5", "pydantic>=2.11,<3", "PySide6>=6.8,<7", "requests>=2.32,<3", diff --git a/resources/translations/en.json b/resources/translations/en.json index 1d0da08..716af7f 100644 --- a/resources/translations/en.json +++ b/resources/translations/en.json @@ -338,5 +338,6 @@ "{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": "" + "$ABOUT_THIS_LAUNCHER": "", + "$ABOUT_THIS_LAUNCHER_MARKDOWN": "" } diff --git a/resources/translations/zh-TW.json b/resources/translations/zh-TW.json index 04e9982..297f66a 100644 --- a/resources/translations/zh-TW.json +++ b/resources/translations/zh-TW.json @@ -338,5 +338,6 @@ "minutes": "分鐘", "{account} is currently signed in.": "{account} 目前已登入。", "{account}'s session has expired.": "{account} 的工作階段已過期。", - "$ABOUT_THIS_LAUNCHER": "一個使用Python編寫的非官方 Minecraft 啟動器。旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\n本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開開發的專案。" + "$ABOUT_THIS_LAUNCHER": "一個使用Python編寫的非官方 Minecraft 啟動器。旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\n本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開開發的專案。", + "$ABOUT_THIS_LAUNCHER_MARKDOWN": "一個使用Python編寫的非官方 Minecraft 啟動器。\n旨在與官方啟動器保持最大程度的兼容,同時更加輕量且易於使用。\n\\n\n*本啟動器和 Mojang 工作室 或 Microsoft 沒有任何隸屬關係。只是一個為了好玩而開開發的專案。*\n\\n\\n\n### 鳴謝\n- [PySide6](https://pypi.org/project/PySide6/): GUI 框架\n- [Nuitka](https://nuitka.net/): 構建工具\n- [Minecraft Wiki](https://minecraft.fandom.com/wiki/Main_Page): 帳號系統和啟動器開發參考\n\\n\n### 開發者\n- [Wei](https://repo.weispace.net/wei): 主要開發者" } diff --git a/window.py b/window.py index 02c5c1d..46a2359 100644 --- a/window.py +++ b/window.py @@ -3,7 +3,7 @@ from html import escape import sys from PySide6 import QtWidgets -from PySide6.QtCore import QSize +from PySide6.QtCore import QSize, Signal, QTimer from PySide6.QtGui import QIcon, Qt, QPixmap, QAction from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QToolButton, \ QStackedWidget @@ -14,6 +14,7 @@ from core_lib.qt import messagebox from core_lib.qt.progress_dialog import ProgressDialog from core_lib.qt.messagebox import ask_yes_no_with_plain_text from constant import MAIN_REPO_URL, LAUNCHER_VERSION, LAUNCHER_NAME, LAUNCHER_DESCRIPTION +from manager.settings_models import PageBarSettings from manager.widgets import AskForRequest, SelectPathRequest from pages.account import AccountPage from pages.create_profile import CreateProfilePage @@ -22,13 +23,35 @@ from pages.manage_profile import ManageProfilePage from pages.test import TestPage from pages.settings import SettingsPage +class PageButton(QToolButton): + def __init__(self, button_id: str, parent=None): + super().__init__(parent) + self.button_id = button_id + self.page = None + self.setCheckable(True) + self.setAutoExclusive(True) + + class ToolBar(QtWidgets.QToolBar): + PageButton = PageButton + position_changed = Signal() + def __init__(self, app: QApplication, parent=None): super(ToolBar, self).__init__(parent) self.app = app self.spacer = QWidget() self.orientationChanged.connect(self._update_widget_size) + self.buttons: dict[str, PageButton] = {} + self._position_timer = QTimer(self) + self._position_timer.setSingleShot(True) + self._position_timer.timeout.connect(self.position_changed.emit) + + def moveEvent(self, event): + super().moveEvent(event) + if hasattr(self, "_position_timer"): + self._position_timer.start(0) + def _update_widget_size(self, orientation): vertical = orientation == Qt.Orientation.Vertical @@ -43,8 +66,11 @@ class ToolBar(QtWidgets.QToolBar): QtWidgets.QSizePolicy.Policy.Preferred, ) - for button in self.findChildren(QToolButton): - if vertical: + for button in self.buttons.values(): + button.setToolTip(button.text().strip()) + button.setMinimumSize(0, 0) + button.setMaximumSize(16777215, 16777215) + if vertical and not button.icon().isNull(): button.setToolButtonStyle( Qt.ToolButtonStyle.ToolButtonIconOnly ) @@ -70,8 +96,13 @@ class ToolBar(QtWidgets.QToolBar): ) button.setMinimumWidth(60) - def add_button(self, text=None, icon: QIcon=None) -> QToolButton: - button = QtWidgets.QToolButton(self) + def add_button(self, button_id: str, text=None,icon: QIcon=None) -> QToolButton: + 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: + raise ValueError(f"Button id {button_id} already exists") + + button = self.PageButton(button_id, self) if text: text = " "+text @@ -94,13 +125,34 @@ class ToolBar(QtWidgets.QToolBar): button.setAutoRaise(True) button.setFixedHeight(60) + self.buttons[button_id] = button return button + def remove_button(self, button: PageButton): + if self.buttons.get(button.button_id) is button: + del self.buttons[button.button_id] + for action in self.actions(): + if self.widgetForAction(action) is button: + self.removeAction(action) + action.deleteLater() + button.hide() + button.deleteLater() + def update_all(self): self._update_widget_size(self.orientation()) self.update() + def is_button_id_exist(self, button_id: str) -> bool: + return button_id in self.buttons + + def focus_button(self, button_id: str): + if not self.is_button_id_exist(button_id): + return + + self.buttons[button_id].click() + self.buttons[button_id].setFocus() + class LauncherMainWindow(QMainWindow): def __init__(self, / ,app, parent: QWidget | None=None): super(LauncherMainWindow, self).__init__(parent) @@ -200,7 +252,7 @@ class LauncherMainWindow(QMainWindow): # Test Window btn if self.app.debug: - self.open_test_page = self.toolbar.add_button(" Tests") + self.open_test_page = self.toolbar.add_button("launcher.pagebutton.tests"," Tests") self.app.set_reloadable_toolbutton_icon( self.open_test_page, Path(self.app.icon_dir, "debug.png"), @@ -208,30 +260,30 @@ class LauncherMainWindow(QMainWindow): self.open_test_page.setObjectName("open_test_page") # Launch profile btn - self.open_launch_profile_page = self.toolbar.add_button(" Launch Profile", + self.open_launch_profile_page = self.toolbar.add_button("launcher.pagebutton.launch_profile", "Launch Profile", icon=self.app.get_icon(Path(self.app.icon_dir, "profile_default.png"), True)) # Home btn - self.home_button = self.toolbar.add_button(" Home") + self.home_button = self.toolbar.add_button("launcher.pagebutton.home"," Home") self.app.set_reloadable_toolbutton_icon( self.home_button, Path(self.app.icon_dir, "home.png"), ) # Settings btn (will be moved to the bottom of the toolbar) - self.open_settings_page = self.toolbar.add_button(" Settings") + self.open_settings_page = self.toolbar.add_button("launcher.pagebutton.settings"," Settings") self.app.set_reloadable_toolbutton_icon( self.open_settings_page, Path(self.app.icon_dir, "settings.png"), ) # Account btn (will be moved to the bottom (or last one item) of the toolbar - self.open_account_page = self.toolbar.add_button(" Accounts", icon=self.app.get_icon(Path(self.app.icon_dir, "head.png"), True)) + self.open_account_page = self.toolbar.add_button("launcher.pagebutton.account"," Accounts", icon=self.app.get_icon(Path(self.app.icon_dir, "head.png"), True)) self.account_page.set_related_button(self.open_account_page) # AccountPage require this to set button icon to # current account's avatar # Profile btn - self.open_create_profile_page = self.toolbar.add_button("Create Profile") + self.open_create_profile_page = self.toolbar.add_button("launcher.pagebutton.create_profile","Create Profile") self.app.set_reloadable_toolbutton_icon( self.open_create_profile_page, Path(self.app.icon_dir, "add.png"), @@ -239,6 +291,7 @@ class LauncherMainWindow(QMainWindow): # manage profile self.open_manage_profile_page = self.toolbar.add_button( + "launcher.pagebutton.manage_profile", " Manage Profiles", icon=self.app.get_icon(Path(self.app.icon_dir, "profile_edit.png"), True), ) @@ -260,39 +313,28 @@ class LauncherMainWindow(QMainWindow): self.toolbar.addWidget(self.open_account_page) # Bind page-related button click event - self.home_button.clicked.connect( - lambda: self.set_current_page(self.home_page, self.home_button) - ) + self.bind_page_button(self.home_button, self.home_page) if self.app.debug: - self.open_test_page.clicked.connect( - lambda: self.set_current_page(self.test_page, self.open_test_page) - ) + self.bind_page_button(self.open_test_page, self.test_page) - self.open_launch_profile_page.clicked.connect( - lambda: self.set_current_page(self.launch_profile_page, self.open_launch_profile_page) - ) + self.bind_page_button(self.open_launch_profile_page, self.launch_profile_page) - self.open_settings_page.clicked.connect( - lambda: self.set_current_page(self.settings_page, self.open_settings_page) - ) + self.bind_page_button(self.open_settings_page, self.settings_page) - self.open_account_page.clicked.connect( - lambda: self.set_current_page(self.account_page, self.open_account_page) - ) + self.bind_page_button(self.open_account_page, self.account_page) - self.open_create_profile_page.clicked.connect( - lambda: self.set_current_page(self.create_profile_page, self.open_create_profile_page) - ) + self.bind_page_button(self.open_create_profile_page, self.create_profile_page) - self.open_manage_profile_page.clicked.connect( - lambda: self.set_current_page(self.manage_profile_page, self.open_manage_profile_page) - ) + self.bind_page_button(self.open_manage_profile_page, self.manage_profile_page) + + # Apply page bar settings + self.apply_page_bar_settings() + self.toolbar.position_changed.connect(self.save_page_bar_position) # Bind signal event self.bind_event() - self.set_current_page(self.home_page, self.home_button) self.app.i18n.language_changed.connect(self.retranslate_ui) self.retranslate_ui() @@ -408,9 +450,23 @@ class LauncherMainWindow(QMainWindow): content=content, ) - def set_current_page(self, page: QWidget, related_button: QToolButton): + def set_current_page(self, page: QWidget, related_button: PageButton, *, persist=True): + if self.central.indexOf(page) < 0: + raise ValueError("Page is not registered") self.central.setCurrentWidget(page) + related_button.setChecked(True) related_button.setFocus() + if not persist: + return + self._pending_page_button = None + + try: + settings = self.app.settings_manager.get("page-bar", PageBarSettings).model_dump() + settings["last_focused_page"] = related_button.button_id + self.app.settings_manager.set("page-bar", settings) + self.app.settings_manager.save() + except Exception as e: + self.app.logger.exception(e) def bind_event(self): download_signal = self.widget_manager.download_signal @@ -527,6 +583,7 @@ class LauncherMainWindow(QMainWindow): help_menu.addAction(about_action) def register_plugin_apis(self, plugin_manager): + plugin_manager.register_api("launcher.window.add_page_button", self.plugin_add_page) 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) @@ -568,22 +625,23 @@ class LauncherMainWindow(QMainWindow): return restore - def plugin_add_page(self, title: str, page: QWidget, icon: QIcon = None): + def plugin_add_page(self, button_id: str, title: str, page: QWidget, icon: QIcon = None): self._check_plugin_gui_thread() - button = self.toolbar.add_button(title, icon) + if self.central.indexOf(page) >= 0: + raise ValueError("Page is already registered") + button = self.toolbar.add_button(button_id, 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.insertWidget(spacer_action, button) + self.bind_page_button(button, page) self.toolbar.update_all() + if getattr(self, "_pending_page_button", None) == button_id: + self.set_current_page(page, button, persist=False) + self._pending_page_button = None removed = False def remove(): @@ -599,9 +657,7 @@ class LauncherMainWindow(QMainWindow): self.central.removeWidget(page) page.hide() - self.toolbar.removeAction(action) - action.deleteLater() - button.deleteLater() + self.toolbar.remove_button(button) page.deleteLater() return remove @@ -638,3 +694,42 @@ class LauncherMainWindow(QMainWindow): self._check_plugin_gui_thread() selected = QFileDialog.getExistingDirectory(self, title, directory) return Path(selected) if selected else None + + def apply_page_bar_settings(self): + settings = self.app.settings_manager.get("page-bar", PageBarSettings) + self.addToolBar(self.page_bar_areas[settings.page_bar_position], self.toolbar) + self.toolbar.update_all() + focus = settings.focus_at_after_restart or settings.last_focused_page + self._pending_page_button = focus + button = self.toolbar.buttons.get(focus, self.home_button) + self.set_current_page(button.page, button, persist=False) + + page_bar_areas = { + "left": Qt.ToolBarArea.LeftToolBarArea, + "right": Qt.ToolBarArea.RightToolBarArea, + "top": Qt.ToolBarArea.TopToolBarArea, + "bottom": Qt.ToolBarArea.BottomToolBarArea, + } + + def save_page_bar_position(self): + if self.toolbar.isFloating(): + return + area = self.toolBarArea(self.toolbar) + position = next((name for name, value in self.page_bar_areas.items() if value == area), None) + if position is None: + return + try: + settings = self.app.settings_manager.get("page-bar", PageBarSettings).model_dump() + if settings["page_bar_position"] == position: + return + settings["page_bar_position"] = position + self.app.settings_manager.set("page-bar", settings) + self.app.settings_manager.save() + except Exception as error: + self.app.logger.exception(error) + + def bind_page_button(self, button: PageButton, page: QWidget): + button.page = page + button.clicked.connect(lambda: self.set_current_page( + self.home_page if button is self.home_button else button.page, button + ))