diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d77c97b..c4f89fb 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" @@ -185,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/CHANGELOG.md b/CHANGELOG.md index 659fb2d..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. @@ -47,6 +48,26 @@ 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. +- 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. +- 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. +- 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. +- 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/installer/MapHide.iss b/installer/MapHide.iss index fd45d7b..e26d7fc 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" @@ -80,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/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/config.py b/maphide/config.py index c198d69..c990e2f 100644 --- a/maphide/config.py +++ b/maphide/config.py @@ -1,7 +1,9 @@ """The settings file: its shape, and reading and writing it.""" import json +import os import shutil +import time from dataclasses import dataclass, replace from .hotkeys import ( @@ -23,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"}) @@ -171,7 +177,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() @@ -180,9 +186,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( @@ -242,8 +251,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): @@ -252,7 +260,32 @@ 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.""" 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()) + _replace_when_free(temporary, path) + except BaseException: + temporary.unlink(missing_ok=True) + raise diff --git a/maphide/controller.py b/maphide/controller.py index c295be1..66cbe7c 100644 --- a/maphide/controller.py +++ b/maphide/controller.py @@ -22,7 +22,21 @@ worker_settings_differ, ) from .obs import ConnectionCheck, check_connection -from .overlay import CONNECTED, MapHideService, human_ts, stop_wait_should_continue +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, + stop_wait_should_continue, +) HISTORY_LINE_COUNT = 10 RESTART_POLL_INTERVAL_MS = 50 @@ -43,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) @@ -92,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. @@ -179,28 +208,53 @@ 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 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._save(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: + # 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() 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) - # 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)): - 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) @@ -208,16 +262,18 @@ 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 + """Start the worker with `cfg`, the saved settings. Start never + saves: only Save does. Raises RuntimeError if the worker is already running.""" - self._save(cfg) 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() @@ -242,10 +298,15 @@ 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 except RuntimeError as exc: + self._relinking_from = None self._notify(str(exc)) self._on_change() @@ -273,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] @@ -292,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..1c3fcea 100644 --- a/maphide/fieldlog.py +++ b/maphide/fieldlog.py @@ -13,8 +13,18 @@ HISTORY_NOTICE, HISTORY_SETTINGS_SAVED, HISTORY_UPDATE_AVAILABLE, + SUBJECT_RELINKING, +) +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 .obs import OBS_BAD_PASSWORD, OBS_LINK_LOST, OBS_OVERLAY_MAY_REMAIN, OBS_UNREACHABLE from .overlay import ( EVENT_CONNECT_FAILED, EVENT_CONNECTED, @@ -42,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", } @@ -56,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): @@ -93,6 +108,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/maphide/overlay.py b/maphide/overlay.py index ea5a21d..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}." @@ -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/maphide/qt/Main.qml b/maphide/qt/Main.qml index 24ec91e..0e6a360 100644 --- a/maphide/qt/Main.qml +++ b/maphide/qt/Main.qml @@ -8,14 +8,25 @@ 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 + // Closing Settings without Save puts the saved settings back: only Save + // keeps a change. onDrawerOpenChanged: if (!drawerOpen) { settings.stopCapture() + settings.maskSecrets() + releaseKeyboard() + backend.discardChanges() + } + // Hidden to the tray, Settings may still be open: hide Host, Port and + // Password anyway. + onVisibleChanged: if (!visible) { + settings.maskSecrets() releaseKeyboard() } - onVisibleChanged: if (!visible) 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. @@ -38,12 +49,16 @@ Window { function onWindowPressed(x, y) { win.releaseFieldUnlessAt(x, y) } } + // 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 + width: 480 - height: 748 + height: fullHeight minimumWidth: width maximumWidth: width - minimumHeight: height - maximumHeight: height // Shown from Python once its title bar matches the theme. visible: false title: "MapHide" @@ -59,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 @@ -191,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 } @@ -215,7 +227,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 @@ -519,52 +545,127 @@ 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 - Column { + Condensed { + id: logHeading x: 14 y: 10 + text: "FIELD LOG" + font.pixelSize: 13 + 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) { @@ -619,7 +720,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, @@ -635,6 +736,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 18df944..b0c072a 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 @@ -19,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 = "" @@ -179,6 +188,7 @@ Item { width: parent.width spacing: 8 Field { + id: hostField width: (parent.width - 8) * 2 / 3 label: "HOST" secret: true @@ -186,6 +196,7 @@ Item { onEdited: (text) => backend.setField("host", text) } Field { + id: portField width: (parent.width - 8) / 3 label: "PORT" secret: true @@ -195,6 +206,7 @@ Item { } } Field { + id: passwordField width: parent.width label: "PASSWORD" secret: true @@ -702,6 +714,34 @@ 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 && !parent.showResetWarning + text: "Unsaved changes" + verticalAlignment: Text.AlignVCenter + horizontalAlignment: Text.AlignHCenter + font.pixelSize: 12 + color: settings.t.warn + } Rectangle { id: stamp anchors.centerIn: parent @@ -739,6 +779,7 @@ Item { PressButton { id: saveButton + objectName: "saveButton" anchors.right: parent.right anchors.rightMargin: 18 y: 12 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/maphide/qt/app.py b/maphide/qt/app.py index 7c384f2..d1abc07 100644 --- a/maphide/qt/app.py +++ b/maphide/qt/app.py @@ -14,6 +14,7 @@ QAbstractNativeEventFilter, QEvent, QObject, + QPoint, QTimer, QUrl, Signal, @@ -56,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. @@ -63,6 +67,91 @@ 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 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): + """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() + 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): @@ -155,9 +244,13 @@ def load(self, **load_options): self.refresh() self._poll_timer.start() if cfg.auto_connect: - QTimer.singleShot(AUTO_CONNECT_DELAY_MS, self._start) - if cfg.check_updates and self._update_checks: - self._schedule(UPDATE_CHECK_DELAY_MS, self._check_quietly) + self._schedule(AUTO_CONNECT_DELAY_MS, self._start) + 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. @@ -199,7 +292,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()) @@ -254,6 +353,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"])) @@ -273,13 +376,12 @@ 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)) - 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: + self.controller.start(config_from_form(**form_values(self.controller.running_config))) + except (ValueError, RuntimeError) as exc: self.notice(str(exc)) @Slot() @@ -327,6 +429,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: @@ -412,6 +536,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() @@ -430,9 +556,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): @@ -522,6 +648,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 @@ -600,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() @@ -680,9 +811,16 @@ 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) window.show() + # 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) @@ -693,6 +831,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 @@ -713,6 +870,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/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/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/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: diff --git a/maphide/updates.py b/maphide/updates.py index eaa6d82..1eaa792 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 @@ -30,6 +31,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 +105,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 +130,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 +146,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 +162,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,11 +182,67 @@ 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 _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 +): """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() + 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 @@ -205,6 +282,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 +291,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 @@ -219,11 +300,34 @@ 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): 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 @@ -275,7 +379,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): @@ -288,13 +398,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): @@ -302,6 +406,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/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_config.py b/tests/test_config.py index c4e739c..c13b875 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,9 +1,11 @@ """Tests for loading, saving, and sanitising the config file.""" import json +import threading import pytest +from maphide import config as config_module from maphide.config import ( DEFAULT_HIDE_DELAY_MS, MAX_HIDE_DELAY_MS, @@ -133,6 +135,83 @@ 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_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" + + 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") @@ -198,6 +277,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): @@ -205,6 +286,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 4423435..267f2b4 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, @@ -155,25 +162,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_does_not_run_the_worker_when_saving_fails(h): +def test_start_never_saves(h): + h.controller.load(load=lambda: make_config(hotkey="M")) + + h.controller.start(make_config(hotkey="K")) + + assert h.saved == [] + assert h.controller.history == [] + + +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): @@ -263,6 +278,48 @@ 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()) + + 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")) @@ -463,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() @@ -536,3 +601,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..aba4bc1 100644 --- a/tests/test_fieldlog.py +++ b/tests/test_fieldlog.py @@ -4,15 +4,19 @@ HISTORY_DEFAULTS_RESTORED, HISTORY_NOTICE, HISTORY_SETTINGS_SAVED, + SUBJECT_RELINKING, HistoryEntry, ) 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, @@ -89,6 +93,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), ], @@ -103,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): diff --git a/tests/test_installer_script.py b/tests/test_installer_script.py new file mode 100644 index 0000000..fcde624 --- /dev/null +++ b/tests/test_installer_script.py @@ -0,0 +1,34 @@ +"""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" +) + + +def setup_directive(name): + match = re.search(rf"^{name}=(.*)$", INSTALLER, re.MULTILINE) + 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. + assert setup_directive("AllowCancelDuringInstall") == "no" + assert 'Type: filesandordirs; Name: "{app}\\_internal"' in INSTALLER 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_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_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 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) diff --git a/tests/test_qt_backend.py b/tests/test_qt_backend.py index ac1e011..bd290b2 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, @@ -107,6 +111,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)) @@ -123,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. @@ -208,7 +249,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 +257,20 @@ 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_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") h.backend.primary() @@ -225,8 +278,89 @@ def test_start_runs_the_worker_with_the_form(h): assert h.backend.primaryIsStop +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.service.started_with[-1].hotkey == "M" + assert h.saved == [] + + +# 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() + assert h.backend.hasUnsavedChanges is False + + +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() @@ -242,7 +376,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.") @@ -302,7 +436,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() @@ -344,7 +478,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) @@ -389,6 +523,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 @@ -408,6 +568,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_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() diff --git a/tests/test_qt_drawer.py b/tests/test_qt_drawer.py new file mode 100644 index 0000000..2902727 --- /dev/null +++ b/tests/test_qt_drawer.py @@ -0,0 +1,302 @@ +"""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, 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 +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 service(): + return FakeService() + + +@pytest.fixture +def setup(qt_app, service): + saved = [] + 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(): + 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 + + +# 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") + + +# 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] + + +# 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 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() diff --git a/tests/test_qt_fit.py b/tests/test_qt_fit.py new file mode 100644 index 0000000..1482daa --- /dev/null +++ b/tests/test_qt_fit.py @@ -0,0 +1,120 @@ +"""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 + DEFAULT_FRAME_HEIGHT, + MIN_WINDOW_HEIGHT, + Backend, + ScreenFit, + build_window, + fitted_height, + on_screen_top, + set_window_height, +) + +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() + + +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): + set_window_height(window, 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): + set_window_height(window, height) + window.show() + QGuiApplication.processEvents() + + log = window.findChild(QObject, "fieldLog") + assert log.height() >= 0 + assert bottom_in_window(log) <= height 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) 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. 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"] 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 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 ---------------------------------------------- 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 diff --git a/tests/test_updates.py b/tests/test_updates.py index 8bb318f..25499b1 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -3,7 +3,10 @@ import hashlib import io import json +import threading +import time import urllib.error +import urllib.request import pytest from test_controller import ManualScheduler @@ -20,6 +23,8 @@ Release, UpdateError, Updater, + check_setup, + clean_downloads, download_setup, fetch_latest, installed_by_setup, @@ -199,6 +204,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 = [] @@ -208,6 +309,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 @@ -238,6 +389,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 +403,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 @@ -400,6 +561,100 @@ 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_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_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()