From c5a9b60fd85ef1e9e6b4d3a2d1d963e5c12970ef Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:42:55 -0500 Subject: [PATCH 01/31] Fit the window to screens too short for it --- maphide/qt/Main.qml | 11 ++++- maphide/qt/Settings.qml | 1 + maphide/qt/app.py | 53 ++++++++++++++++++++++++ tests/test_qt_fit.py | 89 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 152 insertions(+), 2 deletions(-) create mode 100644 tests/test_qt_fit.py diff --git a/maphide/qt/Main.qml b/maphide/qt/Main.qml index 24ec91e..80d7ad9 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -38,8 +38,14 @@ Window { function onWindowPressed(x, y) { win.releaseFieldUnlessAt(x, y) } } + // The height the window is designed for. On a screen too short for it, + // Python lowers fitHeight: the field log and the Settings list take up + // the difference. + readonly property int fullHeight: 748 + property int fitHeight: fullHeight + width: 480 - height: 748 + height: fitHeight minimumWidth: width maximumWidth: width minimumHeight: height @@ -519,8 +525,9 @@ Window { // Field log Rectangle { + objectName: "fieldLog" width: parent.width - height: win.height - y - column.y - 36 + height: Math.max(0,win.height - y - column.y - 36) color: win.t.glass border.color: win.t.border clip: true diff --git a/maphide/qt/Settings.qml b/maphide/qt/Settings.qml index 18df944..bb63f1a 100644 --- a/maphide/qt/Settings.qml +++ b/maphide/qt/Settings.qml @@ -739,6 +739,7 @@ Item { PressButton { id: saveButton + objectName: "saveButton" anchors.right: parent.right anchors.rightMargin: 18 y: 12 diff --git a/maphide/qt/app.py b/maphide/qt/app.py index 7c384f2..e33c1b1 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -14,6 +14,7 @@ QAbstractNativeEventFilter, QEvent, QObject, + QPoint, QTimer, QUrl, Signal, @@ -63,6 +64,56 @@ WM_ENDSESSION = 0x0016 # Fonts the window is drawn in; the self-test checks each one loaded. FONT_FAMILIES = ("Barlow", "Barlow Condensed", "IBM Plex Mono") +# The shortest the window gets on a small screen: everything above the +# field log still shows. +MIN_WINDOW_HEIGHT = 540 +# The title bar and border, when Windows hasn't said yet (the window isn't +# shown). Generous, so a guess never leaves the bottom off-screen. +DEFAULT_FRAME_HEIGHT = 40 + + +def fitted_height(full, available, frame): + """The window's height on a screen with `available` height above the + taskbar, `frame` of it going to the title bar: the full height when it + fits, otherwise what fits, but never below MIN_WINDOW_HEIGHT.""" + return max(MIN_WINDOW_HEIGHT, min(full, available - frame)) + + +def on_screen_top(top, height, area_top, area_height): + """Where a window `height` tall, now at `top`, goes so it's inside the + area: it stays put if it already is. When it can't fit, its title bar + stays visible.""" + lowest = area_top + area_height - height + return max(area_top, min(top, lowest)) + + +def fit_to_screen(window): + """Lower the window's height to what its screen has room for. Call it + before the window is first shown.""" + screen = window.screen() + if screen is None: + return + window.setProperty( + "fitHeight", + fitted_height( + window.property("fullHeight"), + screen.availableGeometry().height(), + DEFAULT_FRAME_HEIGHT, + ), + ) + + +def keep_on_screen(window): + """Move the shown window, title bar included, inside the area above the + taskbar if part of it is off.""" + screen = window.screen() + if screen is None: + return + area = screen.availableGeometry() + frame = window.frameGeometry() + top = on_screen_top(frame.top(), frame.height(), area.top(), area.height()) + if top != frame.top(): + window.setFramePosition(frame.topLeft() + QPoint(0, top - frame.top())) def argb(color, opacity): @@ -682,7 +733,9 @@ def show_window(): backend.notice(NO_TRAY) # Shown only now, so it appears with its theme's title bar already set. paint_title_bar() + fit_to_screen(window) window.show() + keep_on_screen(window) result = app.exec() commands.close() app.removeNativeEventFilter(session_end) diff --git a/tests/test_qt_fit.py b/tests/test_qt_fit.py new file mode 100644 index 0000000..eddf291 --- /dev/null +++ b/tests/test_qt_fit.py @@ -0,0 +1,89 @@ +"""The window fits a screen shorter than it was designed for, such as a +1920x1080 display at 150% scaling, with Save still in reach.""" + +import pytest + +pytest.importorskip("PySide6") + +import PySide6.QtQuick # noqa: E402,F401 +from PySide6.QtCore import QObject, QPointF # noqa: E402 +from PySide6.QtGui import QGuiApplication # noqa: E402 + +from maphide.qt.app import ( # noqa: E402 + MIN_WINDOW_HEIGHT, + Backend, + build_window, + fitted_height, + on_screen_top, +) + +FULL = 748 +TITLE_BAR = 31 +# 1920x1080 at 150%: 720 high in the window's units, minus a 48 taskbar. +LAPTOP_AVAILABLE = 672 + + +def test_a_tall_enough_screen_gets_the_full_height(): + assert fitted_height(FULL, 1032, TITLE_BAR) == FULL + + +def test_a_short_screen_gets_what_fits_under_the_title_bar(): + assert fitted_height(FULL, LAPTOP_AVAILABLE, TITLE_BAR) == LAPTOP_AVAILABLE - TITLE_BAR + + +def test_a_tiny_screen_still_gets_the_minimum(): + assert fitted_height(FULL, 300, TITLE_BAR) == MIN_WINDOW_HEIGHT + + +def test_a_window_already_on_screen_stays_put(): + assert on_screen_top(100, 700, 0, 1032) == 100 + + +def test_a_window_hanging_below_the_taskbar_moves_up(): + assert on_screen_top(100, 672, 0, 672) == 0 + assert on_screen_top(200, 600, 0, 672) == 72 + + +def test_a_window_above_the_screen_moves_down(): + assert on_screen_top(-40, 600, 0, 672) == 0 + + +def test_a_window_taller_than_the_screen_keeps_its_title_bar_visible(): + assert on_screen_top(50, 800, 0, 672) == 0 + + +@pytest.fixture +def window(qt_app): + backend = Backend(update_checks=False, save=lambda cfg: None) + engine, window, warnings = build_window(backend) + assert window is not None, warnings + yield window + window.hide() + del engine + + +def bottom_in_window(item): + return item.mapToScene(QPointF(0, item.height())).y() + + +@pytest.mark.parametrize("height", [LAPTOP_AVAILABLE - TITLE_BAR, MIN_WINDOW_HEIGHT]) +def test_save_stays_inside_a_shorter_window(window, height): + window.setProperty("fitHeight", height) + window.setProperty("drawerOpen", True) + window.show() + QGuiApplication.processEvents() + + assert window.height() == height + save = window.findChild(QObject, "saveButton") + assert bottom_in_window(save) <= height + + +@pytest.mark.parametrize("height", [LAPTOP_AVAILABLE - TITLE_BAR, MIN_WINDOW_HEIGHT]) +def test_the_field_log_shrinks_instead_of_running_off(window, height): + window.setProperty("fitHeight", height) + window.show() + QGuiApplication.processEvents() + + log = window.findChild(QObject, "fieldLog") + assert log.height() >= 0 + assert bottom_in_window(log) <= height From f297d55887dc9062b69de3b0dc722c09e9c9c656 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:53:29 -0500 Subject: [PATCH 02/31] Fit the window reliably, and again when its screen changes --- maphide/qt/Main.qml | 12 +++---- maphide/qt/app.py | 85 +++++++++++++++++++++++++++++++------------- tests/test_qt_fit.py | 35 ++++++++++++++++-- 3 files changed, 99 insertions(+), 33 deletions(-) diff --git a/maphide/qt/Main.qml b/maphide/qt/Main.qml index 80d7ad9..240a0cb 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -38,18 +38,16 @@ Window { function onWindowPressed(x, y) { win.releaseFieldUnlessAt(x, y) } } - // The height the window is designed for. On a screen too short for it, - // Python lowers fitHeight: the field log and the Settings list take up - // the difference. + // The height the window is designed for. Python sets the actual height + // and holds it there (see set_window_height): lower on a screen too + // short for it, with the field log and the Settings list taking up the + // difference. readonly property int fullHeight: 748 - property int fitHeight: fullHeight width: 480 - height: fitHeight + height: fullHeight minimumWidth: width maximumWidth: width - minimumHeight: height - maximumHeight: height // Shown from Python once its title bar matches the theme. visible: false title: "MapHide" diff --git a/maphide/qt/app.py b/maphide/qt/app.py index e33c1b1..d0f099a 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -87,33 +87,68 @@ def on_screen_top(top, height, area_top, area_height): return max(area_top, min(top, lowest)) +def set_window_height(window, height): + """Resize the window to `height` and hold it there, so it can't be + dragged taller or shorter. The hold is loosened first: Windows keeps a + window inside its old limits and would ignore the new height.""" + window.setMinimumHeight(min(height, window.minimumHeight())) + window.setMaximumHeight(max(height, window.maximumHeight())) + window.resize(window.width(), height) + window.setMinimumHeight(height) + window.setMaximumHeight(height) + + def fit_to_screen(window): - """Lower the window's height to what its screen has room for. Call it - before the window is first shown.""" - screen = window.screen() - if screen is None: - return - window.setProperty( - "fitHeight", - fitted_height( - window.property("fullHeight"), - screen.availableGeometry().height(), - DEFAULT_FRAME_HEIGHT, - ), - ) - - -def keep_on_screen(window): - """Move the shown window, title bar included, inside the area above the - taskbar if part of it is off.""" + """Give the window the height its screen has room for, title bar + included, and move it inside the area above the taskbar if part of it + is off. Safe before the window is shown: it then guesses the title bar.""" screen = window.screen() if screen is None: return area = screen.availableGeometry() - frame = window.frameGeometry() - top = on_screen_top(frame.top(), frame.height(), area.top(), area.height()) - if top != frame.top(): - window.setFramePosition(frame.topLeft() + QPoint(0, top - frame.top())) + margins = window.frameMargins() + frame = margins.top() + margins.bottom() + if window.isVisible() and frame > 0: + frame_height = frame + else: + frame_height = DEFAULT_FRAME_HEIGHT + height = fitted_height(window.property("fullHeight"), area.height(), frame_height) + if height != window.height(): + set_window_height(window, height) + if window.isVisible(): + outer = window.frameGeometry() + top = on_screen_top(outer.top(), outer.height(), area.top(), area.height()) + if top != outer.top(): + window.setFramePosition(outer.topLeft() + QPoint(0, top - outer.top())) + + +class ScreenFit(QObject): + """Fits the window to its screen again whenever that changes: moved to + another monitor, a new resolution or scaling, a taller taskbar.""" + + def __init__(self, window): + super().__init__() + self._window = window + self._screen = None + window.screenChanged.connect(self._on_screen_changed) + self._on_screen_changed(window.screen()) + + # Connected as this object's own methods, not lambdas, so Qt stops + # calling them the moment this object is gone. + + def _on_screen_changed(self, screen): + if self._screen is not None and isValid(self._screen): + self._screen.availableGeometryChanged.disconnect(self._on_area_changed) + self._screen = screen + if screen is not None: + screen.availableGeometryChanged.connect(self._on_area_changed) + self.fit() + + def _on_area_changed(self, _area): + self.fit() + + def fit(self): + fit_to_screen(self._window) def argb(color, opacity): @@ -573,6 +608,7 @@ def build_window(backend): window = roots[0] if roots else None if window is not None: window._field_focus = FieldFocus(window, backend.windowPressed.emit) + set_window_height(window, window.property("fullHeight")) return engine, window, warnings @@ -733,9 +769,10 @@ def show_window(): backend.notice(NO_TRAY) # Shown only now, so it appears with its theme's title bar already set. paint_title_bar() - fit_to_screen(window) + screen_fit = ScreenFit(window) window.show() - keep_on_screen(window) + # Again, now that Windows has said how tall the title bar really is. + screen_fit.fit() result = app.exec() commands.close() app.removeNativeEventFilter(session_end) diff --git a/tests/test_qt_fit.py b/tests/test_qt_fit.py index eddf291..1482daa 100644 --- a/tests/test_qt_fit.py +++ b/tests/test_qt_fit.py @@ -10,11 +10,14 @@ from PySide6.QtGui import QGuiApplication # noqa: E402 from maphide.qt.app import ( # noqa: E402 + DEFAULT_FRAME_HEIGHT, MIN_WINDOW_HEIGHT, Backend, + ScreenFit, build_window, fitted_height, on_screen_top, + set_window_height, ) FULL = 748 @@ -66,9 +69,37 @@ def bottom_in_window(item): return item.mapToScene(QPointF(0, item.height())).y() +def test_the_window_starts_at_its_full_height_and_holds_it(window): + assert window.height() == FULL + assert window.minimumHeight() == window.maximumHeight() == FULL + + +def test_a_new_height_takes_even_after_the_native_window_exists(window): + # The app creates the native window early, to colour its title bar. + window.winId() + + set_window_height(window, 600) + assert window.height() == 600 + assert window.minimumHeight() == window.maximumHeight() == 600 + + set_window_height(window, FULL) + assert window.height() == FULL + assert window.minimumHeight() == window.maximumHeight() == FULL + + +def test_the_window_fits_its_screen(window): + window.winId() + available = window.screen().availableGeometry().height() + set_window_height(window, MIN_WINDOW_HEIGHT) + + ScreenFit(window) + + assert window.height() == fitted_height(FULL, available, DEFAULT_FRAME_HEIGHT) + + @pytest.mark.parametrize("height", [LAPTOP_AVAILABLE - TITLE_BAR, MIN_WINDOW_HEIGHT]) def test_save_stays_inside_a_shorter_window(window, height): - window.setProperty("fitHeight", height) + set_window_height(window, height) window.setProperty("drawerOpen", True) window.show() QGuiApplication.processEvents() @@ -80,7 +111,7 @@ def test_save_stays_inside_a_shorter_window(window, height): @pytest.mark.parametrize("height", [LAPTOP_AVAILABLE - TITLE_BAR, MIN_WINDOW_HEIGHT]) def test_the_field_log_shrinks_instead_of_running_off(window, height): - window.setProperty("fitHeight", height) + set_window_height(window, height) window.show() QGuiApplication.processEvents() From 2972659f4a501d69f3cff83d5d4782de1604c503 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:03:02 -0500 Subject: [PATCH 03/31] Send you to the download page when an update can't be installed --- maphide/qt/app.py | 12 +++++++++--- maphide/updates.py | 15 ++++++++------- tests/test_qt_backend.py | 17 +++++++++++++++++ tests/test_updates.py | 17 +++++++++++++++++ 4 files changed, 51 insertions(+), 10 deletions(-) diff --git a/maphide/qt/app.py b/maphide/qt/app.py index d0f099a..e5508ff 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -285,7 +285,13 @@ def _update_view(self): updater = self.updater version = updater.release.version if updater.release else "" # Whole percent, so the window redraws only when the number moves. - return (updater.state, updater.message, version, round(updater.progress * 100)) + return ( + updater.state, + updater.message, + version, + round(updater.progress * 100), + updater.can_install_release, + ) def _settings_view(self): text, warning = source_line(self._source_count()) @@ -516,9 +522,9 @@ def resetDefaults(self): def updatesShown(self): return self._update_checks - @Property(bool, constant=True) + @Property(bool, notify=updateChanged) def canInstallUpdate(self): - return self.updater.can_install + return self._update[4] @Property(str, constant=True) def releasesPage(self): diff --git a/maphide/updates.py b/maphide/updates.py index eaa6d82..c507ddb 100644 --- a/maphide/updates.py +++ b/maphide/updates.py @@ -224,6 +224,13 @@ def __init__( def busy(self): return self.state in (CHECKING, DOWNLOADING, INSTALLING) + @property + def can_install_release(self): + """Whether the release found can be installed from here: this copy + was installed by the setup file, and the release has one MapHide + can use. If not, the window sends you to the download page.""" + return self.can_install and self.release is not None and self.release.setup_url is not None + def _set(self, state, message=""): self.state = state self.message = message @@ -288,13 +295,7 @@ def install(self, on_started): `on_started()`, which should close MapHide. Returns False if there is nothing to install or this copy can't install it.""" release = self.release - if ( - self.busy - or self.state not in (AVAILABLE, FAILED) - or release is None - or release.setup_url is None - or not self.can_install - ): + if self.busy or self.state not in (AVAILABLE, FAILED) or not self.can_install_release: return False def report(fraction): diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index ac1e011..e85c070 100644 --- a/tests/test_qt_backend.py +++ b/tests/test_qt_backend.py @@ -408,6 +408,23 @@ def test_check_now_says_when_maphide_is_up_to_date(h): assert h.backend.updateState == "latest" +def test_an_installed_copy_offers_to_install_a_release_with_a_setup_file(h): + h.latest = NEW_RELEASE + h.backend.checkForUpdates() + h.run_updater() + + assert h.backend.canInstallUpdate is True + + +def test_a_release_without_a_setup_file_sends_you_to_the_download_page(h): + h.latest = Release("0.3.0") + h.backend.checkForUpdates() + h.run_updater() + + assert h.backend.updateState == "available" + assert h.backend.canInstallUpdate is False + + def test_update_runs_the_installer_and_closes_maphide(h): h.latest = NEW_RELEASE h.backend.checkForUpdates() diff --git a/tests/test_updates.py b/tests/test_updates.py index 8bb318f..b611ecc 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -400,6 +400,23 @@ def test_nothing_is_installed_when_it_cant_be(steps): assert s.downloads == [] +@pytest.mark.parametrize( + ("steps", "installable"), + [ + (lambda: Steps(), True), + (lambda: Steps(can_install=False), False), + (lambda: Steps(release=Release("0.3.0")), False), + ], + ids=["installed copy", "unzipped copy", "no setup file"], +) +def test_a_found_release_says_whether_it_can_be_installed(steps, installable): + s = steps() + s.updater.check() + s.finish() + + assert s.updater.can_install_release is installable + + def test_nothing_is_installed_before_a_check_finds_something(): s = Steps() From 749aa45f785cf6073b2e647f1bd8b56f0f07d383 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:08:07 -0500 Subject: [PATCH 04/31] Check HTTPS support and the window icon in the self-test --- maphide/qt/app.py | 20 ++++++++++++++++++++ tests/test_selftest.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 tests/test_selftest.py diff --git a/maphide/qt/app.py b/maphide/qt/app.py index e5508ff..8bddd8c 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -789,6 +789,25 @@ def show_window(): return result +def bundle_problems(icon_path=ICON_ICO_PATH): + """Pieces the app needs that opening the window doesn't prove are there: + HTTPS, which the update check uses, and the window icon. Without HTTPS + every check would just say GitHub can't be reached. Needs a running + QApplication. Returns what's wrong, empty when nothing is.""" + problems = [] + try: + # Imported here: a missing piece should fail this check, not stop + # MapHide from opening. + import ssl + + ssl.create_default_context() + except Exception: + problems.append("HTTPS support did not load, so update checks would fail") + if QIcon(str(icon_path)).pixmap(32, 32).isNull(): + problems.append("the window icon did not load") + return problems + + def selftest(): """Build the window without showing it, and check that it loaded with its map image and fonts. Returns an exit code: 0 when all is well. The @@ -809,6 +828,7 @@ def selftest(): missing_fonts = set(FONT_FAMILIES) - set(QFontDatabase.families()) if missing_fonts: problems.append(f"fonts not loaded: {', '.join(sorted(missing_fonts))}") + problems.extend(bundle_problems()) for problem in problems: print(problem, file=sys.stderr) del engine diff --git a/tests/test_selftest.py b/tests/test_selftest.py new file mode 100644 index 0000000..ea1f048 --- /dev/null +++ b/tests/test_selftest.py @@ -0,0 +1,28 @@ +"""The build check notices when a piece the app needs at runtime, but not +to open its window, is missing: HTTPS for the update check, and the +window icon.""" + +import ssl + +import pytest + +pytest.importorskip("PySide6") + +from maphide.qt.app import bundle_problems # noqa: E402 + + +def test_a_complete_bundle_has_no_problems(qt_app): + assert bundle_problems() == [] + + +def test_missing_https_support_is_reported(qt_app, monkeypatch): + def broken(): + raise ssl.SSLError("no certificates") + + monkeypatch.setattr(ssl, "create_default_context", broken) + + assert bundle_problems() == ["HTTPS support did not load, so update checks would fail"] + + +def test_a_missing_icon_is_reported(qt_app, tmp_path): + assert bundle_problems(icon_path=tmp_path / "missing.ico") == ["the window icon did not load"] From 3515bc1de537a7ef9d794a54276d4611e5da70d6 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:15:25 -0500 Subject: [PATCH 05/31] Save settings safely, and only when they changed on Start --- CHANGELOG.md | 3 +++ maphide/config.py | 18 +++++++++++---- maphide/controller.py | 22 ++++++++++++++----- tests/test_config.py | 30 +++++++++++++++++++++++++ tests/test_controller.py | 47 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 110 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 659fb2d..1b0d67e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,9 @@ All notable changes to MapHide are documented here. - Added a Check for updates switch under Behavior in Settings, on by default, which looks for a new version when MapHide opens. The field log says when one is out. +- Fixed your settings being lost if the PC crashed or lost power while + MapHide was saving them. Start also no longer saves settings that haven't + changed. ## v0.2.6 - 2026-10-27 diff --git a/maphide/config.py b/maphide/config.py index c198d69..b0fb25e 100644 --- a/maphide/config.py +++ b/maphide/config.py @@ -1,6 +1,7 @@ """The settings file: its shape, and reading and writing it.""" import json +import os import shutil from dataclasses import dataclass, replace @@ -242,8 +243,7 @@ def ensure_config_file(path=CONFIG_PATH): if LEGACY_CONFIG_PATH.exists() and LEGACY_CONFIG_PATH.resolve() != path.resolve(): shutil.copy2(LEGACY_CONFIG_PATH, path) return - with open(path, "w", encoding="utf-8") as file: - json.dump(default_config().to_dict(), file, indent=2) + save_config(default_config(), path) def load_config(path=CONFIG_PATH): @@ -253,6 +253,16 @@ def load_config(path=CONFIG_PATH): def save_config(cfg, path=CONFIG_PATH): + """Write `cfg` to a temporary file next to `path`, then swap it in, so a + crash or power cut mid-save leaves the old settings, never half a file.""" path.parent.mkdir(parents=True, exist_ok=True) - with open(path, "w", encoding="utf-8") as file: - json.dump(cfg.to_dict(), file, indent=2) + temporary = path.with_name(path.name + ".tmp") + try: + with open(temporary, "w", encoding="utf-8") as file: + json.dump(cfg.to_dict(), file, indent=2) + file.flush() + os.fsync(file.fileno()) + os.replace(temporary, path) + except BaseException: + temporary.unlink(missing_ok=True) + raise diff --git a/maphide/controller.py b/maphide/controller.py index c295be1..83c050a 100644 --- a/maphide/controller.py +++ b/maphide/controller.py @@ -86,6 +86,9 @@ def __init__( self._notify = notify self._on_change = on_change self.running_config = default_config() + # What the settings file holds, as last read or written; None when + # that isn't known, as when the file couldn't be read. + self._saved_config = None # The settings the running worker was started with, or None. self._worker_config = None self.restart_pending = False @@ -171,22 +174,24 @@ def load(self, load=load_config): try: cfg = load() loaded = True + self._saved_config = cfg except (OSError, ValueError, KeyError): cfg = default_config() loaded = False + self._saved_config = None self.running_config = form_ready(cfg) return self.running_config, loaded def save(self, cfg): """Save `cfg` and put it into effect. Raises OSError if it can't be written, in which case nothing changes.""" - self._save(cfg) + self._write(cfg) self._apply(cfg, "Config saved.", HISTORY_SETTINGS_SAVED) def restore_defaults(self): """Save and apply the default settings, and return them.""" cfg = default_config() - self._save(cfg) + self._write(cfg) self._apply(cfg, "Defaults restored.", HISTORY_DEFAULTS_RESTORED) return cfg @@ -207,11 +212,16 @@ def _worker_needs(self, cfg): # The worker. - def start(self, cfg): - """Save `cfg` and start the worker with it. Raises OSError if the - settings can't be saved, RuntimeError if the worker is already - running.""" + def _write(self, cfg): self._save(cfg) + self._saved_config = cfg + + def start(self, cfg): + """Save `cfg`, unless the file already holds it, and start the + worker with it. Raises OSError if the settings can't be saved, + RuntimeError if the worker is already running.""" + if cfg != self._saved_config: + self._write(cfg) self.service.start(cfg) self._worker_config = cfg self.running_config = cfg diff --git a/tests/test_config.py b/tests/test_config.py index c4e739c..7665623 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -4,6 +4,7 @@ import pytest +from maphide import config as config_module from maphide.config import ( DEFAULT_HIDE_DELAY_MS, MAX_HIDE_DELAY_MS, @@ -133,6 +134,35 @@ def test_save_then_load_round_trips(tmp_path): assert load_config(path) == cfg +def test_a_save_cut_short_leaves_the_old_settings_intact(tmp_path, monkeypatch): + path = tmp_path / "config.json" + old = AppConfig.from_dict({**default_config().to_dict(), "host": "10.0.0.5"}) + save_config(old, path) + + def dump_then_fail(data, file, **_options): + file.write('{"host": "10.0.') + raise OSError("disk full") + + monkeypatch.setattr(config_module.json, "dump", dump_then_fail) + new = AppConfig.from_dict({**default_config().to_dict(), "host": "192.168.1.9"}) + + with pytest.raises(OSError): + save_config(new, path) + monkeypatch.undo() + + assert load_config(path) == old + assert [p.name for p in tmp_path.iterdir()] == ["config.json"] + + +def test_a_save_leaves_no_temporary_file_behind(tmp_path): + path = tmp_path / "config.json" + + save_config(default_config(), path) + save_config(default_config(), path) + + assert [p.name for p in tmp_path.iterdir()] == ["config.json"] + + def test_hand_edited_delay_is_sanitised_on_load(tmp_path): path = tmp_path / "config.json" path.write_text(json.dumps({**BASE, "hide_delay_ms": 99_999}), encoding="utf-8") diff --git a/tests/test_controller.py b/tests/test_controller.py index 4423435..9b0c3a9 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -165,6 +165,53 @@ def test_start_saves_the_settings_then_starts_the_worker_with_them(h): assert (h.controller.can_start, h.controller.can_stop) == (False, True) +def test_start_with_the_settings_just_loaded_does_not_save_them_again(h): + cfg, _ = h.controller.load(load=lambda: make_config(hotkey="M")) + + h.controller.start(cfg) + + assert h.saved == [] + assert h.service.started_with == [cfg] + + +def test_start_with_changed_settings_saves_them(h): + h.controller.load(load=lambda: make_config(hotkey="M")) + changed = make_config(hotkey="K") + + h.controller.start(changed) + + assert h.saved == [changed] + + +def test_start_after_a_save_does_not_save_the_same_settings_again(h): + cfg = make_config(hotkey="K") + h.controller.save(cfg) + h.saved.clear() + + h.controller.start(cfg) + + assert h.saved == [] + + +def test_start_saves_when_the_file_could_not_be_read(h): + def failing_load(): + raise ValueError("bad") + + cfg, _ = h.controller.load(load=failing_load) + + h.controller.start(cfg) + + assert h.saved == [cfg] + + +def test_start_saves_values_loading_had_to_replace(h): + cfg, _ = h.controller.load(load=lambda: make_config(hotkey="?")) + + h.controller.start(cfg) + + assert h.saved == [cfg] + + def test_start_does_not_run_the_worker_when_saving_fails(h): def failing_save(_cfg): raise OSError("denied") From 39b4cb24262b150091f8ef1cfdc5673d95ac2714 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:47:06 -0500 Subject: [PATCH 06/31] Say in the field log when Start saves your settings --- CHANGELOG.md | 2 ++ maphide/controller.py | 6 ++++-- tests/test_controller.py | 11 ++++++++++- tests/test_qt_backend.py | 19 +++++++++++++++++++ 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b0d67e..813ef9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,8 @@ All notable changes to MapHide are documented here. - Fixed your settings being lost if the PC crashed or lost power while MapHide was saving them. Start also no longer saves settings that haven't changed. +- Changed Start to say in the field log when it saves changes you made in + Settings without pressing Save. ## v0.2.6 - 2026-10-27 diff --git a/maphide/controller.py b/maphide/controller.py index 83c050a..6d92d59 100644 --- a/maphide/controller.py +++ b/maphide/controller.py @@ -218,10 +218,12 @@ def _write(self, cfg): def start(self, cfg): """Save `cfg`, unless the file already holds it, and start the - worker with it. Raises OSError if the settings can't be saved, - RuntimeError if the worker is already running.""" + worker with it. A save shows in the field log, as Save's does. + Raises OSError if the settings can't be saved, RuntimeError if the + worker is already running.""" if cfg != self._saved_config: self._write(cfg) + self.add_history(human_ts(), "Config saved.", HISTORY_SETTINGS_SAVED) self.service.start(cfg) self._worker_config = cfg self.running_config = cfg diff --git a/tests/test_controller.py b/tests/test_controller.py index 9b0c3a9..f7acdbc 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -174,13 +174,22 @@ def test_start_with_the_settings_just_loaded_does_not_save_them_again(h): assert h.service.started_with == [cfg] -def test_start_with_changed_settings_saves_them(h): +def test_start_with_changed_settings_saves_them_and_says_so(h): h.controller.load(load=lambda: make_config(hotkey="M")) changed = make_config(hotkey="K") h.controller.start(changed) assert h.saved == [changed] + assert [entry.code for entry in h.controller.history] == [HISTORY_SETTINGS_SAVED] + + +def test_start_that_saves_nothing_says_nothing_about_saving(h): + cfg, _ = h.controller.load(load=lambda: make_config(hotkey="M")) + + h.controller.start(cfg) + + assert h.controller.history == [] def test_start_after_a_save_does_not_save_the_same_settings_again(h): diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index e85c070..d871a92 100644 --- a/tests/test_qt_backend.py +++ b/tests/test_qt_backend.py @@ -225,6 +225,25 @@ def test_start_runs_the_worker_with_the_form(h): assert h.backend.primaryIsStop +def test_start_with_unsaved_changes_says_it_saved_them(h): + fill_form(h.backend, hotkey="M") + + h.backend.primary() + + assert h.saved[-1].hotkey == "M" + assert "> settings saved" in [line[1] for line in h.lines] + + +def test_start_with_nothing_changed_says_nothing_about_saving(h): + fill_form(h.backend) + h.backend.save() + h.lines.clear() + + h.backend.primary() + + assert "> settings saved" not in [line[1] for line in h.lines] + + def test_stop_stops_the_worker(h): fill_form(h.backend) h.backend.primary() From 8963d99ef2c3a455f31a189fedc3ca55e840f3df Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:00:13 -0500 Subject: [PATCH 07/31] Stop instead of reconnecting when defaults are restored while running --- CHANGELOG.md | 2 ++ maphide/controller.py | 21 ++++++++++++++++++--- tests/test_controller.py | 27 +++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 813ef9a..fa1388a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,8 @@ All notable changes to MapHide are documented here. changed. - Changed Start to say in the field log when it saves changes you made in Settings without pressing Save. +- Fixed Reset in Settings, while MapHide was running, trying to connect with + empty settings and ending on a connection error. Reset now stops MapHide. ## v0.2.6 - 2026-10-27 diff --git a/maphide/controller.py b/maphide/controller.py index 6d92d59..1df48c9 100644 --- a/maphide/controller.py +++ b/maphide/controller.py @@ -189,17 +189,28 @@ def save(self, cfg): self._apply(cfg, "Config saved.", HISTORY_SETTINGS_SAVED) def restore_defaults(self): - """Save and apply the default settings, and return them.""" + """Save the default settings, and return them. A running worker is + stopped, not restarted: the defaults have no OBS address to connect + to.""" cfg = default_config() self._write(cfg) - self._apply(cfg, "Defaults restored.", HISTORY_DEFAULTS_RESTORED) + self._record(cfg, "Defaults restored.", HISTORY_DEFAULTS_RESTORED) + if self.restart_pending: + # The restart under way finishes stopping, then starts nothing. + self._pending_restart_config = None + elif self.service.is_running: + self.service.stop() + self._on_change() return cfg - def _apply(self, cfg, done_message, code): + def _record(self, cfg, done_message, code): self.running_config = cfg # The history, not the live status line: a save confirmation isn't # part of the OBS connection's own story. self.add_history(human_ts(), done_message, code) + + def _apply(self, cfg, done_message, code): + self._record(cfg, done_message, code) # Only restart for a change the worker would actually see: a restart # briefly drops the OBS link and hides the overlay. A restart already # under way always takes the newest settings. @@ -254,6 +265,10 @@ def _finish_restart(self): # MapHide is closing: a new worker would outlive the exit's own # wait and be cut off without hiding the overlay. return + if cfg is None: + # Restore defaults called the restart off. + self._on_change() + return try: self.service.start(cfg) self._worker_config = cfg diff --git a/tests/test_controller.py b/tests/test_controller.py index f7acdbc..74fdbf7 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -319,6 +319,33 @@ def test_a_restart_waits_as_long_as_the_old_worker_needs(h): assert len(h.schedule.pending) == 1 +def test_restoring_defaults_while_running_stops_and_stays_stopped(h): + h.controller.start(make_config()) + + h.controller.restore_defaults() + assert h.service.stop_requests == 1 + h.service.finish_stopping() + while h.schedule.pending: + h.schedule.run_next() + + assert h.service.started_with == [make_config()] + assert h.controller.can_start is True + + +def test_restoring_defaults_during_a_restart_cancels_it(h): + h.controller.start(make_config()) + h.controller.save(make_config(hotkey="M")) + + h.controller.restore_defaults() + h.service.finish_stopping() + while h.schedule.pending: + h.schedule.run_next() + + assert h.service.started_with == [make_config()] + assert h.controller.restart_pending is False + assert h.controller.can_start is True + + def test_a_restart_that_cannot_start_the_new_worker_says_so(h): h.controller.start(make_config()) h.controller.save(make_config(hotkey="M")) From 2358b4335aa386231aca58623028f00d414de6ac Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:18:28 -0500 Subject: [PATCH 08/31] Keep Settings changes only on Save, and show when some are unsaved --- CHANGELOG.md | 9 +-- maphide/controller.py | 23 ++----- maphide/qt/Main.qml | 5 ++ maphide/qt/Settings.qml | 14 +++- maphide/qt/app.py | 29 +++++++- tests/test_controller.py | 64 +++--------------- tests/test_qt_backend.py | 100 +++++++++++++++++++++++----- tests/test_qt_drawer.py | 140 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 288 insertions(+), 96 deletions(-) create mode 100644 tests/test_qt_drawer.py diff --git a/CHANGELOG.md b/CHANGELOG.md index fa1388a..05a9655 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,12 +48,13 @@ All notable changes to MapHide are documented here. which looks for a new version when MapHide opens. The field log says when one is out. - Fixed your settings being lost if the PC crashed or lost power while - MapHide was saving them. Start also no longer saves settings that haven't - changed. -- Changed Start to say in the field log when it saves changes you made in - Settings without pressing Save. + MapHide was saving them. - Fixed Reset in Settings, while MapHide was running, trying to connect with empty settings and ending on a connection error. Reset now stops MapHide. +- Changed Settings so only Save keeps a change: closing Settings without + Save puts your saved settings back, and Start uses your saved settings + instead of saving what's in Settings. Settings shows Unsaved changes while + you have any. ## v0.2.6 - 2026-10-27 diff --git a/maphide/controller.py b/maphide/controller.py index 1df48c9..8d380b0 100644 --- a/maphide/controller.py +++ b/maphide/controller.py @@ -86,9 +86,6 @@ def __init__( self._notify = notify self._on_change = on_change self.running_config = default_config() - # What the settings file holds, as last read or written; None when - # that isn't known, as when the file couldn't be read. - self._saved_config = None # The settings the running worker was started with, or None. self._worker_config = None self.restart_pending = False @@ -174,18 +171,16 @@ def load(self, load=load_config): try: cfg = load() loaded = True - self._saved_config = cfg except (OSError, ValueError, KeyError): cfg = default_config() loaded = False - self._saved_config = None self.running_config = form_ready(cfg) return self.running_config, loaded def save(self, cfg): """Save `cfg` and put it into effect. Raises OSError if it can't be written, in which case nothing changes.""" - self._write(cfg) + self._save(cfg) self._apply(cfg, "Config saved.", HISTORY_SETTINGS_SAVED) def restore_defaults(self): @@ -193,7 +188,7 @@ def restore_defaults(self): stopped, not restarted: the defaults have no OBS address to connect to.""" cfg = default_config() - self._write(cfg) + self._save(cfg) self._record(cfg, "Defaults restored.", HISTORY_DEFAULTS_RESTORED) if self.restart_pending: # The restart under way finishes stopping, then starts nothing. @@ -223,18 +218,10 @@ def _worker_needs(self, cfg): # The worker. - def _write(self, cfg): - self._save(cfg) - self._saved_config = cfg - def start(self, cfg): - """Save `cfg`, unless the file already holds it, and start the - worker with it. A save shows in the field log, as Save's does. - Raises OSError if the settings can't be saved, RuntimeError if the - worker is already running.""" - if cfg != self._saved_config: - self._write(cfg) - self.add_history(human_ts(), "Config saved.", HISTORY_SETTINGS_SAVED) + """Start the worker with `cfg`, the saved settings. Start never + saves: only Save does. Raises RuntimeError if the worker is already + running.""" self.service.start(cfg) self._worker_config = cfg self.running_config = cfg diff --git a/maphide/qt/Main.qml b/maphide/qt/Main.qml index 240a0cb..ba204f6 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -11,9 +11,12 @@ Window { readonly property color coverRed: "#d9483b" readonly property color coverRedText: "#ff7a6b" property bool drawerOpen: false + // Closing Settings without Save puts the saved settings back: only Save + // keeps a change. onDrawerOpenChanged: if (!drawerOpen) { settings.stopCapture() releaseKeyboard() + backend.discardChanges() } onVisibleChanged: if (!visible) releaseKeyboard() @@ -625,6 +628,7 @@ Window { // Settings drawer: slides in over the main screen. Rectangle { id: drawer + objectName: "drawer" width: 436 height: parent.height // How far open, from 0 (hidden) to 1. The slide animates this, @@ -640,6 +644,7 @@ Window { Settings { id: settings + objectName: "settings" anchors.fill: parent anchors.leftMargin: 1 onCloseRequested: win.drawerOpen = false diff --git a/maphide/qt/Settings.qml b/maphide/qt/Settings.qml index bb63f1a..ffa3e4c 100644 --- a/maphide/qt/Settings.qml +++ b/maphide/qt/Settings.qml @@ -2,7 +2,8 @@ import QtQuick import QtQuick.Shapes // The settings drawer's contents: numbered sections, then Reset and -// Save. Edits stay in the form, unapplied, until Save. +// Save. Edits stay in the form, unapplied, until Save; closing the drawer +// without Save puts the saved settings back (see Main.qml). Item { id: settings @@ -702,6 +703,17 @@ Item { font.pixelSize: 12 color: settings.t.warn } + // Closing Settings without Save puts the saved settings back. + Label { + objectName: "unsavedNote" + anchors.fill: parent + visible: backend.hasUnsavedChanges && settings.footerProblem === "" && !settings.savedStamp + text: "Unsaved changes" + verticalAlignment: Text.AlignVCenter + horizontalAlignment: Text.AlignHCenter + font.pixelSize: 12 + color: settings.t.warn + } Rectangle { id: stamp anchors.centerIn: parent diff --git a/maphide/qt/app.py b/maphide/qt/app.py index 8bddd8c..a9034f9 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -365,8 +365,11 @@ def assets(self): # What the user does. def _start(self): + # The saved settings, never the form: Start doesn't pick up, or + # save, changes Save hasn't kept. Checked as the form would be, so a + # missing host gets the same message. try: - self.controller.start(config_from_form(**self._form)) + self.controller.start(config_from_form(**form_values(self.controller.running_config))) except ValueError as exc: self.notice(str(exc)) except OSError as exc: @@ -419,6 +422,28 @@ def end_session(self, wait_seconds=SESSION_END_WAIT_SECONDS): def form(self): return self._form + @Property(bool, notify=formChanged) + def hasUnsavedChanges(self): + """Whether the form holds anything Save hasn't kept. Spaces around a + value don't count: Save would drop them.""" + saved = self.controller.running_config + if self._form == form_values(saved): + return False + try: + return config_from_form(**self._form) != saved + except ValueError: + # Half-typed, so it can't be what's saved. + return True + + @Slot() + def discardChanges(self): + """Settings closed without Save: put the saved settings back, theme + included.""" + if self._form != form_values(self.controller.running_config): + self._set_form(self.controller.running_config) + self.clearTest() + self.refresh() + @Slot(str, "QVariant") def setField(self, name, value): if name not in FORM_FIELDS: @@ -504,6 +529,8 @@ def save(self): except OSError as exc: self.saveFailed.emit(f"Couldn't save settings: {plain_reason(exc)}") return + # The form now shows exactly what was saved (spaces trimmed, say). + self._set_form(self.controller.running_config) self.saved.emit() @Slot() diff --git a/tests/test_controller.py b/tests/test_controller.py index 74fdbf7..3b154e5 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -155,81 +155,33 @@ def test_loading_replaces_values_the_form_cannot_show(h): # Starting and stopping. -def test_start_saves_the_settings_then_starts_the_worker_with_them(h): +def test_start_runs_the_worker_with_the_settings(h): cfg = make_config() h.controller.start(cfg) - assert h.saved == [cfg] assert h.service.started_with == [cfg] assert (h.controller.can_start, h.controller.can_stop) == (False, True) -def test_start_with_the_settings_just_loaded_does_not_save_them_again(h): - cfg, _ = h.controller.load(load=lambda: make_config(hotkey="M")) - - h.controller.start(cfg) - - assert h.saved == [] - assert h.service.started_with == [cfg] - - -def test_start_with_changed_settings_saves_them_and_says_so(h): +def test_start_never_saves(h): h.controller.load(load=lambda: make_config(hotkey="M")) - changed = make_config(hotkey="K") - - h.controller.start(changed) - - assert h.saved == [changed] - assert [entry.code for entry in h.controller.history] == [HISTORY_SETTINGS_SAVED] - -def test_start_that_saves_nothing_says_nothing_about_saving(h): - cfg, _ = h.controller.load(load=lambda: make_config(hotkey="M")) - - h.controller.start(cfg) - - assert h.controller.history == [] - - -def test_start_after_a_save_does_not_save_the_same_settings_again(h): - cfg = make_config(hotkey="K") - h.controller.save(cfg) - h.saved.clear() - - h.controller.start(cfg) + h.controller.start(make_config(hotkey="K")) assert h.saved == [] + assert h.controller.history == [] -def test_start_saves_when_the_file_could_not_be_read(h): - def failing_load(): - raise ValueError("bad") - - cfg, _ = h.controller.load(load=failing_load) - - h.controller.start(cfg) - - assert h.saved == [cfg] - - -def test_start_saves_values_loading_had_to_replace(h): - cfg, _ = h.controller.load(load=lambda: make_config(hotkey="?")) - - h.controller.start(cfg) - - assert h.saved == [cfg] - - -def test_start_does_not_run_the_worker_when_saving_fails(h): +def test_start_works_when_the_settings_file_cant_be_written(h): def failing_save(_cfg): raise OSError("denied") controller = AppController(schedule=h.schedule, service=h.service, save=failing_save) - with pytest.raises(OSError): - controller.start(make_config()) - assert h.service.started_with == [] + controller.start(make_config()) + + assert h.service.started_with == [make_config()] def test_stop_asks_the_worker_to_stop(h): diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index d871a92..203a57f 100644 --- a/tests/test_qt_backend.py +++ b/tests/test_qt_backend.py @@ -107,6 +107,12 @@ def fill_form(backend, **values): backend.setField(name, value) +def save_form(backend, **values): + """Fill the form and press Save: Start runs the saved settings.""" + fill_form(backend, **values) + backend.save() + + def test_loading_fills_the_form_from_the_saved_settings(h): h.load(lambda: make_config(host="10.0.0.9", port=4456)) @@ -208,7 +214,7 @@ def test_reset_puts_the_defaults_back_in_the_form(h): # Start, stop and the test button. -def test_start_with_a_form_that_isnt_ready_says_why_in_the_field_log(h): +def test_start_with_saved_settings_that_arent_ready_says_why_in_the_field_log(h): h.backend.primary() assert h.service.started_with == [] @@ -216,8 +222,8 @@ def test_start_with_a_form_that_isnt_ready_says_why_in_the_field_log(h): assert h.backend.controller.history[-1].code == HISTORY_NOTICE -def test_start_runs_the_worker_with_the_form(h): - fill_form(h.backend, hotkey="M") +def test_start_runs_the_worker_with_the_saved_settings(h): + save_form(h.backend, hotkey="M") h.backend.primary() @@ -225,27 +231,89 @@ def test_start_runs_the_worker_with_the_form(h): assert h.backend.primaryIsStop -def test_start_with_unsaved_changes_says_it_saved_them(h): - fill_form(h.backend, hotkey="M") +def test_start_ignores_and_never_saves_unsaved_changes(h): + save_form(h.backend, hotkey="M") + h.saved.clear() + h.backend.setField("hotkey", "K") h.backend.primary() - assert h.saved[-1].hotkey == "M" - assert "> settings saved" in [line[1] for line in h.lines] + assert h.service.started_with[-1].hotkey == "M" + assert h.saved == [] -def test_start_with_nothing_changed_says_nothing_about_saving(h): - fill_form(h.backend) +# Unsaved changes. + + +def test_closing_settings_puts_the_saved_settings_back(h): + save_form(h.backend, hotkey="M") + h.backend.setField("host", "192.168.1.50") + h.backend.setField("hotkey", "K") + + h.backend.discardChanges() + + assert h.backend.form["host"] == "10.0.0.2" + assert h.backend.form["hotkey"] == "M" + assert h.backend.hasUnsavedChanges is False + + +def test_closing_settings_puts_the_saved_theme_back(h): + save_form(h.backend, theme="field") + h.backend.setField("theme", "legacy") + assert h.backend.themeName == "legacy" + + h.backend.discardChanges() + + assert h.backend.themeName == "field" + + +def test_a_change_counts_as_unsaved_until_saved(h): + save_form(h.backend) + assert h.backend.hasUnsavedChanges is False + + h.backend.setField("hide_delay_ms", 650) + assert h.backend.hasUnsavedChanges is True + h.backend.save() - h.lines.clear() + assert h.backend.hasUnsavedChanges is False - h.backend.primary() - assert "> settings saved" not in [line[1] for line in h.lines] +def test_changing_a_field_back_is_not_an_unsaved_change(h): + save_form(h.backend) + + h.backend.setField("host", "192.168.1.50") + h.backend.setField("host", "10.0.0.2") + + assert h.backend.hasUnsavedChanges is False + + +def test_spaces_around_a_value_are_not_an_unsaved_change(h): + save_form(h.backend) + + h.backend.setField("host", " 10.0.0.2 ") + + assert h.backend.hasUnsavedChanges is False + + +def test_a_captured_key_is_an_unsaved_change(h): + save_form(h.backend) + + h.backend.captureKey("show", ord("K"), False) + + assert h.backend.hasUnsavedChanges is True + + +def test_reset_leaves_nothing_unsaved(h): + save_form(h.backend) + h.backend.setField("host", "192.168.1.50") + + h.backend.resetDefaults() + + assert h.backend.hasUnsavedChanges is False def test_stop_stops_the_worker(h): - fill_form(h.backend) + save_form(h.backend) h.backend.primary() h.backend.primary() @@ -261,7 +329,7 @@ def test_the_test_button_presses_and_releases(h): def test_a_settings_change_while_running_reads_as_connecting(h): - fill_form(h.backend) + save_form(h.backend) h.backend.primary() h.service.status = ServiceStatus(CONNECTED, "Connected to OBS.") @@ -321,7 +389,7 @@ def test_a_renamed_source_forgets_the_old_scene_count(h): def test_closing_hides_the_window_and_quits_once_the_worker_is_done(h): - fill_form(h.backend) + save_form(h.backend) h.backend.primary() h.backend.requestClose() @@ -363,7 +431,7 @@ def test_exit_from_the_tray_quits(h): def test_a_session_end_stops_the_worker_and_waits_for_it_here(h): - fill_form(h.backend) + save_form(h.backend) h.backend.primary() h.backend.end_session(wait_seconds=3) diff --git a/tests/test_qt_drawer.py b/tests/test_qt_drawer.py new file mode 100644 index 0000000..c71c244 --- /dev/null +++ b/tests/test_qt_drawer.py @@ -0,0 +1,140 @@ +"""Settings in the real window: closing it without Save puts back what's +saved, in the fields you see as well as underneath, and the footer says +when there are changes Save hasn't kept.""" + +import time + +import pytest + +pytest.importorskip("PySide6") + +import PySide6.QtQuick # noqa: E402,F401 +from PySide6.QtCore import QEvent, QObject, Qt # noqa: E402 +from PySide6.QtGui import QGuiApplication, QKeyEvent # noqa: E402 + +from maphide.qt.app import Backend, build_window # noqa: E402 + +SAVED = {"host": "10.0.0.2", "port": "4455", "scene_item_name": "Overlay"} + + +@pytest.fixture +def setup(qt_app): + saved = [] + backend = Backend(update_checks=False, save=saved.append) + engine, window, warnings = build_window(backend) + assert window is not None, warnings + for name, value in SAVED.items(): + backend.setField(name, value) + backend.save() + # As if the SAVED stamp's two seconds were up. + window.findChild(QObject, "settings").setProperty("savedStamp", False) + window.show() + open_settings(window) + yield backend, window + window.hide() + del engine + + +def text_inputs(window): + found, pending = [], [window.contentItem()] + while pending: + item = pending.pop(0) + if item.inherits("QQuickTextInput"): + found.append(item) + pending.extend(item.childItems()) + return found + + +def type_into(window, field, text): + field.forceActiveFocus() + for char in text: + for kind in (QEvent.Type.KeyPress, QEvent.Type.KeyRelease): + QGuiApplication.sendEvent( + window, QKeyEvent(kind, 0, Qt.KeyboardModifier.NoModifier, char) + ) + QGuiApplication.processEvents() + + +def host_field(window): + return next(f for f in text_inputs(window) if f.property("text") == SAVED["host"]) + + +def open_settings(window): + """Open the drawer and wait for it to finish sliding in: until then it + counts as hidden, and so does everything in it.""" + window.setProperty("drawerOpen", True) + drawer = window.findChild(QObject, "drawer") + deadline = time.monotonic() + 3 + while drawer.property("openness") < 1 and time.monotonic() < deadline: + QGuiApplication.processEvents() + time.sleep(0.01) + assert drawer.property("openness") == 1 + + +def close_settings(window): + window.setProperty("drawerOpen", False) + QGuiApplication.processEvents() + + +def test_typing_in_a_field_changes_the_form(setup): + backend, window = setup + + type_into(window, host_field(window), "9") + + assert backend.form["host"] == "10.0.0.29" + + +def test_closing_settings_puts_the_typed_field_back(setup): + backend, window = setup + field = host_field(window) + type_into(window, field, "9") + + close_settings(window) + + assert backend.form["host"] == SAVED["host"] + assert field.property("text") == SAVED["host"] + + +def test_reset_shows_the_defaults_in_a_typed_field(setup): + backend, window = setup + field = host_field(window) + type_into(window, field, "9") + + backend.resetDefaults() + QGuiApplication.processEvents() + + assert field.property("text") == "" + + +def unsaved_note(window): + return window.findChild(QObject, "unsavedNote") + + +def test_the_footer_says_when_changes_are_unsaved(setup): + backend, window = setup + assert not unsaved_note(window).property("visible") + + type_into(window, host_field(window), "9") + + assert unsaved_note(window).property("visible") + + +def test_the_saved_stamp_shows_instead_of_the_note(setup): + backend, window = setup + type_into(window, host_field(window), "9") + + backend.save() + QGuiApplication.processEvents() + + assert not unsaved_note(window).property("visible") + + +def test_the_unsaved_note_goes_once_settings_close(setup): + backend, window = setup + type_into(window, host_field(window), "9") + + close_settings(window) + open_settings(window) + + assert not unsaved_note(window).property("visible") + assert backend.hasUnsavedChanges is False From 048d310dd2fa9fa3ed25c4e7e83ed216459b4ccd Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:30:54 -0500 Subject: [PATCH 09/31] Warn that Reset disconnects MapHide while it is running --- CHANGELOG.md | 2 ++ maphide/qt/Settings.qml | 19 +++++++++- maphide/qt/app.py | 4 +++ maphide/qt/view.py | 15 ++++++++ tests/test_qt_drawer.py | 77 +++++++++++++++++++++++++++++++++++++++-- tests/test_qt_view.py | 35 +++++++++++++++++++ 6 files changed, 149 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05a9655..461efb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,8 @@ All notable changes to MapHide are documented here. Save puts your saved settings back, and Start uses your saved settings instead of saving what's in Settings. Settings shows Unsaved changes while you have any. +- Added a warning when you click Reset while MapHide is running, saying that + Reset disconnects MapHide from OBS. ## v0.2.6 - 2026-10-27 diff --git a/maphide/qt/Settings.qml b/maphide/qt/Settings.qml index ffa3e4c..256dbb0 100644 --- a/maphide/qt/Settings.qml +++ b/maphide/qt/Settings.qml @@ -703,11 +703,28 @@ Item { font.pixelSize: 12 color: settings.t.warn } + // One message at a time, in this order: a problem, the SAVED + // stamp, what a clicked Reset would interrupt, unsaved changes. + readonly property bool showResetWarning: settings.resetArmed + && backend.resetWarning !== "" + && settings.footerProblem === "" && !settings.savedStamp + Label { + objectName: "resetWarning" + anchors.fill: parent + visible: parent.showResetWarning + text: backend.resetWarning + wrapMode: Text.Wrap + verticalAlignment: Text.AlignVCenter + horizontalAlignment: Text.AlignHCenter + font.pixelSize: 12 + color: settings.t.warn + } // Closing Settings without Save puts the saved settings back. Label { objectName: "unsavedNote" anchors.fill: parent - visible: backend.hasUnsavedChanges && settings.footerProblem === "" && !settings.savedStamp + visible: backend.hasUnsavedChanges && settings.footerProblem === "" + && !settings.savedStamp && !parent.showResetWarning text: "Unsaved changes" verticalAlignment: Text.AlignVCenter horizontalAlignment: Text.AlignHCenter diff --git a/maphide/qt/app.py b/maphide/qt/app.py index a9034f9..37a61b6 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -346,6 +346,10 @@ def primaryEnabled(self): def testEnabled(self): return self._view.test_enabled + @Property(str, notify=changed) + def resetWarning(self): + return self._view.reset_warning + @Property("QVariantMap", notify=themeChanged) def theme(self): return theme_colors(theme_name(self._form["theme"])) diff --git a/maphide/qt/view.py b/maphide/qt/view.py index 2f79c91..58e7a65 100644 --- a/maphide/qt/view.py +++ b/maphide/qt/view.py @@ -19,6 +19,10 @@ COVERING_HINT = "Viewers see the cover, not your map." APPLYING_HINT = "Applying settings…" STOPPING_HINT = "Stopping…" +# Shown once Reset is clicked, while MapHide is running: the defaults have no +# OBS details, so Reset stops it. +RESET_DISCONNECTS = "Reset disconnects MapHide from OBS." +RESET_STOPS = "Reset stops MapHide." # What a service that has never run, or stopped normally, says about itself. _QUIET_STOP_MESSAGES = ("Idle", STOPPED_MESSAGE) @@ -34,6 +38,16 @@ class MainView: primary_is_stop: bool primary_enabled: bool test_enabled: bool + # What Reset would interrupt, or "" when MapHide isn't running. + reset_warning: str = "" + + +def _reset_warning(screen): + if screen in (SCREEN_CONNECTED, SCREEN_COVERING): + return RESET_DISCONNECTS + if screen == SCREEN_CONNECTING: + return RESET_STOPS + return "" def standby_hint(cfg): @@ -91,6 +105,7 @@ def main_view(controller): primary_is_stop=primary_is_stop, primary_enabled=controller.can_stop if primary_is_stop else controller.can_start, test_enabled=controller.can_test, + reset_warning=_reset_warning(screen), ) diff --git a/tests/test_qt_drawer.py b/tests/test_qt_drawer.py index c71c244..e8a8c77 100644 --- a/tests/test_qt_drawer.py +++ b/tests/test_qt_drawer.py @@ -11,16 +11,24 @@ import PySide6.QtQuick # noqa: E402,F401 from PySide6.QtCore import QEvent, QObject, Qt # noqa: E402 from PySide6.QtGui import QGuiApplication, QKeyEvent # noqa: E402 +from test_controller import FakeService # noqa: E402 +from maphide.overlay import CONNECTED, RECONNECTING, ServiceStatus # noqa: E402 from maphide.qt.app import Backend, build_window # noqa: E402 +from maphide.qt.view import RESET_DISCONNECTS, RESET_STOPS # noqa: E402 SAVED = {"host": "10.0.0.2", "port": "4455", "scene_item_name": "Overlay"} @pytest.fixture -def setup(qt_app): +def service(): + return FakeService() + + +@pytest.fixture +def setup(qt_app, service): saved = [] - backend = Backend(update_checks=False, save=saved.append) + backend = Backend(update_checks=False, save=saved.append, service=service) engine, window, warnings = build_window(backend) assert window is not None, warnings for name, value in SAVED.items(): @@ -138,3 +146,68 @@ def test_the_unsaved_note_goes_once_settings_close(setup): assert not unsaved_note(window).property("visible") assert backend.hasUnsavedChanges is False + + +# What a clicked Reset would interrupt. + + +def reset_warning(window): + return window.findChild(QObject, "resetWarning") + + +def arm_reset(window): + """Reset's first click: it now waits for a second.""" + window.findChild(QObject, "settings").setProperty("resetArmed", True) + QGuiApplication.processEvents() + + +def run(backend, service, state, message): + backend.primary() + service.status = ServiceStatus(state, message) + backend.refresh() + QGuiApplication.processEvents() + + +def test_reset_warns_it_disconnects_while_connected(setup, service): + backend, window = setup + run(backend, service, CONNECTED, "Connected to OBS.") + + arm_reset(window) + + assert reset_warning(window).property("visible") + assert reset_warning(window).property("text") == RESET_DISCONNECTS + + +def test_reset_warns_it_stops_maphide_while_still_connecting(setup, service): + backend, window = setup + run(backend, service, RECONNECTING, "Reconnecting... 2s") + + arm_reset(window) + + assert reset_warning(window).property("text") == RESET_STOPS + + +def test_reset_warns_nothing_until_clicked(setup, service): + backend, window = setup + run(backend, service, CONNECTED, "Connected to OBS.") + + assert not reset_warning(window).property("visible") + + +def test_reset_warns_nothing_while_stopped(setup): + backend, window = setup + + arm_reset(window) + + assert not reset_warning(window).property("visible") + + +def test_the_reset_warning_shows_instead_of_the_unsaved_note(setup, service): + backend, window = setup + run(backend, service, CONNECTED, "Connected to OBS.") + type_into(window, host_field(window), "9") + + arm_reset(window) + + assert reset_warning(window).property("visible") + assert not unsaved_note(window).property("visible") diff --git a/tests/test_qt_view.py b/tests/test_qt_view.py index 9ac94dd..aa58613 100644 --- a/tests/test_qt_view.py +++ b/tests/test_qt_view.py @@ -27,6 +27,8 @@ COVERING_HINT, QT_KEY_ESCAPE, QT_KEY_SHIFT, + RESET_DISCONNECTS, + RESET_STOPS, SCREEN_CONNECTED, SCREEN_CONNECTING, SCREEN_COVERING, @@ -165,6 +167,39 @@ def test_stopping_reads_as_offline_but_cant_be_started_yet(): assert not view.primary_enabled +# What Reset warns about, once clicked. + + +@pytest.mark.parametrize( + ("ctrl", "warning"), + [ + (controller(), ""), + (controller(STOPPED, "Failed to connect to OBS."), ""), + (controller(STOPPING, "Stopping..."), ""), + (controller(CONNECTING, "Connecting to OBS..."), RESET_STOPS), + (controller(RECONNECTING, "Reconnecting... 2s"), RESET_STOPS), + (controller(STOPPING, "Stopping...", restart_pending=True), RESET_STOPS), + (controller(CONNECTED, "Connected to OBS."), RESET_DISCONNECTS), + ( + controller(CONNECTED, "Connected to OBS.", ObsSnapshot(covered=True)), + RESET_DISCONNECTS, + ), + ], + ids=[ + "never started", + "stopped after a failure", + "stopping", + "connecting", + "reconnecting", + "applying settings", + "connected", + "covering", + ], +) +def test_reset_warns_when_it_would_stop_maphide(ctrl, warning): + assert main_view(ctrl).reset_warning == warning + + # The field log's catch-up. From 05c300ae686152b909bbdaa5f58c5295c99b079d Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:45:23 -0500 Subject: [PATCH 10/31] Keep trying to reach a copy that is still starting before saying it is running --- CHANGELOG.md | 2 ++ map_hider.py | 30 +++++++++++++++---- maphide/single_instance.py | 15 ++++++---- tests/test_map_hider.py | 54 +++++++++++++++++++++++++++++------ tests/test_single_instance.py | 29 +++++++++++++++++++ 5 files changed, 112 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 461efb0..747f90e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,8 @@ All notable changes to MapHide are documented here. you have any. - Added a warning when you click Reset while MapHide is running, saying that Reset disconnects MapHide from OBS. +- Fixed MapHide refusing to open after it was closed, saying it was already + running, while an earlier "already running" message was still open. ## v0.2.6 - 2026-10-27 diff --git a/map_hider.py b/map_hider.py index a3a7815..2fee861 100644 --- a/map_hider.py +++ b/map_hider.py @@ -39,8 +39,11 @@ # than the window's own exit backstop, so a slow but working exit is never # reported as a failure. QUIT_WAIT_SECONDS = 20 -# How long `--quit` keeps trying to reach a copy that isn't listening yet. +# How long `--quit`, and a second launch, keep trying to reach a copy that +# isn't listening yet, and how often. QUIT_DELIVERY_SECONDS = 5 +SHOW_DELIVERY_SECONDS = 5 +DELIVERY_RETRY_SECONDS = 0.25 ALREADY_RUNNING_MESSAGE = "MapHide is already running." ALREADY_RUNNING_NOTICE_MUTEX = "Local\\MapHide-AlreadyRunningNotice" # Distinct from the main window's title ("MapHide") so FindWindowW below can @@ -143,10 +146,25 @@ def quit_running_copy(wait_seconds=QUIT_WAIT_SECONDS): return 0 if time.monotonic() >= deadline: return 1 - time.sleep(0.25) + time.sleep(DELIVERY_RETRY_SECONDS) return 0 if wait_until_closed(wait_seconds) else 1 +def show_running_copy(): + """Bring the running copy's window forward. Returns whether it got the + message. A copy started a moment ago holds the lock at once but only + listens once its window is built, so keep trying for a few seconds, as + --quit does. Gives up early if that copy closes meanwhile.""" + import time + + deadline = time.monotonic() + SHOW_DELIVERY_SECONDS + while not send_command(COMMAND_SHOW): + if not is_running() or time.monotonic() >= deadline: + return False + time.sleep(DELIVERY_RETRY_SECONDS) + return True + + def report_already_running(headless, notice_name=ALREADY_RUNNING_NOTICE_MUTEX): if headless: print(ALREADY_RUNNING_MESSAGE) @@ -177,10 +195,12 @@ def main(): if not acquire_single_instance(): # The running copy brings its own window forward; the notice is only # for when it can't be reached. - if not headless and send_command(COMMAND_SHOW): + if not headless and show_running_copy(): sys.exit(0) - report_already_running(headless) - sys.exit(1) + # Unless it closed while this launch waited: then this one is MapHide. + if headless or not acquire_single_instance(): + report_already_running(headless) + sys.exit(1) if headless: run_headless() diff --git a/maphide/single_instance.py b/maphide/single_instance.py index 35c7fd7..0ac4479 100644 --- a/maphide/single_instance.py +++ b/maphide/single_instance.py @@ -31,17 +31,22 @@ def acquire(name=MUTEX_NAME): """True if this is the only running copy holding `name`. - The handle is deliberately never closed - it lives for the life of the - process, and Windows releases it automatically on exit (including a - crash), so a later launch can never be blocked by a copy that died - uncleanly. + The winner's handle is deliberately never closed - it lives for the life + of the process, and Windows releases it automatically on exit (including + a crash), so a later launch can never be blocked by a copy that died + uncleanly. A launch that finds `name` already held lets go of its handle + at once: holding it would keep `name` marked as running after the real + copy exits. """ handle = _kernel32.CreateMutexW(None, False, name) if not handle: # Could not even ask the OS - fail open rather than block a # legitimate launch over something unrelated to another copy running. return True - return ctypes.get_last_error() != ERROR_ALREADY_EXISTS + if ctypes.get_last_error() == ERROR_ALREADY_EXISTS: + _kernel32.CloseHandle(handle) + return False + return True # --- talking to the running copy ------------------------------------------- diff --git a/tests/test_map_hider.py b/tests/test_map_hider.py index 49923eb..ede1ec0 100644 --- a/tests/test_map_hider.py +++ b/tests/test_map_hider.py @@ -183,40 +183,78 @@ def test_quit_fails_if_the_running_copy_does_not_close(monkeypatch): assert map_hider.quit_running_copy() == 1 -def _second_launch(monkeypatch, delivered, argv=("map_hider.py",)): - shown = [] +def _second_launch( + monkeypatch, delivered, argv=("map_hider.py",), running=True, acquires=(False, False) +): + """Launch while another copy holds the lock. `delivered` is whether the + running copy hears "show": one answer for every try, or a list of them in + order. `acquires` answers each try at the lock in turn.""" + shown, sent = [], [] + answers = list(delivered) if isinstance(delivered, list) else None + locks = iter(acquires) + + def send(command): + sent.append(command) + return answers.pop(0) if answers is not None else delivered + monkeypatch.setattr(map_hider.sys, "argv", list(argv)) - monkeypatch.setattr(map_hider, "acquire_single_instance", lambda *args: False) - monkeypatch.setattr(map_hider, "send_command", lambda command: delivered) + monkeypatch.setattr(map_hider, "acquire_single_instance", lambda *args: next(locks)) + monkeypatch.setattr(map_hider, "send_command", send) + monkeypatch.setattr(map_hider, "is_running", lambda: running) + monkeypatch.setattr(map_hider, "SHOW_DELIVERY_SECONDS", 0.3) + monkeypatch.setattr(map_hider, "DELIVERY_RETRY_SECONDS", 0.01) monkeypatch.setattr( map_hider, "report_already_running", lambda headless: shown.append(headless) ) + monkeypatch.setattr("maphide.qt.app.main", lambda: "started") try: map_hider.main() except SystemExit as exit_: - return exit_.code, shown + return exit_.code, shown, sent raise AssertionError("main() returned instead of exiting") def test_a_second_launch_brings_the_running_window_forward(monkeypatch): - code, shown = _second_launch(monkeypatch, delivered=True) + code, shown, _sent = _second_launch(monkeypatch, delivered=True) + + assert code == 0 + assert shown == [] + + +def test_a_second_launch_waits_for_a_copy_that_is_still_starting(monkeypatch): + # The first copy holds the lock at once but only listens once its + # window is built, about a second later. + code, shown, sent = _second_launch(monkeypatch, delivered=[False, False, True]) assert code == 0 assert shown == [] + assert sent == ["show", "show", "show"] def test_a_second_launch_falls_back_to_the_notice(monkeypatch): - code, shown = _second_launch(monkeypatch, delivered=False) + code, shown, _sent = _second_launch(monkeypatch, delivered=False) assert code == 1 assert shown == [False] +def test_a_second_launch_opens_maphide_if_the_running_copy_closed(monkeypatch): + code, shown, _sent = _second_launch( + monkeypatch, delivered=False, running=False, acquires=(False, True) + ) + + assert code == "started" + assert shown == [] + + def test_a_second_headless_launch_only_prints(monkeypatch): - code, shown = _second_launch(monkeypatch, delivered=True, argv=("map_hider.py", "--headless")) + code, shown, sent = _second_launch( + monkeypatch, delivered=True, argv=("map_hider.py", "--headless") + ) assert code == 1 assert shown == [True] + assert sent == [] def test_quit_gives_up_quickly_when_the_running_copy_cannot_be_reached(monkeypatch): diff --git a/tests/test_single_instance.py b/tests/test_single_instance.py index bfba21b..5c20cbd 100644 --- a/tests/test_single_instance.py +++ b/tests/test_single_instance.py @@ -1,5 +1,7 @@ """Tests for the OS-level guard against two copies of MapHide running at once.""" +import subprocess +import sys import uuid from maphide import single_instance @@ -26,6 +28,33 @@ def test_two_different_names_do_not_interfere(): assert single_instance.acquire(_unique_name()) is True +def test_a_launch_that_finds_one_running_does_not_keep_it_marked_running(): + # Another process holds the name, as a running MapHide would. + name = _unique_name() + holder = subprocess.Popen( # noqa: S603 - this interpreter, fixed code + [ + sys.executable, + "-c", + "import sys; from maphide import single_instance as s;" + f" s.acquire({name!r}); print('held', flush=True); sys.stdin.read()", + ], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + try: + assert holder.stdout.readline().strip() == "held" + assert single_instance.acquire(name) is False + + holder.stdin.close() + holder.wait(timeout=10) + + # Only the other process held it: once it's gone, so is the name. + assert single_instance.is_running(name) is False + finally: + holder.kill() + + # --- talking to the running copy ---------------------------------------------- From 59a71ab3ae0c34ea1e0770b7f50bfe5a1c2c186d Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:55:00 -0500 Subject: [PATCH 11/31] Keep the status box text inside its box --- maphide/qt/Main.qml | 14 ++++++ tests/test_qt_status.py | 104 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 tests/test_qt_status.py diff --git a/maphide/qt/Main.qml b/maphide/qt/Main.qml index ba204f6..1d10c6d 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -222,7 +222,21 @@ Window { } Mono { id: value + objectName: "statusValue" + cell.index + // Its box, for the tests. + readonly property Item box: cell + // Never past its own box. A scene name can be + // any length, so a long one ends in "…". The + // link state and mode are short enough to + // shrink to fit instead. (Qt doesn't shrink + // text that may also end in "…".) + readonly property bool isScene: cell.index === 1 + width: cell.width - 24 - (dot.visible ? dot.width + 6 : 0) font.pixelSize: 13 + fontSizeMode: isScene ? Text.FixedSize : Text.HorizontalFit + // 11 draws as wide as 12 in this font. + minimumPixelSize: 10 + elide: isScene ? Text.ElideRight : Text.ElideNone text: cell.index === 0 ? ({ stopped: "OFFLINE", connecting: "LINKING" })[win.st] || "ONLINE" : cell.index === 1 ? backend.scene : backend.mode diff --git a/tests/test_qt_status.py b/tests/test_qt_status.py new file mode 100644 index 0000000..ac4a8ea --- /dev/null +++ b/tests/test_qt_status.py @@ -0,0 +1,104 @@ +"""The main screen's status boxes (OBS LINK, LIVE SCENE, MODE) keep their +text inside them, however long a scene name is.""" + +import pytest + +pytest.importorskip("PySide6") + +import PySide6.QtQuick # noqa: E402,F401 +from PySide6.QtCore import QPointF # noqa: E402 +from PySide6.QtGui import QGuiApplication # noqa: E402 +from test_controller import FakeService # noqa: E402 + +from maphide.overlay import CONNECTED, ObsSnapshot, ServiceStatus # noqa: E402 +from maphide.qt.app import Backend, build_window, load_fonts # noqa: E402 + +LONG_SCENE = "Gameplay - Fullscreen Main Cam (Ranked)" + + +@pytest.fixture +def setup(qt_app): + # Sizes depend on the font, so use the one the app draws in. + load_fonts() + service = FakeService() + backend = Backend(update_checks=False, save=lambda cfg: None, service=service) + engine, window, warnings = build_window(backend) + assert window is not None, warnings + window.show() + yield backend, service, window + window.hide() + del engine + + +def connect(backend, service, scene, **settings): + form = {"host": "10.0.0.2", "port": "4455", "scene_item_name": "Overlay", **settings} + for name, value in form.items(): + backend.setField(name, value) + backend.save() + backend.primary() + service.status = ServiceStatus(CONNECTED, "Connected to OBS.") + service.snapshot = ObsSnapshot(scene=scene) + backend.refresh() + QGuiApplication.processEvents() + + +def value(window, index): + # Made by a Repeater, so only the visual tree reaches it. + pending = [window.contentItem()] + while pending: + item = pending.pop(0) + if item.objectName() == f"statusValue{index}": + return item + pending.extend(item.childItems()) + return None + + +def right_edge(item): + """Where the drawn text ends, in window coordinates.""" + return item.mapToScene(QPointF(item.property("contentWidth"), 0)).x() + + +def box_right_edge(item): + box = item.property("box") + return box.mapToScene(QPointF(box.width(), 0)).x() + + +def test_a_long_scene_name_stays_in_its_box(setup): + backend, service, window = setup + connect(backend, service, LONG_SCENE) + + scene = value(window, 1) + + assert right_edge(scene) <= box_right_edge(scene) + # Cut short with "…", so it's clear there is more. + assert scene.property("truncated") + + +def test_a_short_scene_name_shows_in_full(setup): + backend, service, window = setup + connect(backend, service, "Gameplay") + + scene = value(window, 1) + + assert scene.property("text") == "Gameplay" + assert not scene.property("truncated") + + +def test_toggle_mode_with_a_shift_key_fits_without_being_cut(setup): + backend, service, window = setup + connect(backend, service, "Gameplay", toggle_mode=True, hotkey="G", hide_hotkey="SHIFT+H") + + mode = value(window, 2) + + assert mode.property("text") == "TOGGLE · G/SHIFT+H" + assert right_edge(mode) <= box_right_edge(mode) + assert not mode.property("truncated") + + +def test_the_link_state_stays_in_its_box(setup): + backend, service, window = setup + connect(backend, service, "Gameplay") + + link = value(window, 0) + + assert right_edge(link) <= box_right_edge(link) From 10871764a346f579d42511b351a89038db1a2f58 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:07:06 -0500 Subject: [PATCH 12/31] Let the field log scroll sideways for lines too long to fit --- maphide/qt/Main.qml | 143 ++++++++++++++++++++++-------- tests/test_qt_fieldlog_scroll.py | 145 +++++++++++++++++++++++++++++++ 2 files changed, 254 insertions(+), 34 deletions(-) create mode 100644 tests/test_qt_fieldlog_scroll.py diff --git a/maphide/qt/Main.qml b/maphide/qt/Main.qml index 1d10c6d..3f392b6 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -542,51 +542,126 @@ Window { Rectangle { objectName: "fieldLog" width: parent.width - height: Math.max(0,win.height - y - column.y - 36) + height: Math.max(0, win.height - y - column.y - 36) color: win.t.glass border.color: win.t.border clip: true - Column { + Condensed { + id: logHeading x: 14 y: 10 + text: "FIELD LOG" + font.pixelSize: 13 + font.weight: Font.Normal + font.letterSpacing: win.em(13, 0.16) + color: win.t.muted + } + // The lines scroll sideways when one is too long to fit, but + // only when you scroll them: a new line never moves them. + Flickable { + id: logView + objectName: "fieldLogView" + x: 14 + y: logHeading.y + logHeading.height + 5 width: parent.width - 28 - spacing: 5 - Condensed { - text: "FIELD LOG" - font.pixelSize: 13 - font.weight: Font.Normal - font.letterSpacing: win.em(13, 0.16) - color: win.t.muted - } - Repeater { - model: ListModel { id: logModel } - delegate: Item { - id: line - required property string time - required property string text - required property string tone - property real reveal: 0 - width: lineRow.width * Math.floor(reveal * 18) / 18 - height: lineRow.height - clip: true - NumberAnimation on reveal { from: 0; to: 1; duration: 350 } - Row { - id: lineRow - spacing: 10 - Mono { text: line.time; font.pixelSize: 12; color: win.t.faint } - Mono { - text: line.text - font.pixelSize: 12 - color: ({ - linked: win.t.ok, - covered: win.coverRedText, - warning: win.t.warn - })[line.tone] || win.t.text + height: Math.max(0, logBar.y - y - 4) + clip: true + contentWidth: Math.max(width, logLines.width) + contentHeight: logLines.height + flickableDirection: Flickable.HorizontalFlick + boundsBehavior: Flickable.StopAtBounds + interactive: contentWidth > width + readonly property real maxX: Math.max(0, contentWidth - width) + function scrollTo(x) { contentX = Math.max(0, Math.min(maxX, x)) } + // Long lines dropping off the log: stay within what's left. + onMaxXChanged: if (contentX > maxX) contentX = maxX + Column { + id: logLines + spacing: 5 + Repeater { + model: ListModel { id: logModel } + delegate: Item { + id: line + required property string time + required property string text + required property string tone + property real reveal: 0 + width: lineRow.width * Math.floor(reveal * 18) / 18 + height: lineRow.height + clip: true + NumberAnimation on reveal { from: 0; to: 1; duration: 350 } + Row { + id: lineRow + spacing: 10 + Mono { text: line.time; font.pixelSize: 12; color: win.t.faint } + Mono { + text: line.text + font.pixelSize: 12 + color: ({ + linked: win.t.ok, + covered: win.coverRedText, + warning: win.t.warn + })[line.tone] || win.t.text + } } } } } } + // The wheel scrolls the lines sideways anywhere over them, + // as there is nothing to scroll up and down. + MouseArea { + anchors.fill: logView + acceptedButtons: Qt.NoButton + onWheel: (wheel) => { + const delta = wheel.angleDelta.x !== 0 ? wheel.angleDelta.x : wheel.angleDelta.y + logView.scrollTo(logView.contentX - delta / 2) + } + } + // A thin bar along the bottom, only while a line is too long + // to fit: drag it to scroll. + Rectangle { + id: logBar + objectName: "fieldLogBar" + visible: logView.maxX > 0 + x: 14 + y: parent.height - height - 8 + width: parent.width - 28 + height: 4 + color: win.t.border + Rectangle { + id: logHandle + objectName: "fieldLogHandle" + width: Math.max(24, parent.width * logView.width / logView.contentWidth) + height: parent.height + x: logView.maxX > 0 ? (parent.width - width) * logView.contentX / logView.maxX : 0 + color: handleDrag.pressed || handleDrag.containsMouse ? win.t.muted : win.t.border2 + } + // Taller than the bar, so it's easy to grab. + MouseArea { + id: handleDrag + anchors.fill: parent + anchors.topMargin: -6 + anchors.bottomMargin: -6 + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + property real grabX: 0 + property real grabContentX: 0 + onPressed: (mouse) => { + if (mouse.x < logHandle.x || mouse.x > logHandle.x + logHandle.width) + // A click beside the handle jumps it there. + logView.scrollTo((mouse.x - logHandle.width / 2) + / (width - logHandle.width) * logView.maxX) + grabX = mouse.x + grabContentX = logView.contentX + } + onPositionChanged: (mouse) => { + if (pressed && width > logHandle.width) + logView.scrollTo(grabContentX + + (mouse.x - grabX) / (width - logHandle.width) * logView.maxX) + } + } + } Connections { target: backend function onLineAdded(time, text, tone) { diff --git a/tests/test_qt_fieldlog_scroll.py b/tests/test_qt_fieldlog_scroll.py new file mode 100644 index 0000000..b99eddd --- /dev/null +++ b/tests/test_qt_fieldlog_scroll.py @@ -0,0 +1,145 @@ +"""The field log scrolls sideways for a line too long to fit, but only when +you scroll it: a new line never moves it.""" + +import time + +import pytest + +pytest.importorskip("PySide6") + +import PySide6.QtQuick # noqa: E402,F401 +from PySide6.QtCore import QEvent, QPoint, QPointF, Qt # noqa: E402 +from PySide6.QtGui import QGuiApplication, QMouseEvent, QWheelEvent # noqa: E402 + +from maphide.qt.app import Backend, build_window, load_fonts # noqa: E402 + +LONG = "> scene · Gameplay - Fullscreen Main Cam (Ranked) yoyoyoyoyoyoyoyoyoyoyoyoy" + + +@pytest.fixture +def window(qt_app): + load_fonts() + backend = Backend(update_checks=False, save=lambda cfg: None) + engine, window, warnings = build_window(backend) + assert window is not None, warnings + window.show() + window._backend = backend + yield window + window.hide() + del engine + + +def find(window, name): + pending = [window.contentItem()] + while pending: + item = pending.pop(0) + if item.objectName() == name: + return item + pending.extend(item.childItems()) + raise AssertionError(f"{name} not found") + + +def settle(seconds=0.5): + """Let the lines finish typing themselves in.""" + end = time.monotonic() + seconds + while time.monotonic() < end: + QGuiApplication.processEvents() + time.sleep(0.01) + + +def add(window, text): + window._backend.lineAdded.emit("19:00:49", text, "") + settle() + + +def view(window): + return find(window, "fieldLogView") + + +def bar(window): + return find(window, "fieldLogBar") + + +def scrolled(window): + return view(window).property("contentX") + + +def test_short_lines_need_no_scroll_bar(window): + add(window, "> cover dropped") + + assert not bar(window).isVisible() + + +def test_a_line_too_long_to_fit_brings_up_the_scroll_bar(window): + add(window, LONG) + + assert bar(window).isVisible() + assert scrolled(window) == 0 + + +def test_a_new_line_never_scrolls_the_log(window): + add(window, LONG) + view(window).setProperty("contentX", 40) + + add(window, LONG + " more") + add(window, "> cover dropped") + + assert scrolled(window) == 40 + + +def drag(window, item, dx): + start = item.mapToScene(QPointF(item.width() / 2, item.height() / 2)) + end = QPointF(start.x() + dx, start.y()) + left = Qt.MouseButton.LeftButton + none = Qt.MouseButton.NoButton + no_keys = Qt.KeyboardModifier.NoModifier + for kind, point, buttons in ( + (QEvent.Type.MouseButtonPress, start, left), + (QEvent.Type.MouseMove, QPointF(start.x() + dx / 2, start.y()), left), + (QEvent.Type.MouseMove, end, left), + (QEvent.Type.MouseButtonRelease, end, none), + ): + QGuiApplication.sendEvent(window, QMouseEvent(kind, point, point, left, buttons, no_keys)) + QGuiApplication.processEvents() + + +def test_dragging_the_bar_scrolls_the_log(window): + add(window, LONG) + + drag(window, find(window, "fieldLogHandle"), 60) + + assert scrolled(window) > 0 + + +def test_the_mouse_wheel_scrolls_the_log_sideways(window): + add(window, LONG) + log = view(window) + point = log.mapToScene(QPointF(log.width() / 2, 10)) + + QGuiApplication.sendEvent( + window, + QWheelEvent( + point, + point, + QPoint(0, 0), + QPoint(0, -120), + Qt.MouseButton.NoButton, + Qt.KeyboardModifier.NoModifier, + Qt.ScrollPhase.NoScrollPhase, + False, + ), + ) + QGuiApplication.processEvents() + + assert scrolled(window) > 0 + + +def test_once_the_long_lines_are_gone_the_log_slides_back(window): + add(window, LONG) + view(window).setProperty("contentX", 80) + + for _ in range(6): + add(window, "> cover dropped") + + assert scrolled(window) == 0 + assert not bar(window).isVisible() From 48d16fec8312d8e3919fee61c14f8b1fc1369c14 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:34:46 -0500 Subject: [PATCH 13/31] Tighten the updater's download and hand-off to the installer --- maphide/updates.py | 81 ++++++++++++++++++++-- tests/test_qt_backend.py | 4 ++ tests/test_updates.py | 145 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 224 insertions(+), 6 deletions(-) diff --git a/maphide/updates.py b/maphide/updates.py index c507ddb..5cfdcca 100644 --- a/maphide/updates.py +++ b/maphide/updates.py @@ -30,6 +30,9 @@ SETUP_NAME = re.compile(r"MapHide-v(\d+\.\d+\.\d+)-setup\.exe") TIMEOUT_SECONDS = 20 CHUNK_BYTES = 64 * 1024 +# A cap for a download whose size GitHub didn't give; the setup file is +# about 30 MB. +MAX_SETUP_BYTES = 200 * 1024 * 1024 POLL_INTERVAL_MS = 100 # Runs the installer showing only its progress, then reopens MapHide. INSTALLER_ARGUMENTS = ("/SILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/RELAUNCH=1") @@ -101,6 +104,20 @@ def release_from_json(data): return Release(version) +class HttpsOnlyRedirects(urllib.request.HTTPRedirectHandler): + """Follows a redirect only if it stays on https. GitHub sends downloads + on to its file servers; a redirect to plain http is refused.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + if not newurl.startswith("https://"): + raise urllib.error.HTTPError(newurl, code, "Redirect away from https", headers, fp) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +# How MapHide goes online: https only, redirects included. +OPENER = urllib.request.build_opener(HttpsOnlyRedirects()) + + def _request(url): # Only ever https: the release API above, or a download checked against # DOWNLOAD_PREFIX. @@ -112,7 +129,7 @@ def _request(url): ) -def fetch_latest(opener=urllib.request.urlopen): +def fetch_latest(opener=OPENER.open): """The latest release on GitHub. Raises UpdateError.""" try: with opener(_request(LATEST_RELEASE_API), timeout=TIMEOUT_SECONDS) as reply: @@ -128,7 +145,7 @@ def fetch_latest(opener=urllib.request.urlopen): return release_from_json(data) -def download_setup(release, folder, progress=None, opener=urllib.request.urlopen): +def download_setup(release, folder, progress=None, opener=OPENER.open): """Download `release`'s setup file into `folder` and check it against GitHub's checksum. `progress(fraction)` is called as it arrives. Returns the file's path. Raises UpdateError.""" @@ -144,16 +161,19 @@ def download_setup(release, folder, progress=None, opener=urllib.request.urlopen with opener(_request(release.setup_url), timeout=TIMEOUT_SECONDS) as reply: with open(partial, "wb") as file: while chunk := reply.read(CHUNK_BYTES): + received += len(chunk) + # Never more than GitHub said the file is. + if received > (release.setup_size or MAX_SETUP_BYTES): + raise UpdateError(DOWNLOAD_DAMAGED) file.write(chunk) digest.update(chunk) - received += len(chunk) if progress is not None and release.setup_size: progress(min(received / release.setup_size, 1.0)) if digest.hexdigest() != release.setup_sha256: - partial.unlink(missing_ok=True) raise UpdateError(DOWNLOAD_DAMAGED) partial.replace(target) except UpdateError: + partial.unlink(missing_ok=True) raise except (urllib.error.URLError, TimeoutError, OSError) as exc: partial.unlink(missing_ok=True) @@ -161,9 +181,47 @@ def download_setup(release, folder, progress=None, opener=urllib.request.urlopen return target -def launch_installer(path, popen=subprocess.Popen): +def check_setup(path, sha256): + """Check the downloaded setup file against GitHub's checksum once more, + right before it runs. Raises UpdateError if it changed since.""" + digest = hashlib.sha256() + try: + with open(path, "rb") as file: + while chunk := file.read(CHUNK_BYTES): + digest.update(chunk) + except OSError as exc: + raise UpdateError(DOWNLOAD_DAMAGED) from exc + if digest.hexdigest() != sha256: + raise UpdateError(DOWNLOAD_DAMAGED) + + +def clean_downloads(folder): + """Delete setup files from earlier updates, and downloads cut short. A + file still in use, such as an installer still finishing, stays.""" + for pattern in ("MapHide-v*-setup.exe", "MapHide-v*-setup.part"): + for path in Path(folder).glob(pattern): + try: + path.unlink() + except OSError: + pass + + +def _reset_dll_folder(): + # The packaged app points Windows at its own DLL folder, and programs it + # starts would look there too. The installer should use only its own. + import ctypes + + ctypes.windll.kernel32.SetDllDirectoryW(None) + + +def launch_installer( + path, popen=subprocess.Popen, frozen=None, reset_dll_folder=_reset_dll_folder +): """Start the setup file, which closes MapHide, installs over it and reopens it. Raises UpdateError if it can't start.""" + frozen = getattr(sys, "frozen", False) if frozen is None else frozen + if frozen: + reset_dll_folder() try: popen([str(path), *INSTALLER_ARGUMENTS], close_fds=True) except OSError as exc: @@ -205,6 +263,8 @@ def __init__( launch=launch_installer, can_install=None, folder=None, + verify=check_setup, + clean=clean_downloads, ): self._schedule = schedule self._on_change = on_change @@ -212,6 +272,8 @@ def __init__( self._fetch = fetch self._download = download self._launch = launch + self._verify = verify + self._clean = clean self.can_install = installed_by_setup() if can_install is None else can_install self._folder = download_folder() if folder is None else folder self.state = IDLE @@ -282,7 +344,13 @@ def done(release, error): self._set(IDLE if quiet else LATEST) self._set(CHECKING) - self._run(self._fetch, done) + + def work(): + # Off the window's thread, as file access can be slow. + self._clean(self._folder) + return self._fetch() + + self._run(work, done) return True def clear_latest(self): @@ -303,6 +371,7 @@ def report(fraction): def work(): path = self._download(release, self._folder, report) + self._verify(path, release.setup_sha256) self._launch(path) def done(_result, error): diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index 203a57f..349b808 100644 --- a/tests/test_qt_backend.py +++ b/tests/test_qt_backend.py @@ -56,6 +56,10 @@ def __init__(self): "download": lambda release, folder, progress: "setup.exe", "launch": self.installers.append, "can_install": True, + # Never the real download folder. + "folder": "downloads", + "verify": lambda path, sha256: None, + "clean": lambda folder: None, }, service=self.service, save=self.saved.append, diff --git a/tests/test_updates.py b/tests/test_updates.py index b611ecc..a146d55 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -4,6 +4,7 @@ import io import json import urllib.error +import urllib.request import pytest from test_controller import ManualScheduler @@ -20,6 +21,8 @@ Release, UpdateError, Updater, + check_setup, + clean_downloads, download_setup, fetch_latest, installed_by_setup, @@ -199,6 +202,102 @@ def test_only_this_projects_releases_are_downloaded(tmp_path): download_setup(release, tmp_path, opener=opener_returning(SETUP_BYTES)) +def test_a_download_bigger_than_github_said_is_stopped(tmp_path): + release = Release("0.3.0", SETUP_URL, 100, SETUP_SHA) + + with pytest.raises(UpdateError, match="damaged"): + download_setup(release, tmp_path, opener=opener_returning(SETUP_BYTES)) + + assert list(tmp_path.iterdir()) == [] + + +def test_a_redirect_away_from_https_is_refused(): + request = urllib.request.Request(SETUP_URL) + + with pytest.raises(urllib.error.HTTPError): + updates.HttpsOnlyRedirects().redirect_request( + request, None, 302, "Found", {}, "http://example.com/setup.exe" + ) + + +def test_a_redirect_that_stays_on_https_is_followed(): + request = urllib.request.Request(SETUP_URL) + + followed = updates.HttpsOnlyRedirects().redirect_request( + request, None, 302, "Found", {}, "https://objects.githubusercontent.com/setup.exe" + ) + + assert followed.full_url == "https://objects.githubusercontent.com/setup.exe" + + +def test_maphide_goes_online_only_through_the_https_only_redirects(): + handlers = updates.OPENER.handlers + + assert any(isinstance(handler, updates.HttpsOnlyRedirects) for handler in handlers) + + +def test_the_setup_file_is_checked_again_just_before_it_runs(tmp_path): + path = tmp_path / "MapHide-v0.3.0-setup.exe" + path.write_bytes(SETUP_BYTES) + check_setup(path, SETUP_SHA) + + path.write_bytes(b"swapped after downloading") + + with pytest.raises(UpdateError, match="damaged"): + check_setup(path, SETUP_SHA) + + +def test_old_downloads_are_cleaned_up(tmp_path): + (tmp_path / "MapHide-v0.2.7-setup.exe").write_bytes(b"old") + (tmp_path / "MapHide-v0.3.0-setup.part").write_bytes(b"cut short") + (tmp_path / "something-else.txt").write_text("not ours") + + clean_downloads(tmp_path) + + assert [p.name for p in tmp_path.iterdir()] == ["something-else.txt"] + + +def test_cleaning_up_skips_a_file_still_in_use(tmp_path, monkeypatch): + (tmp_path / "MapHide-v0.2.7-setup.exe").write_bytes(b"still running") + + def in_use(self, missing_ok=False): + raise PermissionError("in use") + + monkeypatch.setattr(updates.Path, "unlink", in_use) + + clean_downloads(tmp_path) + + +def test_cleaning_up_with_no_download_folder_is_fine(tmp_path): + clean_downloads(tmp_path / "never-made") + + +def test_the_installer_starts_without_maphides_own_dll_folder(tmp_path): + calls = [] + + launch_installer( + tmp_path / "setup.exe", + lambda args, **_: calls.append("start"), + frozen=True, + reset_dll_folder=lambda: calls.append("reset"), + ) + + assert calls == ["reset", "start"] + + +def test_run_from_source_the_dll_folder_is_left_alone(tmp_path): + calls = [] + + launch_installer( + tmp_path / "setup.exe", + lambda args, **_: calls.append("start"), + frozen=False, + reset_dll_folder=lambda: calls.append("reset"), + ) + + assert calls == ["start"] + + def test_the_installer_runs_with_progress_only_and_reopens_maphide(tmp_path): launched = [] @@ -238,6 +337,9 @@ def __init__(self, release=None, error=None, can_install=True): self.downloads = [] self.launched = [] self.download_error = None + self.verify_error = None + self.verified = [] + self.cleaned = [] self.release = release or release_from_json(release_json()) self.error = error self.updater = Updater( @@ -249,8 +351,15 @@ def __init__(self, release=None, error=None, can_install=True): launch=self.launched.append, can_install=can_install, folder="downloads", + verify=self._verify, + clean=self.cleaned.append, ) + def _verify(self, path, sha256): + if self.verify_error: + raise UpdateError(self.verify_error) + self.verified.append((path, sha256)) + def _changed(self): self.changes += 1 @@ -417,6 +526,42 @@ def test_a_found_release_says_whether_it_can_be_installed(steps, installable): assert s.updater.can_install_release is installable +def test_the_setup_file_is_checked_again_between_download_and_launch(): + s = Steps() + s.updater.check() + s.finish() + + s.updater.install(on_started=lambda: None) + s.finish() + + assert s.verified == [("setup.exe", s.release.setup_sha256)] + assert s.launched == ["setup.exe"] + + +def test_a_setup_file_changed_after_download_is_not_run(): + s = Steps() + s.updater.check() + s.finish() + s.verify_error = updates.DOWNLOAD_DAMAGED + closed = [] + + s.updater.install(on_started=lambda: closed.append(True)) + s.finish() + + assert (s.updater.state, s.updater.message) == (FAILED, updates.DOWNLOAD_DAMAGED) + assert s.launched == [] + assert closed == [] + + +def test_a_check_clears_out_old_downloads(): + s = Steps() + + s.updater.check() + s.finish() + + assert s.cleaned == ["downloads"] + + def test_nothing_is_installed_before_a_check_finds_something(): s = Steps() From 18c5f7c8622fa6a572a6ccbe76e3dea2e5082eea Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:53:44 -0500 Subject: [PATCH 14/31] Keep MapHide stopped when settings are saved while it is stopping --- CHANGELOG.md | 2 ++ maphide/controller.py | 16 +++++++++++++--- tests/test_controller.py | 15 +++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 747f90e..520f4fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,8 @@ All notable changes to MapHide are documented here. Reset disconnects MapHide from OBS. - Fixed MapHide refusing to open after it was closed, saying it was already running, while an earlier "already running" message was still open. +- Fixed MapHide starting again when you saved settings right after pressing + Stop. ## v0.2.6 - 2026-10-27 diff --git a/maphide/controller.py b/maphide/controller.py index 8d380b0..b931ba8 100644 --- a/maphide/controller.py +++ b/maphide/controller.py @@ -22,7 +22,13 @@ worker_settings_differ, ) from .obs import ConnectionCheck, check_connection -from .overlay import CONNECTED, MapHideService, human_ts, stop_wait_should_continue +from .overlay import ( + CONNECTED, + STOPPING, + MapHideService, + human_ts, + stop_wait_should_continue, +) HISTORY_LINE_COUNT = 10 RESTART_POLL_INTERVAL_MS = 50 @@ -208,8 +214,12 @@ def _apply(self, cfg, done_message, code): self._record(cfg, done_message, code) # Only restart for a change the worker would actually see: a restart # briefly drops the OBS link and hides the overlay. A restart already - # under way always takes the newest settings. - if self.restart_pending or (self.service.is_running and self._worker_needs(cfg)): + # under way always takes the newest settings. A worker you stopped is + # left to stop, even while it is still finishing. + stopping = self.service.status.state == STOPPING + if self.restart_pending or ( + self.service.is_running and not stopping and self._worker_needs(cfg) + ): self._restart_service_with(cfg) self._on_change() diff --git a/tests/test_controller.py b/tests/test_controller.py index 3b154e5..38a4467 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -271,6 +271,21 @@ def test_a_restart_waits_as_long_as_the_old_worker_needs(h): assert len(h.schedule.pending) == 1 +def test_saving_while_maphide_is_stopping_does_not_start_it_again(h): + h.controller.start(make_config()) + h.controller.stop() + + h.controller.save(make_config(hotkey="M")) + h.service.finish_stopping() + while h.schedule.pending: + h.schedule.run_next() + + assert h.service.started_with == [make_config()] + assert h.saved[-1] == make_config(hotkey="M") + assert h.controller.running_config == make_config(hotkey="M") + assert h.controller.can_start is True + + def test_restoring_defaults_while_running_stops_and_stays_stopped(h): h.controller.start(make_config()) From 3573b9829341115610980b96d2b1e9b6cee0c048 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:56:53 -0500 Subject: [PATCH 15/31] Hide Host, Port and Password again when Settings closes --- CHANGELOG.md | 2 ++ maphide/qt/Main.qml | 8 +++++++- maphide/qt/Settings.qml | 11 +++++++++++ tests/test_qt_drawer.py | 41 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 520f4fa..162e33d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,8 @@ All notable changes to MapHide are documented here. running, while an earlier "already running" message was still open. - Fixed MapHide starting again when you saved settings right after pressing Stop. +- Changed Host, Port and Password to hide again whenever you close Settings + or MapHide goes to the tray, so they never stay shown on stream. ## v0.2.6 - 2026-10-27 diff --git a/maphide/qt/Main.qml b/maphide/qt/Main.qml index 3f392b6..41bc0d9 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -15,10 +15,16 @@ Window { // keeps a change. onDrawerOpenChanged: if (!drawerOpen) { settings.stopCapture() + settings.maskSecrets() releaseKeyboard() backend.discardChanges() } - onVisibleChanged: if (!visible) releaseKeyboard() + // Hidden to the tray, Settings may still be open: hide Host, Port and + // Password anyway. + onVisibleChanged: if (!visible) { + settings.maskSecrets() + releaseKeyboard() + } // Takes the keyboard back from whichever text field has it, so keys // pressed afterwards don't type into a field you can no longer see. diff --git a/maphide/qt/Settings.qml b/maphide/qt/Settings.qml index 256dbb0..b0c072a 100644 --- a/maphide/qt/Settings.qml +++ b/maphide/qt/Settings.qml @@ -20,6 +20,14 @@ Item { function stopCapture() { capturing = "" } + // Host, Port and Password back to hidden, so a reveal never outlasts + // the moment you wanted it: on stream, the next look would show them. + function maskSecrets() { + hostField.revealed = false + portField.revealed = false + passwordField.revealed = false + } + function startCapture(target) { capturing = capturing === target ? "" : target keyProblem = "" @@ -180,6 +188,7 @@ Item { width: parent.width spacing: 8 Field { + id: hostField width: (parent.width - 8) * 2 / 3 label: "HOST" secret: true @@ -187,6 +196,7 @@ Item { onEdited: (text) => backend.setField("host", text) } Field { + id: portField width: (parent.width - 8) / 3 label: "PORT" secret: true @@ -196,6 +206,7 @@ Item { } } Field { + id: passwordField width: parent.width label: "PASSWORD" secret: true diff --git a/tests/test_qt_drawer.py b/tests/test_qt_drawer.py index e8a8c77..26203b2 100644 --- a/tests/test_qt_drawer.py +++ b/tests/test_qt_drawer.py @@ -211,3 +211,44 @@ def test_the_reset_warning_shows_instead_of_the_unsaved_note(setup, service): assert reset_warning(window).property("visible") assert not unsaved_note(window).property("visible") + + +# Host, Port and Password go back to hidden. + + +def secret_fields(window): + found, pending = [], [window.contentItem()] + while pending: + item = pending.pop(0) + if item.property("secret") is True: + found.append(item) + pending.extend(item.childItems()) + return found + + +def reveal_all(window): + fields = secret_fields(window) + assert len(fields) == 3 + for field in fields: + field.setProperty("revealed", True) + QGuiApplication.processEvents() + return fields + + +def test_closing_settings_hides_host_port_and_password_again(setup): + backend, window = setup + fields = reveal_all(window) + + close_settings(window) + + assert [field.property("revealed") for field in fields] == [False, False, False] + + +def test_hiding_maphide_to_the_tray_hides_them_too(setup): + backend, window = setup + fields = reveal_all(window) + + window.hide() + QGuiApplication.processEvents() + + assert [field.property("revealed") for field in fields] == [False, False, False] From 2d9c46d9a1c43cd2a803d364cc61b647de8d6a3b Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:04:19 -0500 Subject: [PATCH 16/31] Keep the overlay warning when stopped while reconnecting --- CHANGELOG.md | 2 ++ maphide/overlay.py | 4 ++++ tests/fake_obs.py | 8 ++++++-- tests/test_pipeline.py | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 46 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 162e33d..26a8a64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,8 @@ All notable changes to MapHide are documented here. Stop. - Changed Host, Port and Password to hide again whenever you close Settings or MapHide goes to the tray, so they never stay shown on stream. +- Fixed MapHide only saying it stopped, when you pressed Stop while it was + reconnecting and the overlay might still be showing in OBS. ## v0.2.6 - 2026-10-27 diff --git a/maphide/overlay.py b/maphide/overlay.py index ea5a21d..abf8d61 100644 --- a/maphide/overlay.py +++ b/maphide/overlay.py @@ -765,6 +765,10 @@ def _run(self, cfg): "Could not hide the overlay while stopping: %s", describe_exception(exc) ) final_status_message = OBS_OVERLAY_MAY_REMAIN + elif client is None and overlay_may_remain and final_status_message == STOPPED_MESSAGE: + # Stopped while retrying a link that dropped with the overlay + # up: nothing has hidden it since, so the warning still holds. + final_status_message = OBS_OVERLAY_MAY_REMAIN if client is not None: try: disconnect_obs(client) diff --git a/tests/fake_obs.py b/tests/fake_obs.py index 60aa6a5..3d28dac 100644 --- a/tests/fake_obs.py +++ b/tests/fake_obs.py @@ -247,10 +247,11 @@ class Session: `connect` is a FakeObs (every connection attempt reaches it) or a list consumed one attempt at a time - an exception in the list is raised, and a list that runs dry is refused as a wrong password so the worker gives up - instead of retrying forever. + instead of retrying forever. `stop_at_connect` presses Stop during that + connection attempt (1 is the first), as if while MapHide retries. """ - def __init__(self, monkeypatch, cfg, connect, *, max_seconds=15.0): + def __init__(self, monkeypatch, cfg, connect, *, max_seconds=15.0, stop_at_connect=None): self.cfg = cfg self.service = MapHideService() self.keyboard = FakeKeyboard() @@ -267,6 +268,7 @@ def __init__(self, monkeypatch, cfg, connect, *, max_seconds=15.0): self._show_code = cfg.show_vk_codes()[0] self._started = time.monotonic() self._max_seconds = max_seconds + self._stop_at_connect = stop_at_connect monkeypatch.setattr(overlay_module, "connect_obs", self._connect_obs) monkeypatch.setattr(overlay_module, "configure_logging", lambda enabled: None) @@ -320,6 +322,8 @@ def run(self, scenario=None, *, worker_ends_first=False): def _connect_obs(self, host, port, password): self.status_at_connect.append(self.service.status) + if len(self.status_at_connect) == self._stop_at_connect: + self.service.stop() target = self._connect if isinstance(target, FakeObs): client = target diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 1ace7a7..e12f834 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -368,6 +368,40 @@ def scenario(s): assert "may still be showing" not in after_second_drop.message +def test_stopping_while_retrying_with_the_overlay_maybe_up_ends_with_the_warning(monkeypatch): + obs = standard_obs() + unreachable = ObsUnreachableError("Failed to connect to OBS. Make sure OBS is open.") + # Stop is pressed during the third attempt: the second failed retry. + session = Session(monkeypatch, make_config(), [obs] + [unreachable] * 5, stop_at_connect=3) + + def scenario(s): + yield first_scene_read(s) + s.keyboard.hold("G") + yield s.until(lambda: obs.is_enabled("Gameplay"), "the overlay to be shown") + obs.rule("GetCurrentProgramScene", raises=OBSSDKTimeoutError("timed out")) + yield s.pause(5.0) + + session.run(scenario, worker_ends_first=True) + + assert session.service.status.state == STOPPED + assert session.service.status.message == OBS_OVERLAY_MAY_REMAIN + + +def test_stopping_while_retrying_with_the_overlay_hidden_is_a_plain_stop(monkeypatch): + obs = standard_obs() + unreachable = ObsUnreachableError("Failed to connect to OBS. Make sure OBS is open.") + session = Session(monkeypatch, make_config(), [obs] + [unreachable] * 5, stop_at_connect=3) + + def scenario(s): + yield first_scene_read(s) + obs.rule("GetCurrentProgramScene", raises=OBSSDKTimeoutError("timed out")) + yield s.pause(5.0) + + session.run(scenario, worker_ends_first=True) + + assert session.service.status.message == "MapHide stopped." + + def test_with_auto_reconnect_off_a_drop_while_shown_ends_with_the_overlay_warning(monkeypatch): obs = standard_obs() session = Session(monkeypatch, make_config(auto_reconnect=False), obs) From 210e3624c17f4680ac3bae234728c9855951fb5e Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:22:17 -0500 Subject: [PATCH 17/31] Keep a settings reconnect from pushing the saved line out of the field log --- maphide/controller.py | 90 +++++++++++++++++++++++------ maphide/fieldlog.py | 3 + tests/test_controller.py | 121 +++++++++++++++++++++++++++++++++++++++ tests/test_fieldlog.py | 8 +++ 4 files changed, 205 insertions(+), 17 deletions(-) diff --git a/maphide/controller.py b/maphide/controller.py index b931ba8..66cbe7c 100644 --- a/maphide/controller.py +++ b/maphide/controller.py @@ -24,6 +24,14 @@ from .obs import ConnectionCheck, check_connection from .overlay import ( CONNECTED, + EVENT_CONNECTED, + EVENT_CONNECTING, + EVENT_OVERLAY_HIDDEN, + EVENT_OVERLAY_SHOWN, + EVENT_SCENE, + EVENT_SOURCE_FOUND, + EVENT_STOPPED, + STOPPED_MESSAGE, STOPPING, MapHideService, human_ts, @@ -49,6 +57,18 @@ # A message the window itself puts in the history, such as a setting it # can't use. HISTORY_NOTICE = "notice" +# The `subject` of a settings-saved entry when the save also reconnects to +# OBS to put the new settings into effect. +SUBJECT_RELINKING = "relinking" +# News a settings reconnect still shows, without ending its quiet: the link +# coming back, and the cover changing meanwhile. Anything else, a problem +# above all, shows and ends it. +_NEWS_WHILE_RELINKING = ( + EVENT_CONNECTED, + EVENT_OVERLAY_HIDDEN, + EVENT_OVERLAY_SHOWN, + EVENT_SOURCE_FOUND, +) @dataclass(frozen=True) @@ -98,6 +118,9 @@ def __init__( self._pending_restart_config = None self.exit_requested = False self.history = [] + # While a save reconnects to OBS: the scene before it, or None when + # no reconnect is under way. See _keeps_quiet. + self._relinking_from = None # What the window draws. @@ -185,9 +208,30 @@ def load(self, load=load_config): def save(self, cfg): """Save `cfg` and put it into effect. Raises OSError if it can't be - written, in which case nothing changes.""" + written, in which case nothing changes. + + Only a change the worker would actually see restarts it: a restart + briefly drops the OBS link and hides the overlay. A restart already + under way always takes the newest settings. A worker you stopped is + left to stop, even while it is still finishing.""" self._save(cfg) - self._apply(cfg, "Config saved.", HISTORY_SETTINGS_SAVED) + stopping = self.service.status.state == STOPPING + relink = self.restart_pending or ( + self.service.is_running and not stopping and self._worker_needs(cfg) + ) + self.running_config = cfg + if relink and self._relinking_from is None: + # The reconnect's own routine lines stay out of the history. + self._relinking_from = self.snapshot.scene or "" + self.add_history( + human_ts(), + "Config saved.", + HISTORY_SETTINGS_SAVED, + SUBJECT_RELINKING if relink else None, + ) + if relink: + self._restart_service_with(cfg) + self._on_change() def restore_defaults(self): """Save the default settings, and return them. A running worker is @@ -197,8 +241,10 @@ def restore_defaults(self): self._save(cfg) self._record(cfg, "Defaults restored.", HISTORY_DEFAULTS_RESTORED) if self.restart_pending: - # The restart under way finishes stopping, then starts nothing. + # The restart under way finishes stopping, then starts nothing: + # that stop is news again. self._pending_restart_config = None + self._relinking_from = None elif self.service.is_running: self.service.stop() self._on_change() @@ -210,19 +256,6 @@ def _record(self, cfg, done_message, code): # part of the OBS connection's own story. self.add_history(human_ts(), done_message, code) - def _apply(self, cfg, done_message, code): - self._record(cfg, done_message, code) - # Only restart for a change the worker would actually see: a restart - # briefly drops the OBS link and hides the overlay. A restart already - # under way always takes the newest settings. A worker you stopped is - # left to stop, even while it is still finishing. - stopping = self.service.status.state == STOPPING - if self.restart_pending or ( - self.service.is_running and not stopping and self._worker_needs(cfg) - ): - self._restart_service_with(cfg) - self._on_change() - def _worker_needs(self, cfg): return self._worker_config is None or worker_settings_differ(self._worker_config, cfg) @@ -233,11 +266,14 @@ def start(self, cfg): saves: only Save does. Raises RuntimeError if the worker is already running.""" self.service.start(cfg) + self._relinking_from = None self._worker_config = cfg self.running_config = cfg self._on_change() def stop(self): + # A stop you asked for is news, even mid-reconnect. + self._relinking_from = None self.service.stop() self._on_change() @@ -270,6 +306,7 @@ def _finish_restart(self): self.service.start(cfg) self._worker_config = cfg except RuntimeError as exc: + self._relinking_from = None self._notify(str(exc)) self._on_change() @@ -297,12 +334,30 @@ def drain_events(self): event = self.service.events.get_nowait() except queue.Empty: return changed - if event["history"]: + if event["history"] and not self._quiet_while_relinking(event): self.add_history( event["timestamp"], event["message"], event.get("code"), event.get("subject") ) changed = True + def _quiet_while_relinking(self, event): + """Whether a reconnect for saved settings leaves `event` out of the + history: the old link's plain stop, the new one's "connecting", and + the live scene when it hasn't changed. The saved line already says + MapHide is relinking.""" + if self._relinking_from is None: + return False + code = event.get("code") + if code == EVENT_STOPPED and event["message"] == STOPPED_MESSAGE: + return True + if code == EVENT_CONNECTING: + return True + if code in _NEWS_WHILE_RELINKING: + return False + before, self._relinking_from = self._relinking_from, None + # The scene ends the reconnect; anything else is news worth seeing. + return code == EVENT_SCENE and event.get("subject") == before + def add_history(self, timestamp, message, code=None, subject=None): self.history.append(HistoryEntry(timestamp, message, code, subject)) del self.history[:-HISTORY_LINE_COUNT] @@ -316,6 +371,7 @@ def begin_exit(self, on_finished): if self.exit_requested: return False self.exit_requested = True + self._relinking_from = None self.service.stop() self._wait_for_service_stop(EXIT_WAIT_CEILING_MS, on_finished) return True diff --git a/maphide/fieldlog.py b/maphide/fieldlog.py index e162b17..a721255 100644 --- a/maphide/fieldlog.py +++ b/maphide/fieldlog.py @@ -13,6 +13,7 @@ HISTORY_NOTICE, HISTORY_SETTINGS_SAVED, HISTORY_UPDATE_AVAILABLE, + SUBJECT_RELINKING, ) from .obs import OBS_BAD_PASSWORD, OBS_LINK_LOST, OBS_OVERLAY_MAY_REMAIN, OBS_UNREACHABLE from .overlay import ( @@ -93,6 +94,8 @@ def _wording(entry): if code == EVENT_LOG_FAILED: return "> debug log couldn't start", WARNING if code == HISTORY_SETTINGS_SAVED: + if entry.subject == SUBJECT_RELINKING: + return "> settings saved · relinking", PLAIN return "> settings saved", PLAIN if code == HISTORY_DEFAULTS_RESTORED: return "> defaults restored", PLAIN diff --git a/tests/test_controller.py b/tests/test_controller.py index 38a4467..b44bfa7 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -14,14 +14,21 @@ HISTORY_LINE_COUNT, HISTORY_SETTINGS_SAVED, RESTART_POLL_INTERVAL_MS, + SUBJECT_RELINKING, AppController, HistoryEntry, ) from maphide.obs import ConnectionCheck from maphide.overlay import ( CONNECTED, + EVENT_CONNECT_FAILED, + EVENT_CONNECTED, + EVENT_CONNECTING, + EVENT_OVERLAY_HIDDEN, EVENT_SCENE, + EVENT_STOPPED, STOPPED, + STOPPED_MESSAGE, STOPPING, ObsSnapshot, ServiceStatus, @@ -586,3 +593,117 @@ def test_starting_puts_the_started_settings_into_effect(h): h.controller.start(make_config(hotkey="M")) assert h.controller.running_config == make_config(hotkey="M") + + +# Saving while connected: a quiet reconnect in the history. + + +def connected_in(h, scene="Gameplay"): + h.controller.start(make_config()) + h.service.status = ServiceStatus(CONNECTED, "Connected to OBS.") + h.service.snapshot = ObsSnapshot(scene=scene) + + +def relink(h, *events): + """The old worker finishes stopping, the new one starts and reports + `events` as (code, message, subject).""" + h.service.emit(STOPPED_MESSAGE, code=EVENT_STOPPED) + h.service.finish_stopping() + while h.schedule.pending: + h.schedule.run_next() + for code, message, subject in events: + h.service.emit(message, code=code, subject=subject) + h.controller.drain_events() + + +def lines(h): + return [(entry.code, entry.subject) for entry in h.controller.history] + + +def test_saving_while_connected_shows_one_saved_line_then_link_up(h): + connected_in(h) + + h.controller.save(make_config(hotkey="M")) + relink( + h, + (EVENT_CONNECTING, "Connecting to OBS...", None), + (EVENT_CONNECTED, "Connected to OBS.", None), + (EVENT_SCENE, "Live scene: Gameplay", "Gameplay"), + ) + + assert lines(h) == [(HISTORY_SETTINGS_SAVED, SUBJECT_RELINKING), (EVENT_CONNECTED, None)] + + +def test_a_scene_that_changed_meanwhile_is_still_shown(h): + connected_in(h) + + h.controller.save(make_config(hotkey="M")) + relink( + h, + (EVENT_CONNECTING, "Connecting to OBS...", None), + (EVENT_CONNECTED, "Connected to OBS.", None), + (EVENT_SCENE, "Live scene: Camera", "Camera"), + ) + + assert lines(h)[-1] == (EVENT_SCENE, "Camera") + + +def test_a_problem_while_relinking_is_always_shown(h): + connected_in(h) + + h.controller.save(make_config(hotkey="M")) + relink( + h, + (EVENT_CONNECTING, "Connecting to OBS...", None), + (EVENT_CONNECT_FAILED, "Failed to connect to OBS.", None), + (EVENT_CONNECTING, "Connecting to OBS...", None), + ) + + # Quiet ends at the problem: the retry after it is shown too. + assert lines(h) == [ + (HISTORY_SETTINGS_SAVED, SUBJECT_RELINKING), + (EVENT_CONNECT_FAILED, None), + (EVENT_CONNECTING, None), + ] + + +def test_other_news_while_relinking_is_shown(h): + connected_in(h) + + h.controller.save(make_config(hotkey="M")) + h.service.emit("Overlay hidden.", code=EVENT_OVERLAY_HIDDEN) + relink(h, (EVENT_CONNECTED, "Connected to OBS.", None)) + + assert (EVENT_OVERLAY_HIDDEN, None) in lines(h) + + +def test_once_relinked_the_history_is_back_to_normal(h): + connected_in(h) + h.controller.save(make_config(hotkey="M")) + relink( + h, + (EVENT_CONNECTED, "Connected to OBS.", None), + (EVENT_SCENE, "Live scene: Gameplay", "Gameplay"), + ) + + h.controller.stop() + h.service.emit(STOPPED_MESSAGE, code=EVENT_STOPPED) + h.controller.drain_events() + + assert lines(h)[-1] == (EVENT_STOPPED, None) + + +def test_saving_while_stopped_is_a_plain_saved_line(h): + h.controller.save(make_config(hotkey="M")) + + assert lines(h) == [(HISTORY_SETTINGS_SAVED, None)] + + +def test_reset_during_a_relink_still_shows_the_stop(h): + connected_in(h) + h.controller.save(make_config(hotkey="M")) + + h.controller.restore_defaults() + relink(h) + + assert lines(h)[-1] == (EVENT_STOPPED, None) diff --git a/tests/test_fieldlog.py b/tests/test_fieldlog.py index 049921f..7f4ce9a 100644 --- a/tests/test_fieldlog.py +++ b/tests/test_fieldlog.py @@ -4,6 +4,7 @@ HISTORY_DEFAULTS_RESTORED, HISTORY_NOTICE, HISTORY_SETTINGS_SAVED, + SUBJECT_RELINKING, HistoryEntry, ) from maphide.fieldlog import COVERED, LINKED, PLAIN, WARNING, FieldLine, field_line @@ -89,6 +90,13 @@ def line(code, message="", subject=None): WARNING, ), (HISTORY_SETTINGS_SAVED, "Config saved.", None, "> settings saved", PLAIN), + ( + HISTORY_SETTINGS_SAVED, + "Config saved.", + SUBJECT_RELINKING, + "> settings saved · relinking", + PLAIN, + ), (HISTORY_DEFAULTS_RESTORED, "Defaults restored.", None, "> defaults restored", PLAIN), (HISTORY_NOTICE, "OBS Host is required.", None, "> OBS Host is required.", WARNING), ], From 96b2c32c9ba6438de5f7e628a80347c1f7b07d67 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:29:36 -0500 Subject: [PATCH 18/31] Check the OBS port is between 1 and 65535 --- CHANGELOG.md | 2 ++ maphide/config.py | 7 +++++-- tests/test_config.py | 7 +++++++ tests/test_controller.py | 8 ++++++++ 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26a8a64..3640026 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,8 @@ All notable changes to MapHide are documented here. or MapHide goes to the tray, so they never stay shown on stream. - Fixed MapHide only saying it stopped, when you pressed Stop while it was reconnecting and the overlay might still be showing in OBS. +- Fixed Settings accepting an OBS port outside 1 to 65535, which could never + connect. It now says the port must be in that range. ## v0.2.6 - 2026-10-27 diff --git a/maphide/config.py b/maphide/config.py index b0fb25e..74aae0b 100644 --- a/maphide/config.py +++ b/maphide/config.py @@ -172,7 +172,7 @@ def connection_from_form(host, port): """The OBS host and port from a settings form, as typed: (host, port). Raises ValueError with a message fit to show the user when either is - missing or the port isn't a number. + missing, or the port isn't a number from MIN_PORT to MAX_PORT. """ host = str(host).strip() port_text = str(port).strip() @@ -181,9 +181,12 @@ def connection_from_form(host, port): if not port_text: raise ValueError("OBS Port is required.") try: - return host, int(port_text) + port_number = int(port_text) except ValueError as exc: raise ValueError("OBS Port must be a number.") from exc + if not MIN_PORT <= port_number <= MAX_PORT: + raise ValueError(f"OBS Port must be between {MIN_PORT} and {MAX_PORT}.") + return host, port_number def config_from_form( diff --git a/tests/test_config.py b/tests/test_config.py index 7665623..4c1ac83 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -228,6 +228,8 @@ def test_a_filled_in_form_becomes_settings(): ("scene_item_name", "", "Overlay Source is required."), ("hotkey", "ESC", "Show key supports A-Z."), ("port", "44a5", "OBS Port must be a number."), + ("port", "0", "OBS Port must be between 1 and 65535."), + ("port", "70000", "OBS Port must be between 1 and 65535."), ], ) def test_a_form_with_a_problem_says_what_to_fix(field, value, message): @@ -235,6 +237,11 @@ def test_a_form_with_a_problem_says_what_to_fix(field, value, message): config_from_form(**{**FORM, field: value}) +@pytest.mark.parametrize("port", ["1", "65535"]) +def test_the_lowest_and_highest_ports_are_accepted(port): + assert config_from_form(**{**FORM, "port": port}).port == int(port) + + def test_toggle_mode_needs_a_usable_hide_key(): with pytest.raises(ValueError, match="Hide key supports"): config_from_form(**{**FORM, "toggle_mode": True, "hide_hotkey": "CTRL"}) diff --git a/tests/test_controller.py b/tests/test_controller.py index b44bfa7..267f2b4 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -520,6 +520,14 @@ def test_a_connection_check_with_an_unusable_port_says_so_without_trying(h): assert controller.checking_connection is False +def test_test_link_refuses_a_port_out_of_range_without_trying(h): + controller = AppController(schedule=h.schedule, service=h.service, check=None) + + with pytest.raises(ValueError, match="between 1 and 65535"): + controller.check_connection("10.0.0.2", "70000", "", "", lambda _result: None) + assert controller.checking_connection is False + + def test_only_one_connection_check_runs_at_a_time(h): release = threading.Event() From 9e3940950a16b6de18d3e5e4d2c79c5e230e764c Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:50:53 -0500 Subject: [PATCH 19/31] Give each OBS failure its own reason in the field log --- maphide/fieldlog.py | 18 ++++++++++++++++-- tests/test_fieldlog.py | 8 ++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/maphide/fieldlog.py b/maphide/fieldlog.py index a721255..1c3fcea 100644 --- a/maphide/fieldlog.py +++ b/maphide/fieldlog.py @@ -15,7 +15,16 @@ HISTORY_UPDATE_AVAILABLE, SUBJECT_RELINKING, ) -from .obs import OBS_BAD_PASSWORD, OBS_LINK_LOST, OBS_OVERLAY_MAY_REMAIN, OBS_UNREACHABLE +from .obs import ( + OBS_BAD_PASSWORD, + OBS_BAD_REPLY, + OBS_LINK_LOST, + OBS_OVERLAY_MAY_REMAIN, + OBS_READ_REFUSED, + OBS_SETTINGS_WRONG, + OBS_UNREACHABLE, + OBS_WRITE_REFUSED, +) from .overlay import ( EVENT_CONNECT_FAILED, EVENT_CONNECTED, @@ -43,7 +52,11 @@ _FAILURE_REASONS = { OBS_BAD_PASSWORD: "wrong password", OBS_UNREACHABLE: "obs not answering", + OBS_SETTINGS_WRONG: "check host and port", OBS_LINK_LOST: "link lost", + OBS_READ_REFUSED: "obs refused a request", + OBS_WRITE_REFUSED: "obs refused a change", + OBS_BAD_REPLY: "unreadable reply from obs", } @@ -57,7 +70,8 @@ class FieldLine: def _reason(message): if message.startswith("MapHide stopped after an unexpected error"): return "unexpected error" - return _FAILURE_REASONS.get(message, "check host and port") + # Not a guess at the cause: the debug log has the full message. + return _FAILURE_REASONS.get(message, "obs error") def _wording(entry): diff --git a/tests/test_fieldlog.py b/tests/test_fieldlog.py index 7f4ce9a..aba4bc1 100644 --- a/tests/test_fieldlog.py +++ b/tests/test_fieldlog.py @@ -10,10 +10,13 @@ from maphide.fieldlog import COVERED, LINKED, PLAIN, WARNING, FieldLine, field_line from maphide.obs import ( OBS_BAD_PASSWORD, + OBS_BAD_REPLY, OBS_LINK_LOST, OBS_OVERLAY_MAY_REMAIN, + OBS_READ_REFUSED, OBS_SETTINGS_WRONG, OBS_UNREACHABLE, + OBS_WRITE_REFUSED, ) from maphide.overlay import ( EVENT_CONNECT_FAILED, @@ -111,6 +114,11 @@ def test_each_entry_gets_its_field_log_wording(code, message, subject, text, ton (OBS_BAD_PASSWORD, "wrong password"), (OBS_UNREACHABLE, "obs not answering"), (OBS_SETTINGS_WRONG, "check host and port"), + (OBS_READ_REFUSED, "obs refused a request"), + (OBS_WRITE_REFUSED, "obs refused a change"), + (OBS_BAD_REPLY, "unreadable reply from obs"), + (OBS_LINK_LOST, "link lost"), + ("Something MapHide has no words for.", "obs error"), ], ) def test_a_failed_connection_says_why(message, reason): From 6130043c2f963ec68bc7f018d007af9ec7fa3147 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:40:47 -0500 Subject: [PATCH 20/31] Drop an oversized command and say when a second launch can't reach MapHide --- maphide/qt/app.py | 11 +++++++++++ tests/test_qt_commands.py | 32 +++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/maphide/qt/app.py b/maphide/qt/app.py index 37a61b6..3e25201 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -57,6 +57,9 @@ UPDATE_CHECK_DELAY_MS = 3000 CONFIG_NOT_LOADED = "Settings couldn't be read, so the defaults are in use." NO_TRAY = "No notification area, so closing the window will exit MapHide." +NO_COMMANDS = "Opening MapHide again can't bring this window forward." +# The most a second launch's command can take before its line break. +MAX_COMMAND_BYTES = 256 # How long to wait, when Windows is signing out or shutting down, for the # worker to hide the overlay. Windows gives an app about five seconds before # ending it regardless. @@ -724,6 +727,10 @@ def _read(self, connection): handler = self._handlers.get(line) if handler is not None: handler() + # A command is one short word. Whatever sends this much without a + # line break isn't MapHide, so stop holding what it sends. + if connection.bytesAvailable() > MAX_COMMAND_BYTES: + connection.abort() def close(self): self._server.close() @@ -804,6 +811,10 @@ def show_window(): backend.load() if tray is None: backend.notice(NO_TRAY) + if not commands.listening: + # A second launch then can't reach this one, and shows the "already + # running" notice after a few seconds instead. + backend.notice(NO_COMMANDS) # Shown only now, so it appears with its theme's title bar already set. paint_title_bar() screen_fit = ScreenFit(window) diff --git a/tests/test_qt_commands.py b/tests/test_qt_commands.py index 4a85ef9..e244eb5 100644 --- a/tests/test_qt_commands.py +++ b/tests/test_qt_commands.py @@ -14,7 +14,7 @@ from PySide6.QtGui import QGuiApplication # noqa: E402 from maphide.qt.app import CommandServer # noqa: E402 -from maphide.single_instance import send_command # noqa: E402 +from maphide.single_instance import PIPE_PREFIX, send_command # noqa: E402 ROOT = Path(__file__).resolve().parent.parent @@ -88,3 +88,33 @@ def test_a_copy_that_has_stopped_responding_does_not_hang_the_launch(server): assert not delivered assert time.monotonic() - started < 2 + + +def test_a_connection_that_never_ends_its_line_is_dropped(qt_app): + received = [] + name = f"MapHide-Test-{uuid.uuid4().hex}" + server = CommandServer( + name, on_show=lambda: received.append("show"), on_quit=lambda: received.append("quit") + ) + # Writes far more than a command, with no line break, then holds the + # connection open instead of hanging up. + code = ( + "import sys, time; " + "pipe = open(sys.argv[1], 'wb', buffering=0); " + "pipe.write(b'x' * 5000); time.sleep(5)" + ) + # A fixed command with no outside input. + flooder = subprocess.Popen( # noqa: S603 + [sys.executable, "-c", code, PIPE_PREFIX + name], cwd=ROOT + ) + try: + assert until(lambda: server._connections, seconds=5), "the flooder never connected" + assert until(lambda: not server._connections, seconds=3) + assert flooder.poll() is None, "dropped only because the sender gave up" + assert received == [] + + assert send("show", name) + assert until(lambda: received == ["show"]) + finally: + flooder.kill() + server.close() From 85f4ba1d13af00360af3a1033ed84ddf9f1555aa Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:45:05 -0500 Subject: [PATCH 21/31] Keep a hide delay drag on the slider when it drifts --- maphide/qt/Slider.qml | 3 +++ tests/test_qt_drawer.py | 52 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/maphide/qt/Slider.qml b/maphide/qt/Slider.qml index 61bac5d..4b61249 100644 --- a/maphide/qt/Slider.qml +++ b/maphide/qt/Slider.qml @@ -35,6 +35,9 @@ Item { MouseArea { anchors.fill: parent cursorShape: Qt.PointingHandCursor + // A drag that drifts up or down stays on the slider, instead of + // turning into scrolling the list it sits in. + preventStealing: true function pick(x) { const fraction = Math.max(0, Math.min(1, x / width)) const steps = Math.round(fraction * (slider.to - slider.from) / slider.step) diff --git a/tests/test_qt_drawer.py b/tests/test_qt_drawer.py index 26203b2..2902727 100644 --- a/tests/test_qt_drawer.py +++ b/tests/test_qt_drawer.py @@ -9,8 +9,8 @@ pytest.importorskip("PySide6") import PySide6.QtQuick # noqa: E402,F401 -from PySide6.QtCore import QEvent, QObject, Qt # noqa: E402 -from PySide6.QtGui import QGuiApplication, QKeyEvent # noqa: E402 +from PySide6.QtCore import QEvent, QObject, QPointF, Qt # noqa: E402 +from PySide6.QtGui import QGuiApplication, QKeyEvent, QMouseEvent # noqa: E402 from test_controller import FakeService # noqa: E402 from maphide.overlay import CONNECTED, RECONNECTING, ServiceStatus # noqa: E402 @@ -252,3 +252,51 @@ def test_hiding_maphide_to_the_tray_hides_them_too(setup): QGuiApplication.processEvents() assert [field.property("revealed") for field in fields] == [False, False, False] + + +# Dragging the hide delay slider. + + +def hide_delay_slider(window): + pending = [window.contentItem()] + while pending: + item = pending.pop(0) + if item.property("fraction") is not None and item.property("step") is not None: + return item + pending.extend(item.childItems()) + raise AssertionError("no slider") + + +def test_dragging_the_slider_off_course_never_scrolls_the_list(setup): + backend, window = setup + scroller = window.findChild(QObject, "settingsScroller") + slider = hide_delay_slider(window) + # Bring the slider into view, with room to drift up. + scroller.setProperty("contentY", 0) + QGuiApplication.processEvents() + top = slider.mapToItem(scroller, QPointF(0, 0)).y() + scroller.setProperty("contentY", max(0, top - scroller.height() / 2)) + QGuiApplication.processEvents() + scrolled_to = scroller.property("contentY") + before = backend.form["hide_delay_ms"] + + start = slider.mapToScene(QPointF(slider.width() * 0.3, slider.height() / 2)) + left, none = Qt.MouseButton.LeftButton, Qt.MouseButton.NoButton + keys = Qt.KeyboardModifier.NoModifier + QGuiApplication.sendEvent( + window, QMouseEvent(QEvent.Type.MouseButtonPress, start, start, left, left, keys) + ) + # Along the slider, drifting well up: the list would take that over. + for step in range(1, 21): + point = QPointF(start.x() + step * 6, start.y() - step * 8) + QGuiApplication.sendEvent( + window, QMouseEvent(QEvent.Type.MouseMove, point, point, left, left, keys) + ) + QGuiApplication.processEvents() + QGuiApplication.sendEvent( + window, QMouseEvent(QEvent.Type.MouseButtonRelease, point, point, left, none, keys) + ) + QGuiApplication.processEvents() + + assert scroller.property("contentY") == scrolled_to + assert backend.form["hide_delay_ms"] > before From 559cf5de748b031e87a45c42ff4628462cfde39c Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:49:44 -0500 Subject: [PATCH 22/31] Test that the OBS password never reaches a log --- tests/test_password_never_logged.py | 114 ++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 tests/test_password_never_logged.py diff --git a/tests/test_password_never_logged.py b/tests/test_password_never_logged.py new file mode 100644 index 0000000..27ee629 --- /dev/null +++ b/tests/test_password_never_logged.py @@ -0,0 +1,114 @@ +"""The OBS password never reaches a log: not the debug log, not anything a +log handler could pick up, and not the console. + +The OBS library itself logs the password on every connect, at info level. +MapHide turns that library's logging down to critical only; these tests +hold that in place, through MapHide's real connect code and the real +library.""" + +import logging +import socket +import time +from dataclasses import replace + +import pytest + +from maphide import logs +from maphide.config import default_config +from maphide.obs import ObsUnreachableError, connect_obs +from maphide.overlay import MapHideService + +SECRET = "pw-that-must-never-be-logged-7f3a" # noqa: S105 - a made-up test value + + +def closed_port(): + """A local port nothing listens on, so a connect fails at once.""" + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +class Everything(logging.Handler): + """Collects every record any logger lets through, at any level.""" + + def __init__(self): + super().__init__(logging.DEBUG) + self.lines = [] + + def emit(self, record): + self.lines.append(self.format(record)) + + +def set_level(logger, level): + """Set `logger`'s level, returning a way to put the old one back. + setLevel, not the attribute: logging caches levels and only setLevel + clears that.""" + old = logger.level + logger.setLevel(level) + return lambda: logger.setLevel(old) + + +@pytest.fixture +def captured(): + handler = Everything() + root = logging.getLogger() + restore = set_level(root, logging.DEBUG) + root.addHandler(handler) + # MapHide's own logger doesn't pass records up to the root. + logs.logger.addHandler(handler) + yield handler + root.removeHandler(handler) + logs.logger.removeHandler(handler) + restore() + + +def try_to_connect(): + with pytest.raises(ObsUnreachableError): + connect_obs("127.0.0.1", closed_port(), SECRET, timeout=1) + + +def test_connecting_never_logs_the_password(captured, capsys): + try_to_connect() + + assert not [line for line in captured.lines if SECRET in line] + assert SECRET not in capsys.readouterr().err + + +def test_the_check_above_would_catch_a_leak(captured): + # The library logs the password unless MapHide quiets it. + restore = set_level(logging.getLogger("obsws_python"), logging.DEBUG) + try: + try_to_connect() + finally: + restore() + + assert [line for line in captured.lines if SECRET in line] + + +def test_the_debug_log_never_holds_the_password(tmp_path, monkeypatch): + log_file = tmp_path / "maphide-debug.log" + monkeypatch.setattr(logs, "LOG_PATH", log_file) + cfg = replace( + default_config(), + host="127.0.0.1", + port=closed_port(), + password=SECRET, + scene_item_name="Overlay", + auto_reconnect=False, + log_enabled=True, + ) + service = MapHideService() + try: + service.start(cfg) + deadline = time.monotonic() + 10 + while service.is_running and time.monotonic() < deadline: + time.sleep(0.05) + assert not service.is_running + finally: + service.stop() + logs.configure_logging(False) + + written = log_file.read_text(encoding="utf-8") + # It did log the failed connection, just never the password. + assert "Failed to connect" in written + assert SECRET not in written From f52a7c2e4f99dbb48e47a1648015d8577b3e428b Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:58:25 -0500 Subject: [PATCH 23/31] Pin the Inno Setup version and test the names installer and app share --- .github/workflows/build.yml | 16 +++++++-- tests/test_shared_names.py | 71 +++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 tests/test_shared_names.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d77c97b..5396cc3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -163,11 +163,21 @@ jobs: id: installer shell: pwsh run: | - $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" - if (-not (Test-Path $iscc)) { - choco install innosetup --no-progress -y + # One known version builds every installer, whatever the runner + # image happens to come with. + $innoVersion = '6.7.1' + $innoDir = "${env:ProgramFiles(x86)}\Inno Setup 6" + $iscc = "$innoDir\ISCC.exe" + function Get-InnoVersion { + $uninstaller = "$innoDir\unins000.exe" + if (Test-Path $uninstaller) { (Get-Item $uninstaller).VersionInfo.ProductVersion.Trim() } else { '' } + } + if ((Get-InnoVersion) -ne $innoVersion) { + choco install innosetup --version $innoVersion --allow-downgrade --force --no-progress -y if ($LASTEXITCODE) { exit $LASTEXITCODE } } + $found = Get-InnoVersion + if ($found -ne $innoVersion) { throw "Inno Setup is $found, expected $innoVersion" } $appVersion = python -c "from maphide.version import VERSION; print(VERSION)" $name = 'MapHide-${{ steps.package.outputs.version }}-setup' & $iscc /Qp installer/MapHide.iss "/DAppVersion=$appVersion" "/DOutputName=$name" diff --git a/tests/test_shared_names.py b/tests/test_shared_names.py new file mode 100644 index 0000000..0a2bc25 --- /dev/null +++ b/tests/test_shared_names.py @@ -0,0 +1,71 @@ +"""Names the installer, the build workflow and MapHide must agree on. Each +is written in more than one place, and a mismatch fails only on someone's +PC: the installer can't see MapHide running, or the updater can't find the +setup file and every installed copy stays on its version.""" + +import re +from pathlib import Path + +from maphide.paths import APP_USER_MODEL_ID +from maphide.single_instance import MUTEX_NAME +from maphide.updates import INSTALLER_ARGUMENTS, REPO, SETUP_NAME, UNINSTALLER_NAME + +ROOT = Path(__file__).resolve().parent.parent +INSTALLER = (ROOT / "installer" / "MapHide.iss").read_text(encoding="utf-8") +WORKFLOW = (ROOT / ".github" / "workflows" / "build.yml").read_text(encoding="utf-8") +ENTRY_POINT = (ROOT / "map_hider.py").read_text(encoding="utf-8") + + +def installer_define(name): + match = re.search(rf'^#define {name} "([^"]*)"', INSTALLER, re.MULTILINE) + assert match, f"{name} isn't defined in MapHide.iss" + return match.group(1) + + +def test_the_installer_watches_the_lock_maphide_holds(): + # The .iss writes one backslash where Python's string escapes it. + assert installer_define("AppMutexName") == MUTEX_NAME + + +def test_shortcuts_carry_the_app_id_maphide_runs_under(): + assert installer_define("AppUserModelID") == APP_USER_MODEL_ID + + +def test_the_setup_file_ci_publishes_is_one_the_updater_finds(): + template = re.search( + r"\$name = '(MapHide-\$\{\{ steps\.package\.outputs\.version \}\}-setup)'", WORKFLOW + ) + assert template, "the setup file name line in build.yml changed" + published = ( + template.group(1).replace("${{ steps.package.outputs.version }}", "v1.2.3") + ".exe" + ) + + match = SETUP_NAME.fullmatch(published) + + assert match, f"the updater won't recognise {published}" + assert match.group(1) == "1.2.3" + + +def test_the_workflow_names_releases_by_their_tag(): + # A release's version is its tag, as the updater reads it. + assert "$version = '${{ github.ref_name }}'" in WORKFLOW + + +def test_the_installer_reopens_maphide_when_the_updater_asks(): + assert "/RELAUNCH=1" in INSTALLER_ARGUMENTS + assert "{param:RELAUNCH|0}" in INSTALLER + + +def test_the_installer_closes_maphide_the_way_maphide_understands(): + assert "Exec(ExePath, '--quit'" in INSTALLER + assert '"--quit" in sys.argv' in ENTRY_POINT + + +def test_the_uninstaller_keeps_the_name_that_marks_an_installed_copy(): + # Inno Setup names it unins000.exe in the app folder unless told otherwise. + assert UNINSTALLER_NAME == "unins000.exe" + assert not re.search(r"^\s*UninstallFilesDir\s*=", INSTALLER, re.MULTILINE) + + +def test_the_installer_points_at_the_repository_the_updater_reads(): + assert f"AppUpdatesURL=https://github.com/{REPO}/releases" in INSTALLER From 7da3dc923d5107e3a69e93cc088feab715c8c9f7 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:02:50 -0500 Subject: [PATCH 24/31] Correct the download size in the changelog and reword a comment --- CHANGELOG.md | 3 ++- maphide/overlay.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3640026..4ae888f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,8 @@ All notable changes to MapHide are documented here. - Changed the empty-password warning to text next to the Password field instead of an icon. - Changed the debug log option to a switch under Behavior in Settings. -- Changed the download size to about 35 MB, because of the new window. +- Changed the download size to about 27 MB for the installer, or 35 MB for the + zip, because of the new window. - Added Enter and Esc as ways to finish typing in a text field. - Changed launching MapHide while it's already running to bring the open window to the front, even from the tray, instead of showing a notice. diff --git a/maphide/overlay.py b/maphide/overlay.py index abf8d61..6c55870 100644 --- a/maphide/overlay.py +++ b/maphide/overlay.py @@ -194,7 +194,7 @@ def recheck_missing_source(client, scene_items, scene_name, source_name): def scene_status(scene_name, is_first_detection=False): # No hotkey/mode explanation here: the window shows that on its own, and - # repeating it made this line far too long for the space. + # this line has to fit a narrow space. verb = "New scene detected" if is_first_detection else "Switched to scene" return f"{verb}: {scene_name}." From ed502478ff1654960e6dce0e015d2cb0011cdc36 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:06:59 -0500 Subject: [PATCH 25/31] Remove unused colour constants, QML ids and font weights --- maphide/qt/Main.qml | 7 ++----- maphide/themes.py | 5 ----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/maphide/qt/Main.qml b/maphide/qt/Main.qml index 41bc0d9..0e6a360 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -8,6 +8,8 @@ Window { readonly property var t: backend.theme readonly property string st: backend.screen readonly property bool running: backend.primaryIsStop + // The red X and the COVERED stamp are part of the logo, not the theme, + // so they stay the same whichever theme is chosen. readonly property color coverRed: "#d9483b" readonly property color coverRedText: "#ff7a6b" property bool drawerOpen: false @@ -72,11 +74,9 @@ Window { function em(size, amount) { return size * amount } Item { - id: stage anchors.fill: parent Item { - id: main anchors.fill: parent transformOrigin: Item.Left scale: win.drawerOpen ? 0.965 : 1 @@ -204,7 +204,6 @@ Window { Condensed { text: ["OBS LINK", "LIVE SCENE", "MODE"][cell.index] font.pixelSize: 12 - font.weight: Font.Normal font.letterSpacing: win.em(12, 0.14) color: win.t.muted } @@ -558,7 +557,6 @@ Window { y: 10 text: "FIELD LOG" font.pixelSize: 13 - font.weight: Font.Normal font.letterSpacing: win.em(13, 0.16) color: win.t.muted } @@ -722,7 +720,6 @@ Window { // Settings drawer: slides in over the main screen. Rectangle { - id: drawer objectName: "drawer" width: 436 height: parent.height diff --git a/maphide/themes.py b/maphide/themes.py index cf1a69a..391a660 100644 --- a/maphide/themes.py +++ b/maphide/themes.py @@ -7,11 +7,6 @@ from dataclasses import dataclass -# The red X and the COVERED stamp are part of the logo, not the theme, so -# they stay the same whichever theme is chosen. -COVER_RED = "#d9483b" -COVER_RED_TEXT = "#ff7a6b" - @dataclass(frozen=True) class Theme: From 03c1bcafe59941109b8eb2eacabe32efcc7af91c Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:51:37 -0500 Subject: [PATCH 26/31] Test Connect on startup and tidy weak or misnamed tests --- maphide/qt/app.py | 2 +- tests/test_overlay.py | 45 +++++++++++++++++++++++++--------------- tests/test_qt_backend.py | 31 +++++++++++++++++++++++++++ tests/test_state.py | 16 +------------- 4 files changed, 61 insertions(+), 33 deletions(-) diff --git a/maphide/qt/app.py b/maphide/qt/app.py index 3e25201..6fb40ec 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -244,7 +244,7 @@ def load(self, **load_options): self.refresh() self._poll_timer.start() if cfg.auto_connect: - QTimer.singleShot(AUTO_CONNECT_DELAY_MS, self._start) + self._schedule(AUTO_CONNECT_DELAY_MS, self._start) if cfg.check_updates and self._update_checks: self._schedule(UPDATE_CHECK_DELAY_MS, self._check_quietly) diff --git a/tests/test_overlay.py b/tests/test_overlay.py index c91408d..50093a4 100644 --- a/tests/test_overlay.py +++ b/tests/test_overlay.py @@ -2,7 +2,7 @@ only the active scene while every other known scene still converges to the same value shortly after. -Two scenarios get a dedicated regression test: +Two scenarios get a dedicated test: - a key blip landing on the same poll as a detected scene switch must not leak into what gets written to OBS, and - a scene that isn't currently active must be caught up in the background @@ -380,10 +380,9 @@ def fail_fast(host, port, password): def test_a_mid_session_drop_updates_the_status_immediately(monkeypatch): - # Regression: the status line must reflect a lost OBS connection right - # away. Leaving the reconnect countdown to say so instead means the line - # can go on showing "Connected to OBS." for up to a full RECONNECT_TICK - # after the link has actually died. + # The status line reflects a lost OBS connection right away. Leaving the + # reconnect countdown to say so would let the line go on showing + # "Connected to OBS." for up to a full RECONNECT_TICK after the link died. connect_attempts = [] def fake_connect(host, port, password): @@ -427,7 +426,7 @@ def spying_emit(kind, code, message, **kwargs): def test_overlay_available_does_not_go_stale_once_the_only_carrying_scene_is_dropped( monkeypatch, ): - # Regression: catch_up_one_stale_scene can drop the one background scene + # catch_up_one_stale_scene can drop the one background scene # that actually carries the source (a rejected write - the scene was # deleted/renamed in OBS). If overlay_available isn't recomputed # afterward, MapHide keeps treating the overlay as available and can log @@ -472,7 +471,7 @@ def fake_poll_hotkey(vk_codes): def test_no_overlay_event_is_logged_when_the_active_scene_has_nothing_to_write_to( monkeypatch, ): - # Regression: overlay_available can be True from a source that only + # overlay_available can be True from a source that only # exists in a *different* scene - correctly, since sync_scene keeps that # background scene caught up. But sync_scene silently no-ops for the # active scene when it has nothing to write to, so logging "Overlay @@ -555,6 +554,25 @@ def fake_poll_hotkey(vk_codes): assert seeded.hide_key_was_down is False +def test_seed_key_edge_tracking_keeps_everything_but_the_key_edges(monkeypatch): + # A reconnect keeps the intent, what OBS was last told and a hide still + # counting down; only the key edges come from the fresh poll. + monkeypatch.setattr(overlay_module, "poll_hotkey", lambda vk_codes: (False, False)) + cfg = replace(hold_config(), toggle_mode=True) + before = OverlayState( + desired_visible=False, + overlay_visible=True, + last_action_time=datetime(2026, 1, 1, 12, 0, 0), + hide_requested_at=datetime(2026, 1, 1, 12, 0, 1), + show_key_was_down=True, + hide_key_was_down=True, + ) + + seeded = seed_key_edge_tracking(before, cfg, [1], [2]) + + assert seeded == replace(before, show_key_was_down=False, hide_key_was_down=False) + + def test_seed_key_edge_tracking_skips_the_hide_poll_in_hold_mode(monkeypatch): # Matches the same toggle_mode gate the main poll loop already uses - # hold mode never reads hide_key_was_down, so there is nothing to poll. @@ -738,7 +756,7 @@ def test_scene_status_reports_first_detection_separately(): assert scene_status("Gameplay", is_first_detection=True) == "New scene detected: Gameplay." -# --- regression: a blip during a scene switch must not leak into the write --- +# --- a blip during a scene switch must not leak into the write -------------- def test_a_hold_mode_blip_never_reaches_a_write_for_either_scene(): @@ -780,7 +798,7 @@ def test_a_hold_mode_blip_never_reaches_a_write_for_either_scene(): assert state.overlay_visible is False -# --- regression: a scene must be caught up before you switch back to it ----- +# --- a scene must be caught up before you switch back to it ----------------- def test_background_catch_up_fixes_a_stale_scene_before_you_return_to_it(): @@ -823,7 +841,7 @@ def test_background_catch_up_fixes_a_stale_scene_before_you_return_to_it(): ] -# --- regression: adding the source to the active scene needs no switch ----- +# --- adding the source to the active scene needs no switch ----------------- def test_source_added_to_the_active_scene_is_picked_up_without_a_switch(): @@ -913,13 +931,6 @@ def test_stops_the_instant_the_service_reports_not_running(): assert stop_wait_should_continue(False, CEILING * 10, CEILING) is False -def test_a_slow_multi_scene_cleanup_is_not_cut_short(): - # Still genuinely running after a few seconds, but comfortably inside the - # ceiling: it must be waited out. - still_running_at_3_seconds = True - assert stop_wait_should_continue(still_running_at_3_seconds, 3_000, CEILING) is True - - def test_stops_once_the_ceiling_is_reached_even_if_still_running(): # The backstop: quitting (GUI or headless) must still eventually finish # even if something someday blocks past its own timeouts. diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index 349b808..076005e 100644 --- a/tests/test_qt_backend.py +++ b/tests/test_qt_backend.py @@ -133,6 +133,37 @@ def broken(): assert h.lines[-1][1].startswith("> Settings couldn't be read") +def run_scheduled(h): + while h.schedule.pending: + h.schedule.run_next() + + +def test_connect_on_startup_starts_maphide_with_the_saved_settings(h): + h.load(lambda: make_config(host="10.0.0.9", auto_connect=True, check_updates=False)) + assert h.service.started_with == [] + + run_scheduled(h) + + assert [cfg.host for cfg in h.service.started_with] == ["10.0.0.9"] + + +def test_connect_on_startup_ignores_an_edit_made_before_it_starts(h): + h.load(lambda: make_config(host="10.0.0.9", auto_connect=True, check_updates=False)) + fill_form(h.backend, host="10.0.0.5") + + run_scheduled(h) + + assert [cfg.host for cfg in h.service.started_with] == ["10.0.0.9"] + + +def test_maphide_waits_for_start_when_connect_on_startup_is_off(h): + h.load(lambda: make_config(auto_connect=False, check_updates=False)) + + run_scheduled(h) + + assert h.service.started_with == [] + + # The settings form. diff --git a/tests/test_state.py b/tests/test_state.py index e55567b..8267f59 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -337,20 +337,6 @@ def test_holding_the_hide_key_does_not_rehide_after_a_later_show_even_if_pressed # --- state carried across a dropped connection ------------------------------- -def test_intent_survives_a_reconnect_reset(): - # What the worker keeps when the link drops: the intent, what OBS was - # last told, and a hide already counting down - only the key-edge - # tracking (meaningless after a polling gap) is reset. See overlay.py. - cfg = hold_config() - state, _ = drive(cfg, [(0, True, False)]) - assert state.desired_visible is True - assert state.overlay_visible is True - - reconnected = replace(state, show_key_was_down=False, hide_key_was_down=False) - assert reconnected.desired_visible is True - assert reconnected.overlay_visible is True - - def test_a_hide_already_pending_at_reconnect_still_lands(): # Release the key so a hide is armed but not yet fired, then apply the # same reset overlay.py runs on every (re)connect. The key never comes @@ -410,7 +396,7 @@ def test_holding_the_show_key_through_a_reconnect_is_safe_for_separate_keys(): assert actions == [] -def test_holding_the_hide_key_through_a_reconnect_falsely_hides_for_separate_keys(): +def test_holding_the_hide_key_through_a_reconnect_does_not_hide_for_separate_keys(): # H being held doesn't have to mean the user pressed it to hide - it # could be bound to something else entirely (Shift for sprint, say) and # just happen to be down at the exact moment of a reconnect. A real poll From 1839d8f7d6096e0752c3fdc1ca9c9d228f448d8e Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:06:10 -0500 Subject: [PATCH 27/31] Keep an install from being cancelled halfway --- installer/MapHide.iss | 3 +++ tests/test_installer_script.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 tests/test_installer_script.py diff --git a/installer/MapHide.iss b/installer/MapHide.iss index fd45d7b..4c57b12 100644 --- a/installer/MapHide.iss +++ b/installer/MapHide.iss @@ -54,6 +54,9 @@ SolidCompression=yes ; MapHide is closed with --quit below, which hides the overlay in OBS first. CloseApplications=no RestartApplications=no +; The old version's files are deleted before the new ones are copied (see +; [InstallDelete]), so a cancel in between would leave MapHide unable to start. +AllowCancelDuringInstall=no [Languages] Name: "english"; MessagesFile: "compiler:Default.isl" diff --git a/tests/test_installer_script.py b/tests/test_installer_script.py new file mode 100644 index 0000000..0076a84 --- /dev/null +++ b/tests/test_installer_script.py @@ -0,0 +1,21 @@ +"""Settings in the installer script that keep an install or update from +leaving MapHide unable to start.""" + +import re +from pathlib import Path + +INSTALLER = (Path(__file__).resolve().parent.parent / "installer" / "MapHide.iss").read_text( + encoding="utf-8" +) + + +def setup_directive(name): + match = re.search(rf"^{name}=(.*)$", INSTALLER, re.MULTILINE) + return match.group(1).strip() if match else None + + +def test_an_install_cant_be_cancelled_halfway(): + # The old program files are deleted before the new ones are copied, so + # stopping in between would leave a MapHide that can't start. + assert setup_directive("AllowCancelDuringInstall") == "no" + assert 'Type: filesandordirs; Name: "{app}\\_internal"' in INSTALLER From 9366990005c1b75b02425a51299d4a56726a7eaf Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:10:59 -0500 Subject: [PATCH 28/31] Start the update installer from its own folder with a clean environment --- maphide/updates.py | 21 +++++++++++++++++- tests/test_updates.py | 51 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/maphide/updates.py b/maphide/updates.py index 5cfdcca..5aff6cf 100644 --- a/maphide/updates.py +++ b/maphide/updates.py @@ -10,6 +10,7 @@ import hashlib import json +import os import re import subprocess import sys @@ -214,6 +215,18 @@ def _reset_dll_folder(): ctypes.windll.kernel32.SetDllDirectoryW(None) +def _installer_environment(): + # The packaged app keeps notes for itself in _PYI_ variables, which + # programs it starts would inherit: the installer, and through it the + # MapHide it reopens. Left out, and PyInstaller told to start afresh, so + # the new version finds its own files. + env = { + name: value for name, value in os.environ.items() if not name.upper().startswith("_PYI_") + } + env["PYINSTALLER_RESET_ENVIRONMENT"] = "1" + return env + + def launch_installer( path, popen=subprocess.Popen, frozen=None, reset_dll_folder=_reset_dll_folder ): @@ -222,8 +235,14 @@ def launch_installer( frozen = getattr(sys, "frozen", False) if frozen is None else frozen if frozen: reset_dll_folder() + path = Path(path) try: - popen([str(path), *INSTALLER_ARGUMENTS], close_fds=True) + popen( + [str(path), *INSTALLER_ARGUMENTS], + close_fds=True, + env=_installer_environment(), + cwd=str(path.parent), + ) except OSError as exc: raise UpdateError(INSTALLER_DIDNT_START) from exc diff --git a/tests/test_updates.py b/tests/test_updates.py index a146d55..4ac4eef 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -3,6 +3,7 @@ import hashlib import io import json +import time import urllib.error import urllib.request @@ -307,6 +308,56 @@ def test_the_installer_runs_with_progress_only_and_reopens_maphide(tmp_path): assert "/SILENT" in launched[0] and "/RELAUNCH=1" in launched[0] +def test_the_installer_and_the_maphide_it_reopens_start_clean(tmp_path, monkeypatch): + # The packaged app's own settings for its files must not reach the + # installer, nor through it the --quit and the reopened MapHide. + monkeypatch.setenv("_PYI_APPLICATION_HOME_DIR", r"C:\old\_internal") + monkeypatch.setenv("_PYI_ARCHIVE_FILE", r"C:\old\MapHide.exe") + monkeypatch.setenv("MAPHIDE_TEST_KEEP", "kept") + started = [] + + launch_installer(tmp_path / "setup.exe", lambda args, **options: started.append(options)) + + env = started[0]["env"] + assert env["PYINSTALLER_RESET_ENVIRONMENT"] == "1" + assert not [name for name in env if name.upper().startswith("_PYI_")] + assert env["MAPHIDE_TEST_KEEP"] == "kept" + + +def test_the_installer_starts_in_its_own_folder(tmp_path): + started = [] + + launch_installer(tmp_path / "setup.exe", lambda args, **options: started.append(options)) + + assert started[0]["cwd"] == str(tmp_path) + + +def test_a_real_installer_gets_the_clean_start(tmp_path, monkeypatch): + # A stand-in installer that writes down what it was started with. + monkeypatch.setenv("_PYI_ARCHIVE_FILE", r"C:\old\MapHide.exe") + seen = tmp_path / "seen.txt" + setup = tmp_path / "setup.cmd" + setup.write_text( + f'@echo %CD%^|%PYINSTALLER_RESET_ENVIRONMENT%^|%_PYI_ARCHIVE_FILE%> "{seen}"\r\n', + encoding="ascii", + ) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + monkeypatch.chdir(elsewhere) + + launch_installer(setup, frozen=False) + + for _ in range(100): + if seen.exists() and seen.read_text(encoding="ascii").strip(): + break + time.sleep(0.05) + folder, reset, archive = seen.read_text(encoding="ascii").strip().split("|") + assert folder == str(tmp_path) + assert reset == "1" + # Empty: in a batch file, an unset variable expands to nothing. + assert archive == "" + + def test_an_installer_that_wont_start_is_explained(tmp_path): def popen(args, **_): raise FileNotFoundError From 3a3022dbc1878c63653f6dd68172f31f635f3fc6 Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:13:36 -0500 Subject: [PATCH 29/31] Retry a settings save while another program holds the file --- maphide/config.py | 22 +++++++++++++++++++- tests/test_config.py | 49 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/maphide/config.py b/maphide/config.py index 74aae0b..c990e2f 100644 --- a/maphide/config.py +++ b/maphide/config.py @@ -3,6 +3,7 @@ import json import os import shutil +import time from dataclasses import dataclass, replace from .hotkeys import ( @@ -24,6 +25,10 @@ MAX_HIDE_DELAY_MS = 400 MIN_PORT = 1 MAX_PORT = 65535 +# How long a save keeps trying while another program has the settings file +# open, and how often. +SAVE_RETRY_SECONDS = 1.0 +SAVE_RETRY_INTERVAL_SECONDS = 0.05 # Settings only the window uses. Changing these never needs the worker # restarted, so saving them leaves the OBS connection and the overlay alone. WINDOW_ONLY_FIELDS = frozenset({"auto_connect", "theme", "check_updates"}) @@ -255,6 +260,21 @@ def load_config(path=CONFIG_PATH): return AppConfig.from_dict(json.load(file)) +def _replace_when_free(source, target): + """Swap `source` in for `target`. While another program has `target` + open, such as a virus scanner checking it, Windows refuses; that + usually lasts a moment, so try again for up to about a second.""" + deadline = time.monotonic() + SAVE_RETRY_SECONDS + while True: + try: + os.replace(source, target) + return + except PermissionError: + if time.monotonic() >= deadline: + raise + time.sleep(SAVE_RETRY_INTERVAL_SECONDS) + + def save_config(cfg, path=CONFIG_PATH): """Write `cfg` to a temporary file next to `path`, then swap it in, so a crash or power cut mid-save leaves the old settings, never half a file.""" @@ -265,7 +285,7 @@ def save_config(cfg, path=CONFIG_PATH): json.dump(cfg.to_dict(), file, indent=2) file.flush() os.fsync(file.fileno()) - os.replace(temporary, path) + _replace_when_free(temporary, path) except BaseException: temporary.unlink(missing_ok=True) raise diff --git a/tests/test_config.py b/tests/test_config.py index 4c1ac83..c13b875 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,6 +1,7 @@ """Tests for loading, saving, and sanitising the config file.""" import json +import threading import pytest @@ -154,6 +155,54 @@ def dump_then_fail(data, file, **_options): assert [p.name for p in tmp_path.iterdir()] == ["config.json"] +def test_a_save_waits_out_something_holding_the_file_for_a_moment(tmp_path): + # Python opens files without letting them be replaced, as a virus + # scanner or backup tool reading the file would. + path = tmp_path / "config.json" + save_config(default_config(), path) + new = AppConfig.from_dict({**default_config().to_dict(), "host": "192.168.1.9"}) + held = open(path, "rb") # noqa: SIM115 - closed by the timer below + release = threading.Timer(0.2, held.close) + release.start() + try: + save_config(new, path) + finally: + release.join() + held.close() + + assert load_config(path) == new + assert [p.name for p in tmp_path.iterdir()] == ["config.json"] + + +def test_a_file_held_for_good_still_fails_and_keeps_the_old_settings(tmp_path, monkeypatch): + path = tmp_path / "config.json" + old = AppConfig.from_dict({**default_config().to_dict(), "host": "10.0.0.5"}) + save_config(old, path) + monkeypatch.setattr(config_module, "SAVE_RETRY_SECONDS", 0.01) + new = AppConfig.from_dict({**default_config().to_dict(), "host": "192.168.1.9"}) + + with open(path, "rb"), pytest.raises(PermissionError): + save_config(new, path) + + assert load_config(path) == old + assert [p.name for p in tmp_path.iterdir()] == ["config.json"] + + +def test_only_a_file_in_use_is_retried(tmp_path, monkeypatch): + path = tmp_path / "config.json" + attempts = [] + + def full_disk(source, target): + attempts.append(1) + raise OSError("disk full") + + monkeypatch.setattr(config_module.os, "replace", full_disk) + + with pytest.raises(OSError, match="disk full"): + save_config(default_config(), path) + assert len(attempts) == 1 + + def test_a_save_leaves_no_temporary_file_behind(tmp_path): path = tmp_path / "config.json" From 23da9227f8a7f46b63d589f4e167356a096b78cf Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:17:27 -0500 Subject: [PATCH 30/31] Clear out old update downloads on every launch and on uninstall --- .github/workflows/build.yml | 5 ++++ installer/MapHide.iss | 1 + maphide/qt/app.py | 8 +++++-- maphide/updates.py | 16 +++++++++++++ tests/test_installer_script.py | 17 ++++++++++++-- tests/test_qt_backend.py | 26 +++++++++++++++++++++ tests/test_updates.py | 42 ++++++++++++++++++++++++++++++++++ 7 files changed, 111 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5396cc3..c4f89fb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -195,11 +195,16 @@ jobs: $p = Start-Process "$app\MapHide.exe" '--selftest' -PassThru if (-not $p.WaitForExit(60000)) { $p.Kill(); throw 'Installed MapHide.exe --selftest timed out' } if ($p.ExitCode -ne 0) { throw "Installed MapHide.exe --selftest exited $($p.ExitCode)" } + # A download left from an update, which uninstalling removes. + $downloads = Join-Path $env:TEMP 'MapHide-update' + New-Item -ItemType Directory -Force -Path $downloads | Out-Null + Set-Content -Path "$downloads\MapHide-v9.9.9-setup.exe" -Value 'leftover' $p = Start-Process "$app\unins000.exe" '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART' -PassThru -Wait if ($p.ExitCode -ne 0) { throw "Uninstall exited $($p.ExitCode)" } # The uninstaller removes its own copy a moment after it exits. Start-Sleep -Seconds 3 if (Test-Path "$app\MapHide.exe") { throw 'Uninstall left MapHide.exe behind' } + if (Test-Path $downloads) { throw 'Uninstall left the update downloads behind' } - name: Upload build artifact uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/installer/MapHide.iss b/installer/MapHide.iss index 4c57b12..e26d7fc 100644 --- a/installer/MapHide.iss +++ b/installer/MapHide.iss @@ -83,6 +83,7 @@ Filename: "{app}\MapHide.exe"; Flags: nowait; Check: RelaunchRequested [UninstallDelete] Type: filesandordirs; Name: "{app}\_internal" +Type: filesandordirs; Name: "{%TEMP}\MapHide-update" [Code] var diff --git a/maphide/qt/app.py b/maphide/qt/app.py index 6fb40ec..242c1bf 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -245,8 +245,12 @@ def load(self, **load_options): self._poll_timer.start() if cfg.auto_connect: self._schedule(AUTO_CONNECT_DELAY_MS, self._start) - if cfg.check_updates and self._update_checks: - self._schedule(UPDATE_CHECK_DELAY_MS, self._check_quietly) + if self._update_checks: + # A check clears out earlier update downloads too; without one, + # they're cleared out anyway. Not at once: after an update, its + # installer may still be finishing. + later = self._check_quietly if cfg.check_updates else self.updater.tidy + self._schedule(UPDATE_CHECK_DELAY_MS, later) # Keeping the window current. diff --git a/maphide/updates.py b/maphide/updates.py index 5aff6cf..1eaa792 100644 --- a/maphide/updates.py +++ b/maphide/updates.py @@ -300,6 +300,22 @@ def __init__( self.release = None self.progress = 0.0 self.thread = None + self.tidy_thread = None + + def tidy(self): + """Delete earlier downloads, off the window's thread, for when + MapHide opens without checking. A check does this itself.""" + if self.busy: + return + + def run(): + try: + self._clean(self._folder) + except Exception: # noqa: S110 - a leftover file can wait + pass + + self.tidy_thread = threading.Thread(target=run, name="UpdaterTidy", daemon=True) + self.tidy_thread.start() @property def busy(self): diff --git a/tests/test_installer_script.py b/tests/test_installer_script.py index 0076a84..fcde624 100644 --- a/tests/test_installer_script.py +++ b/tests/test_installer_script.py @@ -1,9 +1,12 @@ -"""Settings in the installer script that keep an install or update from -leaving MapHide unable to start.""" +"""Settings in the installer script: what an install, update or uninstall +does to the files MapHide leaves on your PC.""" import re +import tempfile from pathlib import Path +from maphide.updates import download_folder + INSTALLER = (Path(__file__).resolve().parent.parent / "installer" / "MapHide.iss").read_text( encoding="utf-8" ) @@ -14,6 +17,16 @@ def setup_directive(name): return match.group(1).strip() if match else None +def test_uninstalling_removes_the_update_downloads(): + # The same folder the updater downloads into. + folder = download_folder() + assert folder.parent == Path(tempfile.gettempdir()) + assert ( + f'[UninstallDelete]\nType: filesandordirs; Name: "{{app}}\\_internal"\n' + f'Type: filesandordirs; Name: "{{%TEMP}}\\{folder.name}"\n' + ) in INSTALLER + + def test_an_install_cant_be_cancelled_halfway(): # The old program files are deleted before the new ones are copied, so # stopping in between would leave a MapHide that can't start. diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index 076005e..3993256 100644 --- a/tests/test_qt_backend.py +++ b/tests/test_qt_backend.py @@ -511,6 +511,32 @@ def test_no_check_at_startup_when_it_is_turned_off(h): assert h.backend.updateState == "idle" +def test_old_downloads_are_cleared_out_even_with_checks_turned_off(): + cleaned = [] + harness = Harness() + harness.backend.updater._clean = cleaned.append + harness.load(lambda: make_config(check_updates=False)) + assert cleaned == [] + + run_scheduled(harness) + harness.backend.updater.tidy_thread.join(timeout=5) + + assert cleaned == ["downloads"] + + +def test_a_store_copy_leaves_the_download_folder_alone(): + cleaned = [] + harness = Harness() + harness.backend._update_checks = False + harness.backend.updater._clean = cleaned.append + harness.load(lambda: make_config(check_updates=False)) + + run_scheduled(harness) + + assert harness.backend.updater.tidy_thread is None + assert cleaned == [] + + def test_a_store_copy_never_checks(): harness = Harness() harness.backend._update_checks = False diff --git a/tests/test_updates.py b/tests/test_updates.py index 4ac4eef..25499b1 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -3,6 +3,7 @@ import hashlib import io import json +import threading import time import urllib.error import urllib.request @@ -613,6 +614,47 @@ def test_a_check_clears_out_old_downloads(): assert s.cleaned == ["downloads"] +def test_old_downloads_are_cleared_out_without_a_check(): + s = Steps() + + s.updater.tidy() + s.updater.tidy_thread.join(timeout=5) + + assert s.cleaned == ["downloads"] + assert s.updater.state == IDLE + assert s.changes == 0 + + +def test_clearing_out_leaves_a_download_under_way_alone(): + s = Steps() + s.updater.check() + s.finish() + s.cleaned.clear() + s.updater.install(on_started=lambda: None) + + s.updater.tidy() + + assert s.updater.tidy_thread is None + assert s.cleaned == [] + s.finish() + + +def test_a_cleanup_that_goes_wrong_is_ignored(monkeypatch): + crashes = [] + monkeypatch.setattr(threading, "excepthook", crashes.append) + s = Steps() + + def broken(folder): + raise RuntimeError("unexpected") + + s.updater._clean = broken + s.updater.tidy() + s.updater.tidy_thread.join(timeout=5) + + assert crashes == [] + assert s.updater.state == IDLE + + def test_nothing_is_installed_before_a_check_finds_something(): s = Steps() From ef8dfba01418f82f2fa033bbea4e05393c7d80cc Mon Sep 17 00:00:00 2001 From: Color Dumper <156731588+ColorDumper@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:35:06 -0500 Subject: [PATCH 31/31] Drop Start's leftover settings save error --- maphide/qt/app.py | 6 +----- tests/test_qt_backend.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/maphide/qt/app.py b/maphide/qt/app.py index 242c1bf..d1abc07 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -381,11 +381,7 @@ def _start(self): # missing host gets the same message. try: self.controller.start(config_from_form(**form_values(self.controller.running_config))) - except ValueError as exc: - self.notice(str(exc)) - except OSError as exc: - self.notice(f"Couldn't save settings: {plain_reason(exc)}") - except RuntimeError as exc: + except (ValueError, RuntimeError) as exc: self.notice(str(exc)) @Slot() diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index 3993256..bd290b2 100644 --- a/tests/test_qt_backend.py +++ b/tests/test_qt_backend.py @@ -257,6 +257,18 @@ def test_start_with_saved_settings_that_arent_ready_says_why_in_the_field_log(h) assert h.backend.controller.history[-1].code == HISTORY_NOTICE +def test_start_that_maphide_refuses_says_why_in_the_field_log(h): + save_form(h.backend) + + def refuse(cfg): + raise RuntimeError("Service is already running.") + + h.service.start = refuse + h.backend.primary() + + assert h.lines[-1][1:] == ("> Service is already running.", "warning") + + def test_start_runs_the_worker_with_the_saved_settings(h): save_form(h.backend, hotkey="M")