diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index 88611f4..804cf95 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -1,88 +1,130 @@ -name: Create Release - -env: - WORKFLOW_VERSION: 2 +name: Build AppImage and Release on: push: + branches: ['**'] pull_request: workflow_dispatch: +permissions: + contents: read + jobs: - create_release: - if: github.event_name == 'push' && github.ref == 'refs/heads/main' + build_appimage: + name: Build AppImage runs-on: ubuntu-latest - permissions: - contents: write + outputs: + version: ${{ steps.metadata.outputs.version }} + artifact_name: ${{ steps.metadata.outputs.artifact_name }} steps: - name: Checkout uses: actions/checkout@v4 with: - fetch-depth: 0 + persist-credentials: false - - name: Install dependencies for AppImage build + - name: Read version + id: metadata + run: | + set -euo pipefail + version=$(python3 -c 'import xml.etree.ElementTree as ET; print(ET.parse("data/metainfo/io.github.xarishark.mount-manager.metainfo.xml").find("releases/release").get("version", ""))') + if [[ ! "$version" =~ ^[0-9][0-9A-Za-z.+-]*$ ]]; then + echo "Invalid version in AppStream metadata: $version" >&2 + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "artifact_name=SMB-Mount-Manager-${GITHUB_SHA}-${GITHUB_RUN_ATTEMPT}" >> "$GITHUB_OUTPUT" + + - name: Install build dependencies run: | sudo apt-get update sudo apt-get install -y zsync - - name: Extract version and check against tags - id: version_check + - name: Build AppImage + env: + VERSION: ${{ steps.metadata.outputs.version }} run: | set -euo pipefail + packaging/build-appimage.sh + test -s "dist/SMB-Mount-Manager-${VERSION}-x86_64.AppImage" + test -s "dist/SMB-Mount-Manager-${VERSION}-x86_64.AppImage.zsync" + cd dist + sha256sum -c "SMB-Mount-Manager-${VERSION}-x86_64.AppImage.sha256" - new_version=$(sed -n -E 's/^[[:space:]]*]*version="?([^"]+)"?.*/\1/p; s/^[[:space:]]*]*version="?([^"]+)"?.*/\1/p' data/metainfo/io.github.xarishark.mount-manager.metainfo.xml | head -n1) - - if [ -z "$new_version" ]; then - echo "No version found in manifest" - exit 0 - fi + - name: Upload AppImage artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.metadata.outputs.artifact_name }} + path: | + dist/*.AppImage + dist/*.AppImage.sha256 + dist/*.AppImage.zsync + if-no-files-found: error + compression-level: 0 - # Compare against latest tag. - git fetch --tags origin || true - latest_tag=$(git describe --tags --abbrev=0 2>/dev/null || true) - latest_version="${latest_tag#v}" + create_release: + name: Publish version bump + needs: build_appimage + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + permissions: + contents: write + env: + VERSION: ${{ needs.build_appimage.outputs.version }} + BEFORE_SHA: ${{ github.event.before }} + GH_TOKEN: ${{ github.token }} + steps: + - name: Checkout history and tags + uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false - if [ -z "$latest_version" ]; then - echo "No existing tags, will create first release" - echo "new_version=$new_version" >> "$GITHUB_OUTPUT" - exit 0 + - name: Check version bump + id: version_check + run: | + set -euo pipefail + manifest=data/metainfo/io.github.xarishark.mount-manager.metainfo.xml + previous_version= + if [[ ! "$BEFORE_SHA" =~ ^0+$ ]]; then + previous_version=$(git show "$BEFORE_SHA:$manifest" | python3 -c 'import sys, xml.etree.ElementTree as ET; print(ET.parse(sys.stdin).find("releases/release").get("version", ""))') fi + latest_tag=$(git tag --list 'v[0-9]*' --sort=-version:refname | sed -n '1p') + latest_version=${latest_tag#v} - # Check if new version is higher. - highest=$(printf '%s\n' "$latest_version" "$new_version" | sort -V | tail -n1) - if [ "$highest" = "$new_version" ] && [ "$new_version" != "$latest_version" ]; then - echo "Version bumped from $latest_version to $new_version" - echo "new_version=$new_version" >> "$GITHUB_OUTPUT" - else - echo "Version $new_version not higher than $latest_version, skipping release" - fi + for baseline in "$previous_version" "$latest_version"; do + if [ -z "$baseline" ]; then + continue + fi + highest=$(printf '%s\n' "$baseline" "$VERSION" | sort -V | tail -n1) + if [ "$VERSION" = "$baseline" ] || [ "$VERSION" != "$highest" ]; then + echo "Version $VERSION is not newer than $baseline; skipping release." + exit 0 + fi + done + echo "release=true" >> "$GITHUB_OUTPUT" - - name: Build AppImage and create release - if: steps.version_check.outputs.new_version != '' + - name: Download built AppImage + if: steps.version_check.outputs.release == 'true' + uses: actions/download-artifact@v4 + with: + name: ${{ needs.build_appimage.outputs.artifact_name }} + path: dist + + - name: Create release + if: steps.version_check.outputs.release == 'true' run: | - VERSION="${{ steps.version_check.outputs.new_version }}" - echo "Creating release v${VERSION}" - # Fail if the release already exists to keep releases immutable. + set -euo pipefail if gh release view "v${VERSION}" >/dev/null 2>&1; then - echo "Release v${VERSION} already exists aborting" >&2 + echo "Release v${VERSION} already exists; refusing to overwrite it." >&2 exit 1 fi - - packaging/build-appimage.sh "$VERSION" - - APPIMAGE="dist/SMB-Mount-Manager-${VERSION}-x86_64.AppImage" - CHECKSUM="${APPIMAGE}.sha256" - ZSYNC="${APPIMAGE}.zsync" - test -f "$APPIMAGE" || { echo "AppImage not found: $APPIMAGE" >&2; exit 1; } - test -f "$CHECKSUM" || { echo "Checksum not found: $CHECKSUM" >&2; exit 1; } - test -f "$ZSYNC" || { echo "zsync file not found: $ZSYNC" >&2; exit 1; } - + cd dist + APPIMAGE="SMB-Mount-Manager-${VERSION}-x86_64.AppImage" + test -s "$APPIMAGE" + test -s "$APPIMAGE.zsync" + sha256sum -c "$APPIMAGE.sha256" gh release create "v${VERSION}" \ - "$APPIMAGE" \ - "$CHECKSUM" \ - "$ZSYNC" \ + "$APPIMAGE" "$APPIMAGE.sha256" "$APPIMAGE.zsync" \ --title "v${VERSION}" \ --generate-notes \ - --target "${{ github.sha }}" - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + --target "$GITHUB_SHA" diff --git a/AGENTS.md b/AGENTS.md index 37b721e..45be9e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,12 +27,19 @@ The application is split across two files: - Color scheme is delegated to `Adw.StyleManager` (`ColorScheme.DEFAULT`). Do not re-introduce custom CSS for theming or a custom color-scheme detector. - The mount list uses `Adw.PreferencesPage` → `Adw.PreferencesGroup` → `Adw.ActionRow` - per mount with the **hybrid row pattern**: switch + one inline primary suffix - (open-folder or Upgrade) + kebab `MenuButton` containing destructive actions. + per mount with a leading activation switch and inline suffix buttons ordered + open-folder (or Upgrade), Edit Credentials, then Delete. Delete always opens + the confirmation dialog. Unmanaged shares show a "Not managed" label and no controls. - To enumerate or clear rows in an `Adw.PreferencesGroup`, use `group.get_row(index)` — not `get_first_child()`, which returns the group's internal structure widgets, not the `ActionRow` children. +- Confirmed TPM credential failures also use a persistent notice above the mount + list and a steady red destructive-action style on affected Edit Credentials buttons. + The notice uses a compact red pill with one scoped CSS rule using semantic + error colors and the full explanation always visible. Affected share details + are dimmed and activation/folder access is disabled; Edit and Delete stay usable. + Do not override the global theme. Keep share subtitles to one line with status before path; full details stay in the tooltip. - Status / error messages are surfaced as `Adw.Toast` via `MainWindow.show_toast()`. Do not add new `Gtk.Window` / `Adw.Window` message dialogs. - Confirmation prompts use `Adw.AlertDialog`; destructive responses get @@ -44,6 +51,9 @@ The application is split across two files: of `Adw.PreferencesGroup`s — **not** `Adw.PreferencesPage`, whose internal `ScrolledWindow` would fix the dialog height and hide content revealed at runtime (e.g. the credentials group) behind a scrollbar. +- One app-owned `BackgroundWorker` serializes list reads, host checks, and helper + operations. Only main-loop callbacks may access GTK. Cancel stale host/read + results; defer closing until an active privileged operation finishes. - Always escape user-controlled strings (mount paths, statuses) with `GLib.markup_escape_text` before passing them to widgets that render Pango markup. - About box uses `Adw.AboutDialog`. @@ -67,10 +77,14 @@ The application is split across two files: - `packaging/appimage-helper.patch` rewrites the helper invocation so the AppImage re-execs itself under `pkexec`. It targets `mount_manager.py` (the installed filename), not the `mount-manager` symlink. Do not change the helper CLI surface - (`--helper {create|delete|upgrade|set-enabled}`) without updating this patch. + (`--helper {create|delete|upgrade|set-enabled|update-credentials}`) without updating this patch. - If you add a new top-level Python module that the GUI imports, you must add a matching `install` line in `packaging/build-appimage.sh`. +- AppImage update information must use the GitHub Releases `latest` transport + with a version wildcard. Always generate zsync metadata with the public release + download URL; never embed a CI filesystem path or pin discovery to one version. + ## Reference docs - Design spec: `docs/specs/2026-05-28-libadwaita-migration-design.md` diff --git a/mount_manager.py b/mount_manager.py index f36bef3..9e6afdf 100644 --- a/mount_manager.py +++ b/mount_manager.py @@ -20,6 +20,7 @@ import socket import subprocess import sys +import tempfile import time from pathlib import Path from typing import Any @@ -104,6 +105,7 @@ class ManagedMount: active: bool = False needs_upgrade: bool = False status: str = "Unknown" + credentials_need_update: bool = False @dataclasses.dataclass(frozen=True) @@ -116,6 +118,7 @@ class DisplayedMount: needs_upgrade: bool managed: bool managed_record: ManagedMount | None = None + credentials_need_update: bool = False def parse_share_path(raw_value: str) -> SharePath: @@ -208,6 +211,7 @@ def systemd_unit_name_for(mount_point: Path, suffix: str) -> str: result = run_command( ["systemd-escape", f"--suffix={suffix}", "--path", str(mount_point)], check=True, + timeout=3, ) unit_name = result.stdout.strip() if not unit_name.endswith(f".{suffix}"): @@ -537,7 +541,7 @@ def iter_findmnt_filesystems(payload: dict[str, Any]) -> list[dict[str, Any]]: def is_mounted(mount_point: Path) -> bool: - result = run_command(["findmnt", "--json", "--types", "cifs,smb3"], check=False) + result = run_command(["findmnt", "--json", "--types", "cifs,smb3"], check=False, timeout=3) if result.returncode != 0: return False try: @@ -716,6 +720,22 @@ def upgrade_mount(record: ManagedMount) -> None: reset_failed_units(record) +def update_credentials(manager_id: str, username_raw: str, password_raw: str) -> None: + username, password = validate_credentials(username_raw, password_raw) + record = load_record_by_id(manager_id) + + # Encrypt alongside the destination so replacement is atomic. Never try to + # decrypt the old blob: it may no longer be readable after a TPM change. + with tempfile.TemporaryDirectory(dir=record.credential_path.parent) as temporary_dir: + replacement = Path(temporary_dir) / record.credential_path.name + write_encrypted_credential_file(replacement, CREDENTIAL_NAME, username, password) + os.replace(replacement, record.credential_path) + + # An active automount can retry on the next access. Leave running mounts, + # unit files, metadata, and enabled/disabled state alone. + reset_failed_units(record) + + def delete_mount_by_id(manager_id: str) -> None: delete_mount(load_record_by_id(manager_id)) @@ -739,6 +759,68 @@ def load_record_by_id(manager_id: str) -> ManagedMount: return record +def journal_has_tpm_credential_failure(journal: str) -> bool: + """Recognize the reported TPM failure, rather than every mount/login error.""" + tpm_failure = False + credential_failure = False + for line in journal.splitlines(): + try: + entry = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(entry, dict): + continue + message = entry.get("MESSAGE", "") + if not isinstance(message, str): + continue + tpm_failure |= "tpm key integrity check failed" in message.lower() + credential_failure |= ( + str(entry.get("EXIT_STATUS", "")) == "243" + or "status=243/CREDENTIALS" in message + or "Failed at step CREDENTIALS" in message + ) + return tpm_failure and credential_failure + + +def mount_credentials_need_update(unit_name: str) -> bool: + """Check only a current failed invocation; never infer a BIOS update.""" + command = [ + "systemctl", "show", unit_name, + "--property=ActiveState,Result,InvocationID", "--no-pager", + ] + try: + snapshot = run_command(command, check=False, timeout=3) + if snapshot.returncode != 0: + return False + properties = dict(line.split("=", 1) for line in snapshot.stdout.splitlines() if "=" in line) + invocation = properties.get("InvocationID", "") + if ( + properties.get("ActiveState") != "failed" + or properties.get("Result") != "exit-code" + or not re.fullmatch(r"[a-f0-9]{32}", invocation) + or invocation == "0" * 32 + ): + return False + journal = run_command( + [ + "journalctl", "--boot=0", f"--unit={unit_name}", + f"--invocation={invocation}", "--output=json", "--no-pager", + "--quiet", "--lines=100", "--output-fields=MESSAGE,EXIT_STATUS", + ], + check=False, + timeout=3, + ) + if journal.returncode != 0 or not journal_has_tpm_credential_failure(journal.stdout): + return False + # Credentials may have been saved or the mount retried during the read. + current = run_command(command, check=False, timeout=3) + current_properties = dict(line.split("=", 1) for line in current.stdout.splitlines() if "=" in line) + return current.returncode == 0 and current_properties == properties + except MountManagerError: + # Journal access is optional. Do not prompt for root or guess a cause. + return False + + def load_record_from_metadata(path: Path) -> ManagedMount | None: try: payload = json.loads(path.read_text(encoding="utf-8")) @@ -801,8 +883,13 @@ def load_record_from_metadata(path: Path) -> ManagedMount | None: automount_active = systemd_is_active(automount_unit_name) mount_enabled = systemd_is_enabled(unit_name) active = automount_active and not needs_upgrade + credentials_need_update = ( + not mounted and not needs_upgrade and mount_credentials_need_update(unit_name) + ) if needs_upgrade: status = "Old version, please upgrade" + elif credentials_need_update: + status = "Credentials need updating" elif mounted and automount_active: status = "Mounted" elif mounted: @@ -830,19 +917,20 @@ def load_record_from_metadata(path: Path) -> ManagedMount | None: active=active, needs_upgrade=needs_upgrade, status=status, + credentials_need_update=credentials_need_update, ) def systemd_is_active(unit_name: str) -> bool: - return run_command(["systemctl", "is-active", "--quiet", unit_name], check=False).returncode == 0 + return run_command(["systemctl", "is-active", "--quiet", unit_name], check=False, timeout=3).returncode == 0 def systemd_is_enabled(unit_name: str) -> bool: - return run_command(["systemctl", "is-enabled", "--quiet", unit_name], check=False).returncode == 0 + return run_command(["systemctl", "is-enabled", "--quiet", unit_name], check=False, timeout=3).returncode == 0 def systemd_status(unit_name: str) -> str: - result = run_command(["systemctl", "is-active", unit_name], check=False) + result = run_command(["systemctl", "is-active", unit_name], check=False, timeout=3) status = result.stdout.strip() if status: return status.capitalize() @@ -865,7 +953,7 @@ def load_managed_mounts() -> list[ManagedMount]: def load_current_smb_mounts() -> list[DisplayedMount]: - result = run_command(["findmnt", "--json", "--types", "cifs,smb3"], check=False) + result = run_command(["findmnt", "--json", "--types", "cifs,smb3"], check=False, timeout=3) if result.returncode != 0: return [] try: @@ -902,10 +990,14 @@ def load_displayed_mounts() -> list[DisplayedMount]: mount_point=record.mount_point, status=record.status, active=record.active, - openable=not record.needs_upgrade and (record.active or record.mounted), + openable=( + not record.needs_upgrade and not record.credentials_need_update + and (record.active or record.mounted) + ), needs_upgrade=record.needs_upgrade, managed=True, managed_record=record, + credentials_need_update=record.credentials_need_update, ) for record in managed_records ] @@ -976,6 +1068,14 @@ def request_helper_upgrade(record: ManagedMount) -> None: run_privileged_helper("upgrade", {"manager_id": record.manager_id}) +def request_helper_update_credentials(record: ManagedMount, username: str, password: str) -> None: + validate_credentials(username, password) + run_privileged_helper( + "update-credentials", + {"manager_id": record.manager_id, "username": username, "password": password}, + ) + + def request_helper_set_enabled(record: ManagedMount, enabled: bool) -> None: run_privileged_helper( "set-enabled", @@ -1027,6 +1127,12 @@ def run_helper_mode(action: str) -> int: delete_mount_by_id(str(payload.get("manager_id", ""))) elif action == "upgrade": upgrade_mount_by_id(str(payload.get("manager_id", ""))) + elif action == "update-credentials": + update_credentials( + str(payload.get("manager_id", "")), + str(payload.get("username", "")), + str(payload.get("password", "")), + ) elif action == "set-enabled": set_mount_enabled_by_id( str(payload.get("manager_id", "")), @@ -1056,7 +1162,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace: parser = argparse.ArgumentParser(description=APP_NAME) parser.add_argument( "--helper", - choices=("create", "delete", "upgrade", "set-enabled"), + choices=("create", "delete", "upgrade", "set-enabled", "update-credentials"), help=argparse.SUPPRESS, ) return parser.parse_args(argv) diff --git a/mount_manager_ui.py b/mount_manager_ui.py index e0d7eba..f2d6e07 100644 --- a/mount_manager_ui.py +++ b/mount_manager_ui.py @@ -23,10 +23,12 @@ request_helper_delete, request_helper_set_enabled, request_helper_upgrade, + request_helper_update_credentials, validate_credentials, ) import sys +import queue import threading import gi @@ -36,6 +38,56 @@ from gi.repository import Adw, Gdk, Gio, GLib, Gtk +class BackgroundWorker: + """One app-owned thread; callbacks are delivered on the GTK main loop.""" + + def __init__(self) -> None: + self._jobs = queue.Queue() + self._closed = threading.Event() + self._thread = threading.Thread(target=self._run, name="mount-manager-worker", daemon=True) + self._thread.start() + + def submit(self, operation, callback, cancellable=None): + if self._closed.is_set(): + raise RuntimeError("The application worker is closed.") + if cancellable is None: + cancellable = Gio.Cancellable() + self._jobs.put((operation, callback, cancellable)) + return cancellable + + def _run(self) -> None: + while True: + job = self._jobs.get() + if job is None: + return + operation, callback, cancellable = job + del job + if not self._closed.is_set() and not cancellable.is_cancelled(): + result, error = None, None + try: + result = operation() + except Exception as exc: + error = exc + if not self._closed.is_set() and not cancellable.is_cancelled(): + GLib.idle_add(self._deliver, callback, cancellable, result, error) + del result, error + del operation, callback, cancellable + + def _deliver(self, callback, cancellable, result, error) -> bool: + if not self._closed.is_set() and not cancellable.is_cancelled(): + callback(result, error) + return GLib.SOURCE_REMOVE + + def close(self) -> None: + self._closed.set() + while True: + try: + self._jobs.get_nowait() + except queue.Empty: + break + self._jobs.put(None) + + def GLib_markup_escape(text: str) -> str: """Escape Pango markup characters in row titles/subtitles.""" return GLib.markup_escape_text(text, -1) @@ -57,11 +109,27 @@ def apply_style_manager() -> None: """Hand color-scheme selection to libadwaita's preference tracker.""" Adw.StyleManager.get_default().set_color_scheme(Adw.ColorScheme.DEFAULT) Gtk.Window.set_default_icon_name(APP_ICON_NAME) + notice_style = Gtk.CssProvider() + notice_style.load_from_data(b""" + .credential-notice { + background-color: alpha(@error_color, 0.12); + border: 1px solid alpha(@error_color, 0.4); + border-radius: 24px; + padding: 8px 14px; + } + .credential-unavailable .title, + .credential-unavailable .subtitle { + opacity: 0.5; + } + """) + Gtk.StyleContext.add_provider_for_display( + Gdk.Display.get_default(), notice_style, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + ) def mount_status_line(mount: DisplayedMount) -> str: - """Build the AdwActionRow subtitle: `` · ``.""" - return f"{mount.mount_point} · {mount.status}" + """Keep status visible before a potentially long mount path.""" + return f"{mount.status} · {mount.mount_point}" def run_gui() -> int: @@ -126,6 +194,7 @@ def __init__(self, main_window: "MainWindow") -> None: self.share_path: SharePath | None = None self._debounce_id: int = 0 self._cancellable: Gio.Cancellable | None = None + self._adding = False self.cancel_button = Gtk.Button(label="Cancel") self.cancel_button.connect("clicked", lambda _b: self.close()) @@ -215,6 +284,7 @@ def _cancel_pending_host_check(self) -> None: def _cleanup(self, *_args) -> None: self._cancel_pending_host_check() + self.password_row.set_text("") def _show_banner(self, message: str) -> None: self.banner.set_title(message) @@ -254,26 +324,13 @@ def _run_host_check(self) -> bool: cancellable = Gio.Cancellable() self._cancellable = cancellable self.host_spinner.set_visible(True) - thread = threading.Thread( - target=self._host_check_worker, - args=(cancellable, text), - daemon=True, + self.main_window.get_application().worker.submit( + lambda: check_smb_host_reachable(text), + lambda result, error: self._on_host_check_done(cancellable, result, error), + cancellable, ) - thread.start() return False - def _host_check_worker(self, cancellable: Gio.Cancellable, text: str) -> None: - try: - result: tuple[SharePath | None, BaseException | None] = ( - check_smb_host_reachable(text), - None, - ) - except Exception as exc: - result = (None, exc) - if cancellable.is_cancelled(): - return - GLib.idle_add(self._on_host_check_done, cancellable, result[0], result[1]) - def _on_host_check_done( self, cancellable: Gio.Cancellable, @@ -297,40 +354,159 @@ def _on_host_check_done( def _update_add_sensitive(self) -> None: ready = ( - self.share_path is not None + not self._adding + and self.share_path is not None and bool(self.user_row.get_text().strip()) and bool(self.password_row.get_text()) ) self.add_button.set_sensitive(ready) def _on_add_clicked(self) -> None: - if self.share_path is None: + if self.share_path is None or self._adding: return share = self.share_path.source - username = self.user_row.get_text() - password = self.password_row.get_text() + username, password = self.user_row.get_text(), self.password_row.get_text() try: validate_credentials(username, password) - request_helper_create(share, username, password) except MountManagerError as exc: self._show_banner(str(exc)) return - except Exception as exc: - self._show_banner(f"Unexpected error: {exc}") + + def done(error) -> None: + self._adding = False + self.set_can_close(True) + self.cancel_button.set_sensitive(True) + self.add_button.set_label("Add") + self.host_spinner.set_visible(False) + for entry in (self.path_row, self.user_row, self.password_row): + entry.set_sensitive(True) + self._update_add_sensitive() + if error is not None: + self._show_banner(str(error)) + else: + self.close() + self.main_window.show_toast(f"{share} added") + + if self.main_window._run_helper_action( + "Add share", lambda: request_helper_create(share, username, password), on_done=done + ): + self._adding = True + self.set_can_close(False) + self.cancel_button.set_sensitive(False) + self.add_button.set_label("Adding…") + self.add_button.set_sensitive(False) + self.host_spinner.set_visible(True) + self._hide_banner() + for entry in (self.path_row, self.user_row, self.password_row): + entry.set_sensitive(False) + + class UpdateCredentialsDialog(Adw.Dialog): + def __init__(self, main_window: "MainWindow", record: ManagedMount) -> None: + super().__init__() + self.set_title("Edit Credentials") + self.set_content_width(420) + self.main_window = main_window + self.record = record + + self._saving = False + self.cancel_button = Gtk.Button(label="Cancel") + self.cancel_button.connect("clicked", lambda _b: self.close()) + self.save_button = Gtk.Button(label="Save") + self.save_button.add_css_class("suggested-action") + self.save_button.set_sensitive(False) + self.save_button.connect("clicked", lambda _b: self._on_save_clicked()) + header = Adw.HeaderBar() + header.set_show_end_title_buttons(False) + header.pack_start(self.cancel_button) + header.pack_end(self.save_button) + + group = Adw.PreferencesGroup() + group.set_title(GLib_markup_escape(record.source)) + group.set_description( + "Enter your username and password again to replace the stored credentials. " + "They will be used the next time this share is mounted." + ) + self.user_row = Adw.EntryRow(title="Username") + self.password_row = Adw.PasswordEntryRow(title="Password") + for entry in (self.user_row, self.password_row): + entry.connect("changed", lambda _r: self._update_save_sensitive()) + group.add(entry) + + body = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24) + body.set_margin_top(24) + body.set_margin_bottom(24) + body.set_margin_start(12) + body.set_margin_end(12) + body.append(group) + clamp = Adw.Clamp() + clamp.set_maximum_size(600) + clamp.set_child(body) + toolbar = Adw.ToolbarView() + toolbar.add_top_bar(header) + toolbar.set_content(clamp) + self.set_child(toolbar) + self.set_default_widget(self.save_button) + self.connect("map", lambda _d: self.user_row.grab_focus()) + self.connect("closed", lambda _d: self.password_row.set_text("")) + + def _update_save_sensitive(self) -> None: + self.save_button.set_sensitive( + not self._saving + and bool(self.user_row.get_text().strip()) and bool(self.password_row.get_text()) + ) + + def _on_save_clicked(self) -> None: + if self._saving: return + username, password = self.user_row.get_text(), self.password_row.get_text() + try: + validate_credentials(username, password) + except MountManagerError as exc: + self.main_window.show_toast(str(exc)) + return + + def done(error) -> None: + self._saving = False + self.set_can_close(True) + self.cancel_button.set_sensitive(True) + self.save_button.set_label("Save") + self.user_row.set_sensitive(True) + self.password_row.set_sensitive(True) + self._update_save_sensitive() + if error is not None: + self.main_window.show_toast(f"Update credentials failed: {error}") + else: + self.close() + self.main_window.show_toast(f"Credentials updated for {self.record.source}") - self.close() - self.main_window.refresh() - self.main_window.show_toast(f"{share} added") + if self.main_window._run_helper_action( + "Update credentials", + lambda: request_helper_update_credentials(self.record, username, password), + on_done=done, + ): + self._saving = True + self.set_can_close(False) + self.cancel_button.set_sensitive(False) + self.save_button.set_label("Saving…") + self.save_button.set_sensitive(False) + self.user_row.set_sensitive(False) + self.password_row.set_sensitive(False) class MainWindow(Adw.ApplicationWindow): def __init__(self, app: Adw.Application) -> None: super().__init__(application=app, title=APP_NAME) self.set_default_size(760, 480) self.set_icon_name(APP_ICON_NAME) + self._refreshing = False + self._operation_busy = False + self._loaded = False + self._closing = False + self._close_when_idle = False + self._refresh_cancellable = None + self.connect("close-request", self._on_close_request) bind_action(self, app, "win.about", self.show_about_dialog) - bind_action(self, app, "win.close", self.close, ("w",)) + bind_action(self, app, "win.close", self.request_close, ("w",)) bind_action(self, app, "win.add-share", self.show_add_dialog, ("n",)) bind_action(self, app, "win.refresh", self.refresh, ("r",)) bind_action(self, app, "win.show-menu", self._open_primary_menu, ("F10",)) @@ -343,9 +519,10 @@ def __init__(self, app: Adw.Application) -> None: self.menu_button.set_menu_model(menu) self.menu_button.set_tooltip_text("Primary menu") - refresh_button = Gtk.Button.new_from_icon_name("view-refresh-symbolic") - refresh_button.set_tooltip_text("Refresh") - refresh_button.set_action_name("win.refresh") + self.refresh_button = Gtk.Button.new_from_icon_name("view-refresh-symbolic") + self.refresh_button.set_tooltip_text("Refresh") + self.refresh_button.set_action_name("win.refresh") + self.refresh_spinner = Adw.Spinner() add_button = Gtk.Button.new_from_icon_name("list-add-symbolic") add_button.set_tooltip_text("Add SMB share") @@ -354,7 +531,7 @@ def __init__(self, app: Adw.Application) -> None: header = Adw.HeaderBar() header.pack_start(add_button) header.pack_end(self.menu_button) - header.pack_end(refresh_button) + header.pack_end(self.refresh_button) self.toast_overlay = Adw.ToastOverlay() @@ -376,10 +553,35 @@ def __init__(self, app: Adw.Application) -> None: self.preferences_page = Adw.PreferencesPage() self.preferences_page.set_vexpand(True) + self.credential_notice = Adw.PreferencesGroup() + self.credential_notice.set_visible(False) + notice_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) + notice_box.add_css_class("credential-notice") + notice_icon = Gtk.Image.new_from_icon_name("dialog-error-symbolic") + notice_icon.add_css_class("error") + notice_box.append(notice_icon) + notice_text = Gtk.Label(xalign=0) + notice_text.set_text( + "Saved credentials cannot be unlocked. This can happen after a BIOS update " + "or TPM reset. Use the red pencil button beside each affected share to " + "re-enter its SMB username and password." + ) + notice_text.set_wrap(True) + notice_text.set_hexpand(True) + notice_box.append(notice_text) + self.credential_notice.add(notice_box) + self.preferences_page.add(self.credential_notice) + self.mount_group = Adw.PreferencesGroup() self.mount_group.set_separate_rows(True) self.preferences_page.add(self.mount_group) + self.loading_page = Adw.StatusPage(title="Loading shares…") + self.loading_page.set_vexpand(True) + loading_spinner = Adw.Spinner() + loading_spinner.set_size_request(32, 32) + self.loading_page.set_child(loading_spinner) + self.content_box.append(self.loading_page) self.content_box.append(self.preferences_page) self.content_box.append(self.empty_page) @@ -396,14 +598,74 @@ def _open_primary_menu(self) -> None: def show_toast(self, message: str) -> None: self.toast_overlay.add_toast(Adw.Toast(title=message)) + def _update_busy(self) -> None: + busy = self._refreshing or self._operation_busy + self.lookup_action("refresh").set_enabled(not busy) + self.lookup_action("add-share").set_enabled(not busy) + self.mount_group.set_sensitive(not busy) + if busy: + self.refresh_button.set_child(self.refresh_spinner) + self.refresh_button.set_tooltip_text("Working…") + else: + self.refresh_button.set_icon_name("view-refresh-symbolic") + self.refresh_button.set_tooltip_text("Refresh") + + def request_close(self) -> None: + if self._operation_busy: + self._close_when_idle = True + self.show_toast("Finishing the current operation before closing…") + else: + dialog = self.get_visible_dialog() + if dialog is None: + self.close() + else: + dialog.connect("closed", lambda _d: self.close()) + dialog.force_close() + + def _on_close_request(self, *_args) -> bool: + if self._operation_busy: + self.request_close() + return True + self._closing = True + if self._refresh_cancellable is not None: + self._refresh_cancellable.cancel() + return False + def refresh(self) -> None: + if self._refreshing or self._operation_busy or self._closing: + return + self._refreshing = True + self._update_busy() + self.loading_page.set_visible(not self._loaded) + if not self._loaded: + self.preferences_page.set_visible(False) + self.empty_page.set_visible(False) + self._refresh_cancellable = self.get_application().worker.submit( + load_displayed_mounts, self._on_refresh_done + ) + + def _on_refresh_done(self, mounts, error) -> None: + if self._closing: + return + self._refreshing = False + self._refresh_cancellable = None + self._update_busy() + self.loading_page.set_visible(False) + if error is not None: + self.show_toast(f"Could not load shares: {error}") + if not self._loaded: + self.empty_page.set_title("Could not load shares") + self.empty_page.set_visible(True) + return + self._loaded = True + self.empty_page.set_title("No SMB shares") while (row := self.mount_group.get_row(0)) is not None: self.mount_group.remove(row) - - mounts = load_displayed_mounts() self.empty_page.set_visible(not mounts) self.preferences_page.set_visible(bool(mounts)) - + self.credential_notice.set_visible( + any(mount.managed and mount.credentials_need_update for mount in mounts) + ) for mount in mounts: self.mount_group.add(self.row_for(mount)) @@ -411,6 +673,9 @@ def row_for(self, mount: DisplayedMount) -> Adw.ActionRow: row = Adw.ActionRow() row.set_title(GLib_markup_escape(mount.source)) row.set_subtitle(GLib_markup_escape(mount_status_line(mount))) + row.set_title_lines(1) + row.set_subtitle_lines(1) + row.set_tooltip_text(f"{mount.source}\n{mount_status_line(mount)}") if not mount.managed or mount.managed_record is None: not_managed_label = Gtk.Label(label="Not managed") @@ -420,12 +685,16 @@ def row_for(self, mount: DisplayedMount) -> Adw.ActionRow: return row record = mount.managed_record + if mount.credentials_need_update: + row.add_css_class("credential-unavailable") mount_switch = Gtk.Switch() mount_switch.set_valign(Gtk.Align.CENTER) mount_switch.set_active(mount.active) - mount_switch.set_sensitive(not mount.needs_upgrade) - if mount.needs_upgrade: + mount_switch.set_sensitive(not mount.needs_upgrade and not mount.credentials_need_update) + if mount.credentials_need_update: + mount_switch.set_tooltip_text("Update credentials before using this share") + elif mount.needs_upgrade: mount_switch.set_tooltip_text( "Upgrade this older mount before enabling it" ) @@ -437,11 +706,12 @@ def row_for(self, mount: DisplayedMount) -> Adw.ActionRow: "notify::active", lambda switch, _param: self.toggle_mount(record, switch), ) - row.add_suffix(mount_switch) + row.add_prefix(mount_switch) if mount.needs_upgrade: upgrade_button = Gtk.Button(label="Upgrade") upgrade_button.set_valign(Gtk.Align.CENTER) + upgrade_button.set_sensitive(not mount.credentials_need_update) upgrade_button.set_tooltip_text( "Upgrade mount units using the existing encrypted credentials" ) @@ -452,35 +722,39 @@ def row_for(self, mount: DisplayedMount) -> Adw.ActionRow: open_button = Gtk.Button.new_from_icon_name("folder-open-symbolic") open_button.set_valign(Gtk.Align.CENTER) open_button.add_css_class("flat") - open_button.set_sensitive(mount.openable) + open_button.set_sensitive(mount.openable and not mount.credentials_need_update) open_button.set_tooltip_text( - "Open mount folder" - if mount.openable - else "Enable on-demand access to open its folder" + "Update credentials before opening this share" + if mount.credentials_need_update else + "Open mount folder" if mount.openable else + "Enable on-demand access to open its folder" ) open_button.connect( "clicked", lambda _b: self.open_mount_folder(record) ) row.add_suffix(open_button) - menu = Gio.Menu() - menu.append("Delete\u2026", f"row.delete::{record.manager_id}") - - row_action_group = Gio.SimpleActionGroup() - delete_action = Gio.SimpleAction.new("delete", GLib.VariantType.new("s")) - delete_action.connect( - "activate", lambda _a, _p, r=record: self.confirm_delete(r) + credentials_button = Gtk.Button.new_from_icon_name("document-edit-symbolic") + credentials_button.set_valign(Gtk.Align.CENTER) + if mount.credentials_need_update: + credentials_button.add_css_class("destructive-action") + credentials_button.set_tooltip_text( + "Credentials need updating: re-enter your SMB username and password" + ) + else: + credentials_button.add_css_class("flat") + credentials_button.set_tooltip_text("Edit credentials") + credentials_button.connect( + "clicked", lambda _b: UpdateCredentialsDialog(self, record).present(self) ) - row_action_group.add_action(delete_action) - row.insert_action_group("row", row_action_group) + row.add_suffix(credentials_button) - menu_button = Gtk.MenuButton() - menu_button.set_valign(Gtk.Align.CENTER) - menu_button.set_icon_name("view-more-symbolic") - menu_button.add_css_class("flat") - menu_button.set_menu_model(menu) - menu_button.set_tooltip_text("More actions") - row.add_suffix(menu_button) + delete_button = Gtk.Button.new_from_icon_name("user-trash-symbolic") + delete_button.set_valign(Gtk.Align.CENTER) + delete_button.add_css_class("flat") + delete_button.set_tooltip_text("Delete share") + delete_button.connect("clicked", lambda _b: self.confirm_delete(record)) + row.add_suffix(delete_button) return row @@ -500,9 +774,6 @@ def show_about_dialog(self) -> None: about.present(self) def open_mount_folder(self, record: ManagedMount) -> None: - if not record.mount_point.exists(): - self.show_toast(f"Mount folder does not exist: {record.mount_point}") - return launcher = Gtk.FileLauncher.new( Gio.File.new_for_path(str(record.mount_point)) ) @@ -518,29 +789,41 @@ def _on_open_folder_done( return self.show_toast(f"Could not open folder: {exc.message}") - def _run_helper_action(self, label: str, callback) -> bool: - """Invoke a privileged helper callback, toast on failure, return True on success.""" - try: - callback() - except Exception as exc: - self.show_toast(f"{label} failed: {exc}") + def _run_helper_action(self, label: str, callback, *, message=None, on_done=None) -> bool: + """Serialize changes and deliver their result on the main thread.""" + if self._operation_busy or self._refreshing or self._closing: return False + self._operation_busy = True + self._update_busy() + + def done(_result, error) -> None: + self._operation_busy = False + self._update_busy() + if on_done is not None: + on_done(error) + elif error is not None: + self.show_toast(f"{label} failed: {error}") + elif message: + self.show_toast(message) + if self._close_when_idle: + self.request_close() + else: + self.refresh() + + self.get_application().worker.submit(callback, done) return True def upgrade_mount(self, record: ManagedMount) -> None: - if self._run_helper_action( - "Upgrade", lambda: request_helper_upgrade(record) - ): - self.refresh() - self.show_toast(f"{record.source} upgraded") + self._run_helper_action( + "Upgrade", lambda: request_helper_upgrade(record), + message=f"{record.source} upgraded", + ) def toggle_mount(self, record: ManagedMount, switch: Gtk.Switch) -> None: enabled = switch.get_active() - switch.set_sensitive(False) self._run_helper_action( "Toggle", lambda: request_helper_set_enabled(record, enabled) ) - self.refresh() def confirm_delete(self, record: ManagedMount) -> None: alert = Adw.AlertDialog( @@ -563,11 +846,10 @@ def _on_delete_response( ) -> None: if response != "delete": return - if self._run_helper_action( - "Delete", lambda: request_helper_delete(record) - ): - self.refresh() - self.show_toast(f"{record.source} removed") + self._run_helper_action( + "Delete", lambda: request_helper_delete(record), + message=f"{record.source} removed", + ) class MountManagerApplication(Adw.Application): def __init__(self) -> None: @@ -576,7 +858,8 @@ def __init__(self) -> None: flags=Gio.ApplicationFlags.DEFAULT_FLAGS, ) - bind_action(self, self, "app.quit", self.quit, ("q",)) + self.worker = BackgroundWorker() + bind_action(self, self, "app.quit", self.request_quit, ("q",)) bind_action( self, self, @@ -585,6 +868,17 @@ def __init__(self) -> None: ("question",), ) + def request_quit(self) -> None: + window = self.props.active_window + if window is not None: + window.request_close() + else: + self.quit() + + def do_shutdown(self) -> None: + self.worker.close() + Adw.Application.do_shutdown(self) + def _show_shortcuts(self) -> None: window = self.props.active_window if window is None: diff --git a/packaging/appimage-helper.patch b/packaging/appimage-helper.patch index d9437c1..8e2ef8f 100644 --- a/packaging/appimage-helper.patch +++ b/packaging/appimage-helper.patch @@ -1,7 +1,7 @@ diff --git a/mount_manager.py b/mount_manager.py --- a/mount_manager.py +++ b/mount_manager.py -@@ -921,18 +921,51 @@ +@@ -921,18 +921,52 @@ return displayed @@ -31,6 +31,7 @@ diff --git a/mount_manager.py b/mount_manager.py - command = [ +def privileged_helper_command(pkexec: str, action: str) -> list[str]: ++ # Forward all helper actions, including credential updates, unchanged. + appimage = appimage_helper_path() + if appimage is not None: + return [ diff --git a/packaging/build-appimage.sh b/packaging/build-appimage.sh index e63c44e..2f4fae7 100755 --- a/packaging/build-appimage.sh +++ b/packaging/build-appimage.sh @@ -145,6 +145,11 @@ if [ "$appdir_only" -eq 1 ]; then exit 0 fi +if ! command -v zsyncmake >/dev/null 2>&1; then + echo "zsyncmake not found. Install the zsync package." >&2 + exit 1 +fi + appimagetool="${APPIMAGETOOL:-}" if [ -z "$appimagetool" ] && command -v appimagetool >/dev/null 2>&1; then appimagetool="$(command -v appimagetool)" @@ -169,7 +174,8 @@ echo "Using appimagetool: $appimagetool" "$appimagetool" --version || true rm -f "$output" "$output.sha256" "$output.zsync" -UPDATE_INFO="zsync|https://github.com/Xarishark/mount-manager/releases/download/v${version}/${APPIMAGE_NAME}-${version}-${arch}.AppImage.zsync" +UPDATE_INFO="gh-releases-zsync|Xarishark|mount-manager|latest|${APPIMAGE_NAME}-*-${arch}.AppImage.zsync" +DOWNLOAD_URL="https://github.com/Xarishark/mount-manager/releases/download/v${version}/${APPIMAGE_NAME}-${version}-${arch}.AppImage" echo "Building AppImage with UPDATE_INFO: $UPDATE_INFO" if ! ARCH="$arch" APPIMAGE_EXTRACT_AND_RUN=1 "$appimagetool" -u "$UPDATE_INFO" "$appdir" "$output"; then echo "appimagetool failed to build AppImage" >&2 @@ -177,15 +183,9 @@ if ! ARCH="$arch" APPIMAGE_EXTRACT_AND_RUN=1 "$appimagetool" -u "$UPDATE_INFO" " fi chmod 0755 "$output" -# Verify zsync file was created by appimagetool -if [ ! -f "$output.zsync" ]; then - echo "WARNING: zsync file not created by appimagetool, generating with zsyncmake..." >&2 - if ! command -v zsyncmake >/dev/null 2>&1; then - echo "ERROR: zsyncmake not found. Install zsync package." >&2 - exit 1 - fi - zsyncmake -e "$output" -o "$output.zsync" -fi +# Always generate the control file with a public URL. appimagetool may otherwise +# embed the build machine's absolute output path, which clients cannot download. +zsyncmake -e -u "$DOWNLOAD_URL" -o "$output.zsync" "$output" # List files in dist directory for debugging echo "Files in dist directory:" diff --git a/tests/test_mount_status_line.py b/tests/test_mount_status_line.py index b4e15aa..6621e71 100644 --- a/tests/test_mount_status_line.py +++ b/tests/test_mount_status_line.py @@ -26,13 +26,13 @@ def test_combines_mount_point_and_status(self) -> None: from mount_manager_ui import mount_status_line line = mount_status_line(_mount(status="Mounted")) - self.assertEqual(line, "/mnt/mount-manager/share · Mounted") + self.assertEqual(line, "Mounted · /mnt/mount-manager/share") def test_idle_status(self) -> None: from mount_manager_ui import mount_status_line line = mount_status_line(_mount(status="Idle", active=False)) - self.assertEqual(line, "/mnt/mount-manager/share · Idle") + self.assertEqual(line, "Idle · /mnt/mount-manager/share") def test_unmanaged_uses_unmanaged_status(self) -> None: from mount_manager_ui import mount_status_line @@ -44,7 +44,7 @@ def test_unmanaged_uses_unmanaged_status(self) -> None: managed=False, ) ) - self.assertEqual(line, "/mnt/elsewhere · Mounted (not managed)") + self.assertEqual(line, "Mounted (not managed) · /mnt/elsewhere") if __name__ == "__main__":