diff --git a/README.md b/README.md index 465f871..9ba8409 100644 --- a/README.md +++ b/README.md @@ -33,14 +33,15 @@ time in chosen apps into XP and a small village-building game. | Area | What you get | | --- | --- | | Tracking | Foreground-only time, idle cut-off at your last input, lock-screen detection, midnight-accurate daily totals, UWP apps resolved to the real app, elevated apps tracked by name | -| Dashboard | Live session card, today vs. this time yesterday, week total, today by hour, last 14 days, top apps with share and category breakdown | +| Dashboard | Live session dial, today vs. this time yesterday, week total, today by hour, last 14 days, top apps with share and category breakdown | +| In other terms | Today, this week or all time retold as Everest summit days, Apollo 11 trips, ISS laps, marathons, novels and more, each with the basis for its number | | Calendar | Month heatmap with keyboard navigation, month totals and busiest day, per-day hourly chart and app list | | Apps | Search, period filter (today to all time), category and favorite filters, sort by time, launches or clicks | | App detail | Today / 7 / 30 day totals, 30-day chart, recent sessions, first and last seen, longest session, rename, category | -| Control | Per-app daily limits with notifications, exclude any app (with undo), pause from the tray for a set time | +| Control | Per-app daily limits with notifications, per-type notification switches, exclude any app (with undo), pause from the tray for a set time | | Rewards | Optional XP, levels, streaks and a village-building game whose buildings boost future rewards | -| Desktop | Tray icon with live tooltip, launch at sign-in (starts hidden), single instance, dark, light or system theme with 8 accents | -| Motion | Fluent-timed page transitions, counters, chart and list motion that explain each change; follows Windows *Animation effects* and can be turned off in Settings | +| Desktop | Tray icon with live tooltip, launch at sign-in (starts hidden), single instance, six palettes (three dark, three light) with system switching and 8 accents | +| Motion | Fluent-timed page transitions, odometer readouts, springy switches, check marks that draw in, a gliding fader, hover fades and a tick burst on claims and builds; follows Windows *Animation effects* and can be turned off in Settings | | Data | CSV and JSON export, consistent database backup and validated restore, automatic schema migrations | | Updates | Once-a-day check against GitHub releases, in-app download and install | @@ -60,11 +61,17 @@ time in chosen apps into XP and a small village-building game. Village
Village: buildings, inventory and market - Settings
Settings apply immediately - Dashboard in the light theme
Light theme + In other terms
In other terms: the week as Voyager kilometres, marathons and Everest + Appearance settings
Palette gallery, accents and animation switch + + + Settings
Check boxes and a ruler slider for idle timeout + Dashboard in the light theme
Paper, the default light palette +All six palettes, each with a different accent + Screenshots and the animation above are generated from demo data with `python scripts/screenshots.py` and `python scripts/record_demo.py`. @@ -73,13 +80,14 @@ and `python scripts/record_demo.py`. The interface is styled as an instrument panel: warm neutrals, hairline rules, engraved monospaced labels and one signal color. Recorded history is drawn in neutral ink; the signal color marks only what is live, selected or current. Charts use hairline grids, thin bars on tick-mark rulers and a five-step calendar ramp. -Category colors are a categorical palette checked for color-vision-deficiency separation in both themes, -and text never takes a data color. +Category colors are a categorical palette checked for color-vision-deficiency separation in both modes, +and text never takes a data color. Every palette and accent pair keeps small text at 4.5:1 and marks at +3:1; accents are re-stepped per palette to hold that (`tests/test_theme.py` checks all 48 pairs). | Element | Choice | | --- | --- | | Type | Instrument Sans (interface, tabular figures), Martian Mono (labels) | -| Themes | Graphite (dark) and Paper (light), or follow Windows | +| Palettes | Dark: Graphite, Carbon (true black), Midnight. Light: Paper, Porcelain, Sage. System mode switches between your two picks | | Signal color | Orange `#ff6b1a` by default, 8 presets in Settings | | Shape | 6 px panels, 4 px controls, 1 px borders, no shadows | @@ -92,7 +100,29 @@ Download the latest build from [Releases](https://github.com/H4ch1Net/AppTrackr/ | `AppTrackr_Setup.exe` | You want Start Menu entries, optional sign-in startup and uninstall support. Installs per user, no admin rights needed. | | `AppTrackr_Portable.zip` | You want to run it from a folder. Extract anywhere and start `AppTrackr.exe`. | -Requirements: Windows 10 or 11 (64-bit). Upgrading over v1.0 keeps your data and migrates it on first start. +Requirements: Windows 10 or 11 (64-bit). + +### Upgrading + +Every version keeps your data in `%APPDATA%\AppTrackr`, and installers and portable builds of any +version read the same folder, so upgrading never starts you from zero. + +- **From 1.1 or later.** AppTrackr checks GitHub once a day. Choose *Download and install* in Settings; + the installer replaces the old build and starts the new one, and tracking picks up where it stopped. +- **From 1.0.x.** Run the new `AppTrackr_Setup.exe`. It installs over 1.0 in the same folder, closes the + running copy and keeps the Start Menu and sign-in entries. To update from inside 1.0 instead, paste + `https://api.github.com/repos/H4ch1Net/AppTrackr/releases/latest` into *Settings > Updates > Update feed + URL* (1.0 ships without one) and press *Check for Updates*. +- **Portable.** Extract the new zip anywhere, or over the old folder, and start it. Data stays in `%APPDATA%`. + +On the first start after an upgrade that changes the database, AppTrackr copies it to +`data-backup-schema-.sqlite` in the same folder and then upgrades it in a single transaction: +either everything is converted or nothing changes. Upgrading from 1.0 keeps every app, finished session, open +and click count, reward, building and setting, and rebuilds daily totals from the raw sessions, which also +recovers time 1.0 left out (sessions that ended in idle, and sessions that ran past midnight). Sign-in +entries made by 1.0 are updated to start in the tray. If an upgrade ever fails, AppTrackr says so, leaves +the data as it was and points to the backup and the log. `tests/test_upgrade.py` runs this upgrade on a +database written by v1.0.2's own code. ## Usage @@ -108,6 +138,9 @@ use **Quit** from the tray menu (or Ctrl+Q) to stop it. - **Favorites and streaks.** Star apps you want to spend time in. A streak day needs 30 minutes in favorites. - **Rewards.** Pick earning apps on the Rewards page or from an app's page. Milestones (30 min, 1 h, 2 h, 5 h of focus per day) pay XP and resources you spend in the village. Turn the whole layer off in Settings. +- **In other terms.** The dashboard card retells today, this week or all time against known yardsticks. + *Shuffle* shows others. Each comparison names its basis, for example "South Col to the summit and back + down: about 14 h". ### Keyboard shortcuts @@ -225,13 +258,14 @@ both to the GitHub release. `ci.yml` runs lint and tests on Windows and Linux fo apptrackr/ __main__.py entry point: arguments, logging, single instance, service wiring paths.py data, log and asset locations + perspective.py yardsticks for 'In other terms' and how they are picked core/ tracker, platform (Win32), launch watcher, click counter, autostart, limits data/ SQLite access and migrations, queries, export/backup, app catalog, demo data rewards/ milestone rules, reward engine, streaks game/ village state and balance values updater/ GitHub release check and installer download ui/ main window, theme and motion tokens, icons, views and shared widgets - assets/ logo, Lucide icons, illustrations, bundled fonts + assets/ logo, Lucide and AppTrackr line icons, illustrations, bundled fonts packaging/ PyInstaller spec, Inno Setup script, app icon scripts/ screenshot, demo animation, README art and icon generators tests/ pytest suite (data, tracker, rewards, updater, offscreen UI) @@ -257,8 +291,8 @@ flowchart LR - **Nothing is tracked.** Check the tracking module at the bottom of the sidebar. *Paused* resumes on click. *Idle* means no input for the idle timeout. Apps you excluded are listed in Settings. - **An app shows up under an odd name.** Open it and use the menu next to *Favorite* to rename it. -- **The window opens at sign-in instead of staying in the tray.** Startup entries created by v1.0 lack - `--minimized`. Turn *Launch at startup* off and on again in Settings to rewrite the entry. +- **The window opens at sign-in instead of staying in the tray.** Start AppTrackr once; it updates startup + entries left by older versions. If that does not help, turn *Launch at startup* off and on in Settings. - **Something broke.** Run with `--debug` and look at `%APPDATA%\AppTrackr\logs\apptrackr.log`, then [open an issue](https://github.com/H4ch1Net/AppTrackr/issues) with the relevant lines. @@ -272,7 +306,8 @@ regenerated screenshots if they change what the README shows. ## License -[MIT](LICENSE). Icons from [Lucide](https://lucide.dev) (ISC, see `apptrackr/assets/icons/LICENSE`). +[MIT](LICENSE). Icons from [Lucide](https://lucide.dev) (ISC, see `apptrackr/assets/icons/LICENSE`), plus a few +drawn for AppTrackr (marked in the SVG). Fonts: [Instrument Sans](https://github.com/Instrument/instrument-sans) and [Martian Mono](https://github.com/evilmartians/mono), both SIL Open Font License 1.1 (see `apptrackr/assets/fonts`). diff --git a/apptrackr/__main__.py b/apptrackr/__main__.py index 47bf569..cd6e5c9 100644 --- a/apptrackr/__main__.py +++ b/apptrackr/__main__.py @@ -125,7 +125,24 @@ def main(argv: list[str] | None = None) -> int: from apptrackr.data import db from apptrackr.ui.main import MainWindow, prepare_app - db.init_db() + try: + db.init_db() + except Exception: + log.exception("Could not open or upgrade the database") + from PySide6.QtWidgets import QMessageBox + + QMessageBox.critical( + None, + APP_NAME, + "AppTrackr could not open or upgrade its data, so it did not start. Your data was not changed, " + f"and a backup copy is kept next to it in:\n{paths.data_dir()}\n\n" + f"Details are in the log:\n{paths.log_dir()}", + ) + return 1 + if not args.demo: + from apptrackr.core import autostart + + autostart.repair() if args.demo: from apptrackr.data import demo @@ -163,6 +180,8 @@ def shutdown(): shutil.rmtree(paths.data_dir(), ignore_errors=True) app.aboutToQuit.connect(shutdown) + # Windows sign-out and installers closing the app (Restart Manager) ask to save first. + app.commitDataRequest.connect(lambda *_: tracker.flush()) log.info("%s %s started (data: %s)", APP_NAME, __version__, paths.data_dir()) return app.exec() diff --git a/apptrackr/assets/icons/book.svg b/apptrackr/assets/icons/book.svg new file mode 100644 index 0000000..e28a3a1 --- /dev/null +++ b/apptrackr/assets/icons/book.svg @@ -0,0 +1 @@ + diff --git a/apptrackr/assets/icons/footprints.svg b/apptrackr/assets/icons/footprints.svg new file mode 100644 index 0000000..008590c --- /dev/null +++ b/apptrackr/assets/icons/footprints.svg @@ -0,0 +1 @@ + diff --git a/apptrackr/assets/icons/languages.svg b/apptrackr/assets/icons/languages.svg new file mode 100644 index 0000000..5a25f94 --- /dev/null +++ b/apptrackr/assets/icons/languages.svg @@ -0,0 +1 @@ + diff --git a/apptrackr/assets/icons/orbit.svg b/apptrackr/assets/icons/orbit.svg new file mode 100644 index 0000000..e4fed62 --- /dev/null +++ b/apptrackr/assets/icons/orbit.svg @@ -0,0 +1 @@ + diff --git a/apptrackr/assets/icons/plane.svg b/apptrackr/assets/icons/plane.svg new file mode 100644 index 0000000..1c5c8f8 --- /dev/null +++ b/apptrackr/assets/icons/plane.svg @@ -0,0 +1 @@ + diff --git a/apptrackr/core/autostart.py b/apptrackr/core/autostart.py index a92fb49..1b10769 100644 --- a/apptrackr/core/autostart.py +++ b/apptrackr/core/autostart.py @@ -4,6 +4,7 @@ import logging import sys +from pathlib import Path log = logging.getLogger(__name__) @@ -60,3 +61,45 @@ def set_enabled(enable: bool) -> bool: except OSError: log.exception("Could not update autostart entry") return False + + +def _exe_in(cmd: str) -> str: + """The program path at the start of a Run-key command line.""" + cmd = cmd.strip() + if cmd.startswith('"'): + end = cmd.find('"', 1) + return cmd[1:end] if end > 0 else cmd[1:] + return cmd.split(" ", 1)[0] + + +def needs_repair(current: str, ours: str, exists=lambda p: Path(p).exists()) -> bool: + """True when an existing entry should be rewritten for this build. + + 1.1 and later always add --minimized, so an entry without it was made by 1.0 (even + when it points at an old portable copy) and is moved to this build. An entry whose + program no longer exists is repaired too; one for another live 1.1+ copy is left alone. + """ + if "--minimized" not in current: + return True + exe = _exe_in(current) + return not exe or not exists(exe) + + +def repair() -> bool: + """Bring an existing startup entry up to date after an upgrade. Returns True if rewritten.""" + if not supported() or not getattr(sys, "frozen", False): + return False + import winreg + + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _RUN_KEY) as key: + current, _kind = winreg.QueryValueEx(key, _VALUE) + except FileNotFoundError: + return False + except OSError: + log.exception("Could not read autostart entry") + return False + if not needs_repair(str(current), sys.executable): + return False + log.info("Updating the startup entry for this version (was %r)", current) + return set_enabled(True) diff --git a/apptrackr/core/tracker.py b/apptrackr/core/tracker.py index 587dc5c..0119469 100644 --- a/apptrackr/core/tracker.py +++ b/apptrackr/core/tracker.py @@ -93,6 +93,11 @@ def stop(self) -> None: with self._lock: self._close(self._clock()) + def flush(self) -> None: + """Commit the live session so far without ending it (sign-out, installer closing the app).""" + with self._lock: + self._checkpoint(self._clock()) + def reload_settings(self) -> None: with self._lock: self._idle_threshold = max(0, db.get_int("idle_threshold_sec", 300)) diff --git a/apptrackr/data/db.py b/apptrackr/data/db.py index e011c17..bb8c9b6 100644 --- a/apptrackr/data/db.py +++ b/apptrackr/data/db.py @@ -5,6 +5,7 @@ import logging import sqlite3 import threading +import time from pathlib import Path from typing import Any, Callable @@ -73,20 +74,58 @@ def _columns(conn: sqlite3.Connection, table: str) -> set[str]: def init_db() -> None: - """Create the schema on first run and migrate older databases.""" + """Create the schema on first run and migrate older databases. + + Before migrating, the database is copied next to itself (see backup_path), and + all migrations run in one transaction: an upgrade either completes or leaves the + database exactly as the previous version wrote it. + """ conn = get_connection() fresh = not _table_exists(conn, "apps") + version = SCHEMA_VERSION if fresh else conn.execute("PRAGMA user_version").fetchone()[0] + pending = [(target, migrate) for target, migrate in _MIGRATIONS if version < target] + if pending: + _backup(conn, version) conn.executescript(_SCHEMA.read_text(encoding="utf-8")) - version = conn.execute("PRAGMA user_version").fetchone()[0] - if fresh: - version = SCHEMA_VERSION - for target, migrate in _MIGRATIONS: - if version < target: - log.info("Migrating database to schema v%d", target) + if not pending: + if fresh: + conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}") + conn.commit() # a database from a newer version keeps its higher user_version + return + conn.execute("BEGIN IMMEDIATE") + try: + for target, migrate in pending: + log.info("Migrating database from schema v%d to v%d", version, target) migrate(conn) version = target - conn.execute(f"PRAGMA user_version = {int(version)}") - conn.commit() + conn.execute(f"PRAGMA user_version = {int(version)}") + conn.commit() + except Exception: + conn.rollback() + log.exception("Database migration failed; the database was left unchanged") + raise + + +def backup_path(version: int) -> Path: + """Where the pre-upgrade copy of a schema *version* database is kept.""" + stamp = time.strftime("%Y%m%d-%H%M%S") + return db_path().with_name(f"data-backup-schema{version}-{stamp}.sqlite") + + +def _backup(conn: sqlite3.Connection, version: int) -> Path | None: + """Copy the database before an upgrade touches it. A failed copy is logged, not fatal.""" + target = backup_path(version) + try: + dest = sqlite3.connect(str(target)) + try: + conn.backup(dest) + finally: + dest.close() + log.info("Backed up the database to %s before upgrading", target) + return target + except (sqlite3.Error, OSError): + log.exception("Could not back up the database before upgrading") + return None # --------------------------------------------------------------------------- diff --git a/apptrackr/perspective.py b/apptrackr/perspective.py new file mode 100644 index 0000000..8ef1054 --- /dev/null +++ b/apptrackr/perspective.py @@ -0,0 +1,247 @@ +"""Tracked time, retold: "that's 2.4 Everest summit days". + +Each yardstick is something people know, with the duration it takes and the +basis for that number, which the UI shows next to the comparison. pick() +chooses yardsticks that land in a readable range for a given total. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +HOUR = 60 # yardsticks are in minutes + + +@dataclass(frozen=True) +class Yardstick: + key: str + minutes: float # one unit of the yardstick + many: str # label after a count: "4.2 Everest summit days" + part: str # label after a percentage: "38% of the way to the Moon on Apollo 11" + basis: str # where the number comes from, shown under the comparison + icon: str + group: str # used to keep a set of picks varied + max_count: float = 60 # above this the count stops meaning much + one: str = "" # singular label when the count reads exactly 1 + times: bool = False # counts read as multiples: "2.5×" + + +YARDSTICKS: tuple[Yardstick, ...] = ( + Yardstick( + "everest", + 14 * HOUR, + "Everest summit days", + "of an Everest summit day", + "South Col to the summit and back down: about 14 h", + "mountain", + "adventure", + one="Everest summit day", + ), + Yardstick( + "apollo", + 102 * HOUR + 45, + "trips to the Moon on Apollo 11", + "of the way to the Moon on Apollo 11", + "Launch to lunar landing, July 1969: 102 h 45 m", + "moon", + "space", + one="trip to the Moon on Apollo 11", + ), + Yardstick( + "iss", + 92.9, + "laps of Earth by the ISS", + "of a lap of Earth by the ISS", + "The space station circles the planet every 93 minutes", + "orbit", + "space", + max_count=200, + one="lap of Earth by the ISS", + ), + Yardstick( + "sunlight", + 8 + 19 / 60, + "trips by sunlight from the Sun to Earth", + "of sunlight's trip to Earth", + "Light from the Sun takes 8 min 19 s to reach us", + "sun", + "space", + max_count=400, + one="trip by sunlight from the Sun to Earth", + ), + Yardstick( + "marathon", + 4 * HOUR + 30, + "marathons at an everyday pace", + "of a marathon at an everyday pace", + "A typical finishing time: about 4 h 30 m", + "footprints", + "sport", + one="marathon at an everyday pace", + ), + Yardstick( + "record", + 2 * HOUR + 35 / 60, + "world-record marathons", + "of the marathon world record", + "Kelvin Kiptum, Chicago 2023: 2:00:35", + "timer", + "sport", + one="world-record marathon", + ), + Yardstick( + "walk", + 12, + "km walked", + "of a kilometre on foot", + "At an easy 5 km/h, without stopping", + "footprints", + "everyday", + max_count=20000, + ), + Yardstick( + "novel", + 90000 / 238, + "novels read", + "of a novel", + "90,000 words at an average 238 words a minute", + "book", + "learning", + one="novel read", + ), + Yardstick( + "flight", + 8 * HOUR, + "flights from London to New York", + "of a flight from London to New York", + "About 8 h in the air", + "plane", + "travel", + one="flight from London to New York", + ), + Yardstick( + "language", + 600 * HOUR, + "the class hours to learn French or Spanish", + "of the class hours to learn French or Spanish", + "The US Foreign Service Institute's estimate: about 600 h", + "languages", + "learning", + max_count=10, + times=True, + ), + Yardstick( + "mastery", + 10000 * HOUR, + "the 10,000 hours said to make an expert", + "of the 10,000 hours said to make an expert", + "The rule of thumb Malcolm Gladwell made famous", + "trophy", + "learning", + max_count=5, + times=True, + ), + Yardstick( + "moonwalk", + 384400 * 12, + "walks to the Moon", + "of a walk to the Moon", + "384,400 km at 5 km/h, no breaks", + "moon", + "adventure", + max_count=5, + one="walk to the Moon", + ), + Yardstick( + "voyager", + 1e6 / (16.9 * 60), + "million km covered by Voyager 1", + "covered at Voyager 1's speed", + "The probe leaves the Sun behind at about 16.9 km/s", + "rocket", + "space", + max_count=2000, + ), +) + + +@dataclass(frozen=True) +class Fact: + key: str + value: str # "4.2" or "38%" + label: str # "Everest summit days" + basis: str + icon: str + ratio: float + + +def _count(ratio: float) -> str: + if ratio < 10: + text = f"{ratio:.1f}" + return text[:-2] if text.endswith(".0") else text + return f"{ratio:,.0f}" + + +def _percent(ratio: float) -> str: + pct = ratio * 100 + if pct < 0.1: + return "<0.1%" + return f"{pct:.1f}%" if pct < 10 else f"{pct:.0f}%" + + +def describe(minutes: float, stick: Yardstick) -> Fact: + """*minutes* of tracked time measured against one yardstick.""" + ratio = minutes / stick.minutes + if stick.key == "walk" and ratio < 1: + return Fact(stick.key, f"{ratio * 1000:,.0f} m", "walked", stick.basis, stick.icon, ratio) + if stick.key == "voyager" and ratio < 1: + km = ratio * 1e6 + km = round(km, -max(0, len(str(int(km))) - 3)) # three significant figures; the speed is approximate + return Fact(stick.key, f"{km:,.0f} km", "covered at Voyager 1's speed", stick.basis, stick.icon, ratio) + if ratio >= 1: + value = _count(ratio) + if stick.times: + return Fact(stick.key, value + "×", stick.many, stick.basis, stick.icon, ratio) + label = stick.one if value == "1" and stick.one else stick.many + return Fact(stick.key, value, label, stick.basis, stick.icon, ratio) + return Fact(stick.key, _percent(ratio), stick.part, stick.basis, stick.icon, ratio) + + +def _score(minutes: float, stick: Yardstick) -> float | None: + """Lower reads better. None when the comparison would be too tiny or too large to mean much.""" + ratio = minutes / stick.minutes + if ratio > stick.max_count or ratio < 0.02: + return None + if ratio >= 1: + return abs(math.log10(ratio) - math.log10(4)) # small whole-ish counts read best + return abs(math.log10(ratio) - math.log10(0.4)) + 0.35 # "40% of the way" is fun, but counts first + + +def pick(minutes: float, count: int = 3, offset: int = 0) -> list[Fact]: + """Up to *count* comparisons for *minutes*, varied across groups. + + *offset* rotates through the readable candidates (the Shuffle button). + """ + if minutes <= 0: + return [] + scored = [(s, stick) for stick in YARDSTICKS if (s := _score(minutes, stick)) is not None] + scored.sort(key=lambda item: (item[0], item[1].key)) + ranked = [stick for _, stick in scored] + if not ranked: + return [] + start = (offset * count) % len(ranked) + ranked = ranked[start:] + ranked[:start] + chosen: list[Yardstick] = [] + for stick in ranked: # first pass: one per group + if len(chosen) < count and all(stick.group != c.group for c in chosen): + chosen.append(stick) + for stick in ranked: # then fill from what is left + if len(chosen) < count and stick not in chosen: + chosen.append(stick) + return [describe(minutes, stick) for stick in chosen] + + +def readable_count(minutes: float) -> int: + """How many yardsticks give a readable comparison for *minutes*.""" + return sum(1 for stick in YARDSTICKS if _score(minutes, stick) is not None) diff --git a/apptrackr/ui/main.py b/apptrackr/ui/main.py index e7e3346..ac3df34 100644 --- a/apptrackr/ui/main.py +++ b/apptrackr/ui/main.py @@ -470,7 +470,7 @@ def _slow_tick(self) -> None: msg = f"Streak extended to {streak['streak']} days" if streak.get("reward"): msg += f" ({fmt.reward(streak['reward'], ', ')})" - self.notify("Streak", msg) + self.notify("Streak", msg, kind="streaks") bus.rewards_changed.emit() for app in self._limits.check(snap.app_id, snap.uncommitted_ms): self.notify( @@ -478,16 +478,21 @@ def _slow_tick(self) -> None: f"{app['name']}: {fmt.duration(app['used_ms'], short=True)} today " f"(limit {fmt.duration(app['daily_limit_ms'], short=True)})", tone="warning", + kind="limits", ) except Exception: log.exception("Background evaluation failed") self._update_badges() - def notify(self, title: str, message: str, tone: str = "success") -> None: - """Toast when the window is visible, tray notification otherwise.""" + def notify(self, title: str, message: str, tone: str = "success", kind: str | None = None) -> None: + """Toast when the window is visible, tray notification otherwise (if that kind is on).""" if self.isVisible() and not self.isMinimized() and self.isActiveWindow(): self.toast.show_message(message, tone) - elif getattr(self, "_tray", None) and db.get_bool("notifications_enabled", True): + elif ( + getattr(self, "_tray", None) + and db.get_bool("notifications_enabled", True) + and (kind is None or db.get_bool(f"notify_{kind}", True)) + ): self._tray.showMessage(title, message, QSystemTrayIcon.MessageIcon.Information, 6000) # ------------------------------------------------------------------ @@ -625,7 +630,12 @@ def _on_update_checked(self, info) -> None: if not info: return self.set_update_available(info) - self.notify("Update available", f"{APP_NAME} {info.version} is available. Open Settings to install.", "info") + self.notify( + "Update available", + f"{APP_NAME} {info.version} is available. Open Settings to install.", + "info", + kind="updates", + ) def set_update_available(self, info) -> None: self.ctx.update_info = info @@ -656,6 +666,8 @@ def apply_app_theme(app: QApplication) -> None: db.get_setting("ui_mode", "dark"), db.get_setting("ui_theme", theme.DEFAULT_ACCENT), system_dark=system_prefers_dark(), + dark_palette=db.get_setting("ui_dark_palette", theme.DEFAULT_DARK), + light_palette=db.get_setting("ui_light_palette", theme.DEFAULT_LIGHT), ) app.setPalette(theme.palette()) app.setStyleSheet(theme.stylesheet(arrow_icon=_combo_arrow(theme.current().text_dim))) diff --git a/apptrackr/ui/motion.py b/apptrackr/ui/motion.py index 145b279..e0862e2 100644 --- a/apptrackr/ui/motion.py +++ b/apptrackr/ui/motion.py @@ -9,10 +9,12 @@ - exit / dismiss ACCELERATE, FASTER-FAST - move / resize EASY_EASE, NORMAL-GENTLE - data change EASY_EASE, SLOW (staggered for series) +- physical controls SPRING, GENTLE (toggle knob) """ from __future__ import annotations +import math import sys from typing import Callable @@ -48,6 +50,8 @@ def _bezier(x1: float, y1: float, x2: float, y2: float) -> QEasingCurve: DECELERATE = _bezier(0.1, 0.9, 0.2, 1.0) ACCELERATE = _bezier(0.9, 0.1, 1.0, 0.2) EASY_EASE = _bezier(0.33, 0.0, 0.67, 1.0) +# Small overshoot for physical controls (switch knobs, check marks settling). +SPRING = _bezier(0.34, 1.4, 0.64, 1.0) LINEAR = QEasingCurve(QEasingCurve.Type.Linear) _override: bool | None = None @@ -77,16 +81,21 @@ def system_allows_animation() -> bool: return True +def preference() -> bool: + """The user's choice (in-app setting, else the OS), ignoring test overrides.""" + from ..data import db + + stored = db.get_setting("animations", "") + return stored == "1" if stored in ("0", "1") else system_allows_animation() + + def enabled() -> bool: """Whether animations should play: in-app setting, else the OS preference.""" global _cached if _override is not None: return _override if _cached is None: - from ..data import db - - stored = db.get_setting("animations", "") - _cached = stored == "1" if stored in ("0", "1") else system_allows_animation() + _cached = preference() return _cached @@ -216,14 +225,26 @@ def stagger_in(widgets: list[QWidget], step: int = 22, duration: int = FAST, lim def collapse(widget: QWidget, on_done: Callable, duration: int = NORMAL) -> None: - """Fade a widget out while shrinking its height to zero, then call *on_done*.""" + """Fade a widget out while shrinking its height to zero, then call *on_done*. + + *on_done* runs exactly once, also when a refresh destroys the widget mid-animation. + """ if not enabled(): on_done() return + done = False + + def finish(*_args) -> None: + nonlocal done + if not done: + done = True + on_done() + + widget.destroyed.connect(finish) widget.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) height = widget.height() fade(widget, 1.0, 0.0, FAST, ACCELERATE) - tween(widget, height, 0, duration, lambda v: _set_max_height(widget, v), EASY_EASE, on_done, key="collapse") + tween(widget, height, 0, duration, lambda v: _set_max_height(widget, v), EASY_EASE, finish, key="collapse") def _set_max_height(widget: QWidget, value: float) -> None: @@ -272,6 +293,54 @@ def flash(widget: QWidget, color: str | None = None, radius: float = 12, duratio tween(overlay, 1.0, 0.0, duration, overlay.set_strength, DECELERATE, overlay.deleteLater) +class _Burst(QWidget): + """Ring of short ticks that shoots outward from a point and fades: a dial flash.""" + + def __init__(self, host: QWidget, center: QPointF, color: QColor, radius: float, ticks: int): + super().__init__(host) + self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) + self._center, self._color, self._radius, self._ticks = center, color, radius, ticks + self._t = 0.0 + size = radius * 2 + 24 + self.setGeometry(int(center.x() - size / 2), int(center.y() - size / 2), int(size), int(size)) + self.show() + self.raise_() + + def set_t(self, value: float) -> None: + self._t = value + self.update() + + def paintEvent(self, _event): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + c = QPointF(self.width() / 2, self.height() / 2) + t = self._t + color = QColor(self._color) + color.setAlphaF(max(0.0, 1.0 - t) ** 1.5) + p.setPen(QPen(color, 2, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap)) + inner = self._radius * (0.35 + 0.65 * t) + length = 7 * (1 - t) + 2 + for i in range(self._ticks): + angle = math.radians(i * 360 / self._ticks - 90 + 8 * t) + r2 = inner + length * (1.4 if i % 3 == 0 else 1.0) + p.drawLine( + QPointF(c.x() + inner * math.cos(angle), c.y() + inner * math.sin(angle)), + QPointF(c.x() + r2 * math.cos(angle), c.y() + r2 * math.sin(angle)), + ) + + +def burst(widget: QWidget, color: str | None = None, radius: float = 34, ticks: int = 12) -> None: + """Celebrate a moment (a claim, a level, a build) with ticks bursting from *widget*'s centre.""" + if not enabled() or widget is None or not widget.isVisible(): + return + from . import theme + + host = widget.window() + center = QPointF(widget.mapTo(host, widget.rect().center())) + overlay = _Burst(host, center, QColor(color or theme.current().accent), radius, ticks) + tween(overlay, 0.0, 1.0, SLOWER + 150, overlay.set_t, DECELERATE, overlay.deleteLater) + + # --------------------------------------------------------------------------- # Widgets # --------------------------------------------------------------------------- diff --git a/apptrackr/ui/theme.py b/apptrackr/ui/theme.py index dac8931..752feb8 100644 --- a/apptrackr/ui/theme.py +++ b/apptrackr/ui/theme.py @@ -1,8 +1,10 @@ """Design tokens and the global stylesheet: the "Instrument panel" system. -Graphite (dark) and Paper (light) are warm neutrals with hairline structure and -one signal accent. Data marks are drawn in neutral ink; the accent marks what is -live or selected. Fonts come from ui/fonts.py. +Six palettes (three dark, three light) share one structure: neutral surfaces, +hairline borders and a single signal accent. Data marks are drawn in neutral +ink; the accent marks what is live or selected. Every palette keeps small text +at 4.5:1 or better, and accents are re-stepped per palette so marks read at 3:1 +and accent text at 4.5:1. Fonts come from ui/fonts.py. """ from __future__ import annotations @@ -11,8 +13,8 @@ from PySide6.QtGui import QColor, QPalette -# Signal accents. Values are tuned for the Graphite surface; Paper uses a darker -# step for text (Theme.accent_text) while fills keep the same hue. +# Signal accents, tuned for dark surfaces. Light palettes darken them (fit_accent) +# so fills and text keep their contrast. ACCENTS = { "Orange": "#ff6b1a", "Amber": "#f2b01e", @@ -52,6 +54,18 @@ def contrast(a: str, b: str) -> float: return (la + 0.05) / (lb + 0.05) +def _step_until(color: str, against: tuple[str, ...], target: float, dark: bool) -> str: + """Lighten (dark themes) or darken (light themes) *color* in HSV until it meets *target*.""" + c = QColor(color) + for _ in range(40): + if all(contrast(c.name(), bg) >= target for bg in against): + break + c = c.lighter(104) if dark else c.darker(104) + if dark and c.value() >= 255: # saturated colours stop lightening in HSV; blend toward white + c = QColor(_mix(c.name(), "#ffffff", 0.08)) + return c.name() + + @dataclass(frozen=True) class Theme: dark: bool @@ -74,6 +88,7 @@ class Theme: danger: str = "#f04e4e" warning: str = "#f2a516" success: str = "#47c46b" + name: str = "" def accent_soft(self, alpha: float = 0.16) -> str: c = QColor(self.accent) @@ -86,13 +101,8 @@ def accent_hover(self) -> str: @property def accent_text(self) -> str: - """Accent usable as text on the window; darkened on Paper until it reads at 4.5:1.""" - color = self.accent - step = 0 - while contrast(color, self.window) < 4.5 and step < 12: - color = _mix(color, self.text, 0.08) - step += 1 - return color + """Accent usable as small text on the window and on panels (4.5:1).""" + return _step_until(self.accent, (self.window, self.surface), 4.5, self.dark) @property def on_accent(self) -> str: @@ -112,6 +122,7 @@ def color(self, name: str) -> QColor: GRAPHITE = Theme( + name="Graphite", dark=True, window="#121210", sidebar="#0e0e0c", @@ -123,13 +134,54 @@ def color(self, name: str) -> QColor: border_strong="#3b3a35", text="#edebe4", text_dim="#aaa79d", - text_muted="#77746b", + text_muted="#8b8880", track="#25241f", ink="#6b6860", grid="#23221f", ) +CARBON = Theme( + name="Carbon", + dark=True, + window="#000000", + sidebar="#050505", + surface="#0c0c0c", + surface_alt="#141414", + hover="#1b1b1b", + input="#080808", + border="#242424", + border_strong="#353535", + text="#f3f3f1", + text_dim="#a9a9a6", + text_muted="#80807d", + track="#1a1a1a", + ink="#5e5e5c", + grid="#151515", +) + +MIDNIGHT = Theme( + name="Midnight", + dark=True, + window="#0b0f17", + sidebar="#080b11", + surface="#111723", + surface_alt="#18202e", + hover="#1f2938", + input="#0d121c", + border="#232d3d", + border_strong="#334055", + text="#e7ecf3", + text_dim="#a0abbd", + text_muted="#7d89a1", + track="#1a2231", + ink="#58657b", + grid="#171f2c", +) + +_LIGHT_STATUS = {"gold": "#b9800a", "danger": "#d23b30", "warning": "#b86e00", "success": "#2a8a47"} + PAPER = Theme( + name="Paper", dark=False, window="#f2f0ea", sidebar="#ebe8e0", @@ -141,16 +193,70 @@ def color(self, name: str) -> QColor: border_strong="#c8c2b5", text="#191814", text_dim="#4f4c44", - text_muted="#7f7b71", + text_muted="#6b675e", track="#e7e3d9", - ink="#aca595", + ink="#969082", grid="#e0dcd2", - gold="#b9800a", - danger="#d23b30", - warning="#b86e00", - success="#2a8a47", + **_LIGHT_STATUS, +) + +PORCELAIN = Theme( + name="Porcelain", + dark=False, + window="#f0f2f4", + sidebar="#e8ebee", + surface="#fbfcfd", + surface_alt="#eff1f4", + hover="#e5e8ec", + input="#ffffff", + border="#d8dce2", + border_strong="#c2c8d0", + text="#14171c", + text_dim="#48505c", + text_muted="#626976", + track="#e3e6eb", + ink="#8c939e", + grid="#dde1e6", + **_LIGHT_STATUS, ) +SAGE = Theme( + name="Sage", + dark=False, + window="#edf0ea", + sidebar="#e4e8e0", + surface="#f8faf6", + surface_alt="#ecefe8", + hover="#e1e6dc", + input="#fbfcfa", + border="#d3d9cd", + border_strong="#bbc4b4", + text="#151a13", + text_dim="#465041", + text_muted="#5f695a", + track="#dfe4da", + ink="#899282", + grid="#d9dfd3", + **_LIGHT_STATUS, +) + +DARK_PALETTES = {t.name: t for t in (GRAPHITE, CARBON, MIDNIGHT)} +LIGHT_PALETTES = {t.name: t for t in (PAPER, PORCELAIN, SAGE)} +PALETTES = {**DARK_PALETTES, **LIGHT_PALETTES} +DEFAULT_DARK, DEFAULT_LIGHT = GRAPHITE.name, PAPER.name + + +def fit_accent(color: str, base: Theme) -> str: + """The accent as used on *base*: stepped until marks read at 3:1 against its panels.""" + return _step_until(color, (base.surface, base.window), 3.0, base.dark) + + +def build(palette_name: str, accent_name: str = DEFAULT_ACCENT) -> Theme: + """A complete theme: palette plus fitted accent.""" + base = PALETTES.get(palette_name, GRAPHITE) + return replace(base, accent=fit_accent(ACCENTS.get(accent_name, ACCENTS[DEFAULT_ACCENT]), base)) + + # Category colours: a validated categorical set (dataviz reference palette), stepped # per mode. Text never wears these; they mark swatches, dots and share segments. # The reference orange is swapped for bronze so no category reads as the signal colour. @@ -166,9 +272,10 @@ def color(self, name: str) -> QColor: None: ("#a39e92", "#5e5b54"), } -_current = GRAPHITE +_current = build(DEFAULT_DARK) _mode = "dark" _accent_name = DEFAULT_ACCENT +_palettes = {"dark": DEFAULT_DARK, "light": DEFAULT_LIGHT} def current() -> Theme: @@ -183,20 +290,35 @@ def accent_name() -> str: return _accent_name +def palette_choice(kind: str) -> str: + """The palette chosen for 'dark' or 'light' mode.""" + return _palettes[kind] + + def category_color(category: str | None) -> str: light, dark = CATEGORY_COLORS.get(category, CATEGORY_COLORS[None]) return dark if _current.dark else light -def configure(mode: str | None = None, accent: str | None = None, system_dark: bool = True) -> Theme: - """Select mode ('dark', 'light', 'system') and accent preset; returns the new theme.""" +def configure( + mode: str | None = None, + accent: str | None = None, + system_dark: bool = True, + dark_palette: str | None = None, + light_palette: str | None = None, +) -> Theme: + """Select mode ('dark', 'light', 'system'), accent and per-mode palettes; returns the new theme.""" global _current, _mode, _accent_name if mode in MODES: _mode = mode if accent in ACCENTS: _accent_name = accent + if dark_palette in DARK_PALETTES: + _palettes["dark"] = dark_palette + if light_palette in LIGHT_PALETTES: + _palettes["light"] = light_palette dark = system_dark if _mode == "system" else _mode == "dark" - _current = replace(GRAPHITE if dark else PAPER, accent=ACCENTS[_accent_name]) + _current = build(_palettes["dark" if dark else "light"], _accent_name) return _current diff --git a/apptrackr/ui/views/app_detail.py b/apptrackr/ui/views/app_detail.py index 3761246..1d8e256 100644 --- a/apptrackr/ui/views/app_detail.py +++ b/apptrackr/ui/views/app_detail.py @@ -16,6 +16,7 @@ QWidget, ) +from ... import perspective from ...data import catalog, queries from ...rewards import engine as rewards from ...rewards import rules @@ -38,18 +39,19 @@ eyebrow, label, ) - -LIMITS = ( - ("No limit", 0), - ("15 minutes", 15), - ("30 minutes", 30), - ("45 minutes", 45), - ("1 hour", 60), - ("1.5 hours", 90), - ("2 hours", 120), - ("3 hours", 180), - ("4 hours", 240), - ("6 hours", 360), +from ..widgets.controls import TickSlider + +LIMITS = ( # slider stops in minutes; 0 removes the limit + ("Off", 0), + ("15m", 15), + ("30m", 30), + ("45m", 45), + ("1h", 60), + ("1h30", 90), + ("2h", 120), + ("3h", 180), + ("4h", 240), + ("6h", 360), ) MINUTE = 60_000 @@ -119,13 +121,11 @@ def __init__(self, ctx, parent=None): SettingRow("Category", "Groups apps on the dashboard and in filters.", self.category) ) self.settings_card.body.addWidget(divider()) - self.limit = QComboBox() - for text, minutes in LIMITS: - self.limit.addItem(text, minutes) - self.limit.currentIndexChanged.connect(self._on_limit) - self.settings_card.body.addWidget( - SettingRow("Daily limit", "Get a notification once today's time passes it.", self.limit) - ) + self.limit = TickSlider(list(LIMITS)) + self.limit.setAccessibleName("Daily limit") + self.limit.committed.connect(self._on_limit) + self.settings_card.body.addWidget(SettingRow("Daily limit", "Get a notification once today's time passes it.")) + self.settings_card.body.addWidget(self.limit) self.rewards_divider = divider() self.settings_card.body.addWidget(self.rewards_divider) self.rewards_toggle = Toggle() @@ -183,9 +183,12 @@ def reload(self, animate: bool = False) -> None: self._set_combo(self.category, app.get("category")) limit_minutes = (app.get("daily_limit_ms") or 0) // MINUTE - if self.limit.findData(limit_minutes) < 0: - self.limit.addItem(fmt.duration(limit_minutes * MINUTE), limit_minutes) - self._set_combo(self.limit, limit_minutes) + stops = list(LIMITS) + if all(v != limit_minutes for _, v in stops): # a limit set elsewhere keeps its own stop + stops = sorted([*stops, (fmt.axis(limit_minutes * MINUTE).lower(), limit_minutes)], key=lambda s: s[1]) + if stops != self.limit.stops(): + self.limit.set_stops(stops) + self.limit.set_stop_value(limit_minutes) on = rewards.enabled() for w in (self.rewards_divider, self.rewards_row, self.reward_hint): @@ -235,7 +238,7 @@ def reload(self, animate: bool = False) -> None: ) self.chart_card.set_caption( "Focused time per day" - + (f" · dashed line is your {fmt.duration(limit_ms, short=True)} limit" if limit_ms else "") + + (f" · the line marks your {fmt.duration(limit_ms, short=True)} limit" if limit_ms else "") ) self._fill_facts(app) @@ -257,6 +260,15 @@ def _fill_facts(self, app: dict) -> None: val = label(value) val.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) self.facts_grid.addWidget(val, row, 1) + # The all-time total retold: a different yardstick for each app. + retold = perspective.pick(summary["total_ms"] / 60000, 1, offset=self.app_id or 0) + if retold: + fact = retold[0] + row = len(facts) + self.facts_grid.addWidget(eyebrow("In other terms"), row, 0, Qt.AlignmentFlag.AlignTop) + val = label(f"About {fact.value} {fact.label}", wrap=True) + val.setToolTip(fact.basis) + self.facts_grid.addWidget(val, row, 1) self.facts_grid.setColumnStretch(1, 1) def _fill_sessions(self, animate: bool = False) -> None: @@ -332,10 +344,10 @@ def _on_category(self) -> None: queries.set_category(self.app_id, self.category.currentData()) bus.data_changed.emit() - def _on_limit(self) -> None: + def _on_limit(self, minutes: int) -> None: if self.app_id is None: return - minutes = self.limit.currentData() or 0 + minutes = minutes or 0 queries.set_daily_limit(self.app_id, minutes * MINUTE) bus.data_changed.emit() self.ctx.toast(f"Daily limit set to {fmt.duration(minutes * MINUTE)}" if minutes else "Daily limit removed") diff --git a/apptrackr/ui/views/calendar_view.py b/apptrackr/ui/views/calendar_view.py index ca5de7a..3053959 100644 --- a/apptrackr/ui/views/calendar_view.py +++ b/apptrackr/ui/views/calendar_view.py @@ -25,6 +25,7 @@ eyebrow, label, ) +from ..widgets.rolling import RollingLabel class CalendarView(Page): @@ -69,7 +70,7 @@ def __init__(self, ctx, parent=None): box = QVBoxLayout() box.setSpacing(3) box.addWidget(eyebrow(caption)) - value = label("–") + value = RollingLabel("–") value.setFont(fonts.sans(15, 600, tabular=True)) box.addWidget(value) self.stat_labels[key] = value @@ -130,14 +131,14 @@ def refresh(self, animate: bool = False) -> None: total = sum(totals.values()) active = [v for v in totals.values() if v > 0] - self.stat_labels["total"].setText(fmt.duration(total, short=True)) - self.stat_labels["avg"].setText(fmt.duration(total / len(active), short=True) if active else "–") - self.stat_labels["active"].setText(str(len(active))) + self.stat_labels["total"].roll_to(fmt.duration(total, short=True)) + self.stat_labels["avg"].roll_to(fmt.duration(total / len(active), short=True) if active else "–") + self.stat_labels["active"].roll_to(str(len(active))) if active: best = max(totals.items(), key=lambda kv: kv[1]) - self.stat_labels["best"].setText(f"{fmt.short_date(best[0])} · {fmt.duration(best[1], short=True)}") + self.stat_labels["best"].roll_to(f"{fmt.short_date(best[0])} · {fmt.duration(best[1], short=True)}") else: - self.stat_labels["best"].setText("–") + self.stat_labels["best"].roll_to("–") self.header.set_subtitle( f"{fmt.duration(total, short=True)} tracked in {first:%B}" if total else f"Nothing tracked in {first:%B}" ) diff --git a/apptrackr/ui/views/dashboard.py b/apptrackr/ui/views/dashboard.py index 7de62a4..b0dc720 100644 --- a/apptrackr/ui/views/dashboard.py +++ b/apptrackr/ui/views/dashboard.py @@ -34,6 +34,8 @@ set_role, tone_color, ) +from ..widgets.other_terms import OtherTermsCard +from ..widgets.rolling import RollingLabel TOP_APPS = 7 @@ -112,7 +114,7 @@ def _fact(caption: str): box = QVBoxLayout() box.setSpacing(2) box.addWidget(eyebrow(caption)) - value = label("–") + value = RollingLabel("–") value.setFont(fonts.sans(14, 600, tabular=True)) box.addWidget(value) return box, value @@ -145,7 +147,7 @@ def update_from(self, snap: trk.Snapshot) -> None: parts.append(f"limit {fmt.duration(app['daily_limit_ms'], short=True)}") self.detail.setText(" · ".join(parts)) self.fact_started[1].setText(fmt.time_of_day(snap.session_start)) - self.fact_today[1].setText(fmt.duration(today, short=True)) + self.fact_today[1].roll_to(fmt.duration(today, short=True)) self.dial.set_state(True, snap.session_ms, "Session") self._set_state("Live", "pillAccent") return @@ -192,6 +194,7 @@ def __init__(self, ctx, parent=None): self._yesterday_hours: list[int] | None = None self._day_keys: list[str] = [] self._fractions: dict[int, float] = {} + self._before_today: tuple[str, int] = ("", 0) self.header = PageHeader("Dashboard", "", kicker=_kicker_date()) self.add(self.header) @@ -240,6 +243,9 @@ def __init__(self, ctx, parent=None): self.top_card.body.addWidget(legend_host) cols.addWidget(self.top_card, 5) self.add(cols) + + self.other_terms = OtherTermsCard(index=5) + self.add(self.other_terms) self.layout_.addStretch(1) bus.data_changed.connect(lambda: self.isVisible() and self.refresh()) @@ -285,6 +291,11 @@ def _refresh_totals(self, snap: trk.Snapshot) -> None: week_ms = queries.total_ms(queries.week_start(), today) + live days_in = date.today().weekday() + 1 self.t_week.set_number(week_ms, _short, f"{fmt.duration(week_ms / days_in, short=True)} per day on average") + if self._before_today[0] != today: # everything before today changes once a day + first = queries.first_tracked_day() or today + yesterday = (date.today() - timedelta(days=1)).isoformat() + self._before_today = (today, queries.total_ms(first, yesterday) if first < today else 0) + self.other_terms.set_totals(today_ms, week_ms, self._before_today[1] + today_ms) profile = rewards.get_profile() streak = profile["streak"] diff --git a/apptrackr/ui/views/rewards_view.py b/apptrackr/ui/views/rewards_view.py index 37c1d2f..c54e632 100644 --- a/apptrackr/ui/views/rewards_view.py +++ b/apptrackr/ui/views/rewards_view.py @@ -3,7 +3,7 @@ from __future__ import annotations from PySide6.QtCore import Qt -from PySide6.QtWidgets import QComboBox, QGridLayout, QHBoxLayout, QProgressBar, QVBoxLayout, QWidget +from PySide6.QtWidgets import QComboBox, QGridLayout, QHBoxLayout, QProgressBar, QPushButton, QVBoxLayout, QWidget from ...data import queries from ...game import economy @@ -25,8 +25,10 @@ eyebrow, icon_label, label, + set_role, vdivider, ) +from ..widgets.rolling import RollingLabel METRIC_TEXT = {"focused_ms": "focused", "opens_count": "launches", "clicks_count": "clicks"} @@ -56,7 +58,8 @@ def __init__(self, ctx, parent=None): cap.addWidget(self.crown) cap.addStretch(1) level_col.addLayout(cap) - self.level = label("", "hero") + self.level = RollingLabel("") + set_role(self.level, "hero") level_col.addWidget(self.level) top.addLayout(level_col) progress_col = QVBoxLayout() @@ -76,7 +79,7 @@ def __init__(self, ctx, parent=None): col = QVBoxLayout() col.setSpacing(4) col.addWidget(eyebrow(caption)) - value = label("–") + value = RollingLabel("–") value.setFont(fonts.sans(20, 600, tabular=True)) col.addWidget(value) col.addStretch(1) @@ -184,13 +187,13 @@ def refresh(self) -> None: bonuses = game_state.get_bonuses() self.crown.setVisible(bonuses["has_monument"]) self.crown.setToolTip("Monument built") - self.level.setText(str(profile["level"])) + self.level.roll_to(str(profile["level"])) into, need = economy.level_progress(profile["xp"]) self.progress.setMaximum(need) self.progress_text.setText(f"{into} / {need} XP to level {profile['level'] + 1}") self._animate_profile(profile, into) streak = profile["streak"] - self.stat_values["streak"].setText(f"{streak} day{'s' if streak != 1 else ''}") + self.stat_values["streak"].roll_to(f"{streak} day{'s' if streak != 1 else ''}") groups = rewards.unclaimed_by_app() self.claim_all.setEnabled(bool(groups)) @@ -250,9 +253,16 @@ def _pending_row(self, group: dict) -> QWidget: n = len(group["event_ids"]) text.addWidget(label(f"{n} milestone{'s' if n != 1 else ''}", "caption")) lay.addLayout(text, 1) - amounts = label(fmt.reward(group["reward"], " · "), "tick") + # Items keep together (non-breaking spaces) and wrap between each other on narrow windows. + parts = [part.replace(" ", "\u00a0") for part in fmt.reward(group["reward"], "|").split("|")] + amounts = label( + "\u00a0· ".join(parts), + "tick", + wrap=True, + align=Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, + ) amounts.setFont(fonts.mono(10, 500, 2)) - lay.addWidget(amounts) + lay.addWidget(amounts, 2) lay.addWidget(button("Claim", on_click=lambda ids=group["event_ids"]: self._claim(ids, row))) return row @@ -286,7 +296,7 @@ def _earning_row(self, item: dict) -> QWidget: animate_progress(bar, self._progress.get(item["app_id"], 0), value) row.bar_value = value if nxt: - col.addWidget(label(f"Next: {fmt.reward(nxt['reward'], ', ')}", "caption")) + col.addWidget(label(f"Next: {fmt.reward(nxt['reward'], ', ')}", "caption", wrap=True)) else: col.addWidget(label("All milestones reached today", "caption")) lay.addLayout(col, 1) @@ -336,16 +346,20 @@ def restart(): animate_progress(self.progress, shown["into"], into) def _claim(self, event_ids: list[int], row: QWidget) -> None: - motion.collapse(row, lambda: self._report(rewards.claim_many(event_ids))) + applied = rewards.claim_many(event_ids) # claim first; the animation only presents it + motion.burst(row.findChild(QPushButton)) + motion.collapse(row, lambda: self._report(applied)) def _claim_all(self) -> None: rows = [r for r in self._pending_rows if r is not None] if not rows: return self.claim_all.setEnabled(False) + applied = rewards.claim_many() + motion.burst(self.claim_all, radius=40, ticks=16) for row in rows[1:]: motion.collapse(row, lambda: None) - motion.collapse(rows[0], lambda: self._report(rewards.claim_many())) + motion.collapse(rows[0], lambda: self._report(applied)) def _report(self, applied: dict) -> None: bus.rewards_changed.emit() # refreshes this page while it is visible @@ -353,6 +367,8 @@ def _report(self, applied: dict) -> None: self.refresh() if applied: motion.flash(self.profile) + if applied.get("level_up"): + motion.burst(self.level, theme.current().gold, radius=46, ticks=18) msg = "Claimed " + fmt.reward({k: v for k, v in applied.items() if k != "level_up"}, ", ") if applied.get("level_up"): msg += f". Level {applied['level_up']} reached!" @@ -373,14 +389,12 @@ def _add_app(self) -> None: self._changed() def _remove_app(self, app_id: int, name: str, row: QWidget) -> None: - def remove(): - rules.enable_app_rewards(app_id, False) - self._changed() + rules.enable_app_rewards(app_id, False) def undo(): rules.enable_app_rewards(app_id, True) self._added_app = app_id self._changed() - motion.collapse(row, remove) + motion.collapse(row, self._changed) self.ctx.toast(f"{name} no longer earns rewards", "info", "Undo", undo) diff --git a/apptrackr/ui/views/settings_view.py b/apptrackr/ui/views/settings_view.py index f10b81c..114eff6 100644 --- a/apptrackr/ui/views/settings_view.py +++ b/apptrackr/ui/views/settings_view.py @@ -7,12 +7,11 @@ import time from pathlib import Path -from PySide6.QtCore import QObject, QRectF, QSize, Qt, QUrl, Signal +from PySide6.QtCore import QObject, QPointF, QRectF, QSize, Qt, QUrl, Signal from PySide6.QtGui import QColor, QDesktopServices, QPainter, QPen from PySide6.QtWidgets import ( QAbstractButton, QButtonGroup, - QComboBox, QFileDialog, QGridLayout, QHBoxLayout, @@ -28,8 +27,9 @@ from ...data import db, export, queries from ...updater import apply as updater_apply from ...updater import check as updater -from .. import fmt, motion, theme +from .. import fmt, fonts, motion, theme from ..signals import bus, run_async +from ..widgets.charts import _column from ..widgets.components import ( Card, ElidedLabel, @@ -41,19 +41,22 @@ button, clear_layout, divider, + eyebrow, label, ) - -IDLE_CHOICES = ( +from ..widgets.controls import CheckBox, TickSlider + +IDLE_CHOICES = ( # slider stops, shortest first; 0 turns idle detection off + ("1m", 60), + ("2m", 120), + ("3m", 180), + ("5m", 300), + ("10m", 600), + ("15m", 900), + ("30m", 1800), ("Never", 0), - ("1 minute", 60), - ("2 minutes", 120), - ("3 minutes", 180), - ("5 minutes", 300), - ("10 minutes", 600), - ("15 minutes", 900), - ("30 minutes", 1800), ) +NOTIFY_KINDS = (("limits", "Daily limits"), ("streaks", "Streaks"), ("updates", "Updates")) SHORTCUTS = ( ("Ctrl+1 … Ctrl+5", "Switch page"), ("Ctrl+,", "Settings"), @@ -69,33 +72,164 @@ class _ProgressRelay(QObject): progress = Signal(int, int) -class Swatch(QAbstractButton): - """Round accent color picker button.""" +PALETTE_NOTES = { + "Graphite": "Warm graphite. The default.", + "Carbon": "True black for OLED screens.", + "Midnight": "Deep blue night panel.", + "Paper": "Warm paper. The default.", + "Porcelain": "Cool, neutral white.", + "Sage": "Soft green-grey.", +} + + +class _Selectable(QAbstractButton): + """Checkable tile whose hover and selection states ease in and out.""" + + def __init__(self, parent=None): + super().__init__(parent) + self.setCheckable(True) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setFocusPolicy(Qt.FocusPolicy.TabFocus) + self._hover = 0.0 + self._sel = 0.0 + self.toggled.connect(self._on_toggled) + + def _on_toggled(self, on: bool) -> None: + motion.tween(self, self._sel, 1.0 if on else 0.0, motion.GENTLE, self._set_sel, motion.DECELERATE, key="sel") + + def set_checked_silently(self, on: bool) -> None: + self.blockSignals(True) + self.setChecked(on) + self.blockSignals(False) + self._sel = 1.0 if on else 0.0 + self.update() + + def _set_sel(self, v: float) -> None: + self._sel = v + self.update() + + def _set_hover(self, v: float) -> None: + self._hover = v + self.update() + + def enterEvent(self, event): + motion.tween(self, self._hover, 1.0, motion.FAST, self._set_hover, motion.DECELERATE, key="hover") + super().enterEvent(event) + + def leaveEvent(self, event): + motion.tween(self, self._hover, 0.0, motion.NORMAL, self._set_hover, motion.EASY_EASE, key="hover") + super().leaveEvent(event) + + +class Swatch(_Selectable): + """Accent picker: the accent as it will render on the current palette.""" def __init__(self, name: str, color: str, parent=None): super().__init__(parent) self.name = name self.color = color - self.setCheckable(True) self.setToolTip(name) self.setAccessibleName(f"{name} accent") - self.setCursor(Qt.CursorShape.PointingHandCursor) - self.setFocusPolicy(Qt.FocusPolicy.TabFocus) def sizeHint(self) -> QSize: - return QSize(28, 28) + return QSize(30, 30) def paintEvent(self, _event): t = theme.current() p = QPainter(self) p.setRenderHint(QPainter.RenderHint.Antialiasing) - if self.isChecked() or self.hasFocus(): - p.setPen(QPen(QColor(t.text if self.isChecked() else t.accent), 1.5)) + if self._sel > 0.01 or self.hasFocus(): + ring = QColor(t.text if self.isChecked() else t.accent) + ring.setAlphaF(max(self._sel, 1.0 if self.hasFocus() else 0.0)) + p.setPen(QPen(ring, 1.5)) p.setBrush(Qt.BrushStyle.NoBrush) - p.drawRoundedRect(QRectF(1.5, 1.5, 25, 25), 5, 5) + p.drawRoundedRect(QRectF(1.5, 1.5, 27, 27), 5, 5) + inset = 7 - 1.5 * self._hover + 1.0 * self._sel p.setPen(Qt.PenStyle.NoPen) - p.setBrush(QColor(self.color)) - p.drawRoundedRect(QRectF(6, 6, 16, 16), 3, 3) + p.setBrush(QColor(theme.fit_accent(self.color, theme.current()))) + p.drawRoundedRect(QRectF(inset, inset, 30 - 2 * inset, 30 - 2 * inset), 3, 3) + + +class ThemeTile(_Selectable): + """A palette rendered as a miniature AppTrackr window.""" + + W, H = 168, 104 + + def __init__(self, palette: str, parent=None): + super().__init__(parent) + self.palette = palette + self.active = False # palette currently on screen (vs. chosen for the other mode) + self.setToolTip(f"{palette}: {PALETTE_NOTES.get(palette, '')}") + self.setAccessibleName(f"{palette} palette") + + def sizeHint(self) -> QSize: + return QSize(self.W, self.H + 40) + + def paintEvent(self, _event): + t = theme.current() + pv = theme.build(self.palette, theme.accent_name()) + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + frame = QRectF(1, 1, self.W - 2, self.H - 2) + ring = QColor(t.accent if self.active else t.text_dim) + edge = QColor(t.border_strong) + if self._hover: + edge = QColor(theme._mix(t.border_strong, t.text_muted, self._hover)) + p.setPen(QPen(edge, 1)) + p.setBrush(QColor(pv.window)) + p.drawRoundedRect(frame, 6, 6) + # Sidebar with nav lines; the first is the current page. + side = QRectF(frame.left() + 1, frame.top() + 1, 34, frame.height() - 2) + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(QColor(pv.sidebar)) + p.drawRoundedRect(side, 5, 5) + p.drawRect(QRectF(side.right() - 6, side.top(), 6, side.height())) + for i in range(4): + y = side.top() + 16 + i * 11 + p.setBrush(QColor(pv.surface_alt if i == 0 else pv.sidebar)) + p.drawRoundedRect(QRectF(side.left() + 4, y - 3, side.width() - 8, 8), 2, 2) + p.setBrush(QColor(pv.text if i == 0 else pv.text_muted)) + p.drawRoundedRect(QRectF(side.left() + 9, y, 14 if i else 18, 2), 1, 1) + if i == 0: + p.setBrush(QColor(pv.accent)) + p.drawRect(QRectF(side.left() + 4, y - 3, 1.5, 8)) + # Panel with a hero number line and bars: history in ink, now in the accent. + panel = QRectF(side.right() + 8, frame.top() + 10, frame.right() - side.right() - 18, frame.height() - 20) + p.setPen(QPen(QColor(pv.border), 1)) + p.setBrush(QColor(pv.surface)) + p.drawRoundedRect(panel, 4, 4) + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(QColor(pv.text_muted)) + p.drawRoundedRect(QRectF(panel.left() + 8, panel.top() + 8, 26, 2), 1, 1) + p.setBrush(QColor(pv.text)) + p.drawRoundedRect(QRectF(panel.left() + 8, panel.top() + 15, 44, 6), 2, 2) + base = panel.bottom() - 9 + p.setPen(QPen(QColor(pv.border), 1)) + p.drawLine(QPointF(panel.left() + 8, base + 0.5), QPointF(panel.right() - 8, base + 0.5)) + p.setPen(Qt.PenStyle.NoPen) + heights = (14, 26, 30, 18, 9, 22, 28, 12) + slot = (panel.width() - 16) / len(heights) + for i, h in enumerate(heights): + p.setBrush(QColor(pv.accent if i == len(heights) - 1 else pv.ink)) + p.drawPath(_column(panel.left() + 8 + i * slot + slot * 0.2, base, slot * 0.6, h, 1.5)) + # Selection ring eases in around the preview. + if self._sel > 0.01: + ring.setAlphaF(self._sel) + p.setPen(QPen(ring, 2)) + p.setBrush(Qt.BrushStyle.NoBrush) + grow = 2 * (1 - self._sel) + p.drawRoundedRect(frame.adjusted(-grow, -grow, grow, grow).adjusted(0.5, 0.5, -0.5, -0.5), 6, 6) + if self.hasFocus(): + p.setPen(QPen(QColor(t.accent), 1, Qt.PenStyle.DashLine)) + p.setBrush(Qt.BrushStyle.NoBrush) + p.drawRoundedRect(frame.adjusted(-3, -3, 3, 3), 8, 8) + # Caption: engraved name and a one-line note. + p.setPen(QColor(t.text if self.isChecked() else t.text_dim)) + p.setFont(fonts.mono(10, 500, 8)) + p.drawText(QPointF(2, self.H + 16), self.palette.upper()) + p.setPen(QColor(t.text_muted)) + p.setFont(fonts.sans(11)) + p.drawText(QPointF(2, self.H + 32), PALETTE_NOTES.get(self.palette, "")) class SettingsView(Page): @@ -150,12 +284,23 @@ def _build_general(self) -> None: ) card.body.addWidget(divider()) self.notifications = Toggle() - self.notifications.toggled.connect(lambda on: self._save("notifications_enabled", on)) + self.notifications.toggled.connect(self._set_notifications) card.body.addWidget( - SettingRow( - "Notifications", "Daily limits, streaks and updates while the window is hidden.", self.notifications - ) + SettingRow("Notifications", "Shown by Windows while the AppTrackr window is hidden.", self.notifications) ) + kinds = QHBoxLayout() + kinds.setContentsMargins(0, 0, 0, 6) + kinds.setSpacing(20) + self.notify_boxes: dict[str, CheckBox] = {} + for key, text in NOTIFY_KINDS: + box = CheckBox(text) + box.toggled.connect( + lambda on, k=key, t=text: self._save(f"notify_{k}", on, f"{t} notifications {'on' if on else 'off'}") + ) + self.notify_boxes[key] = box + kinds.addWidget(box) + kinds.addStretch(1) + card.body.addLayout(kinds) card.body.addWidget(divider()) self.rewards = Toggle() self.rewards.toggled.connect(self._set_rewards) @@ -170,10 +315,9 @@ def _build_general(self) -> None: def _build_tracking(self) -> None: card = Card("Tracking", index=2) - self.idle = QComboBox() - for text, sec in IDLE_CHOICES: - self.idle.addItem(text, sec) - self.idle.currentIndexChanged.connect(self._set_idle) + self.idle = TickSlider(list(IDLE_CHOICES)) + self.idle.setAccessibleName("Idle timeout") + self.idle.committed.connect(self._set_idle) card.body.addWidget( SettingRow( "Idle timeout", @@ -208,7 +352,26 @@ def _build_appearance(self) -> None: card = Card("Appearance", index=3) self.mode = SegmentedControl(["Dark", "Light", "System"]) self.mode.changed.connect(self._set_mode) - card.body.addWidget(SettingRow("Theme", "", self.mode)) + card.body.addWidget(SettingRow("Mode", "System follows Windows' app mode.", self.mode)) + card.body.addWidget(divider()) + card.body.addWidget( + SettingRow("Palette", "One for dark mode and one for light mode. System switches between them.") + ) + grid = QGridLayout() + grid.setHorizontalSpacing(16) + grid.setVerticalSpacing(6) + self.tiles: dict[str, ThemeTile] = {} + for row, (kind, names) in enumerate((("Dark", theme.DARK_PALETTES), ("Light", theme.LIGHT_PALETTES))): + heading = eyebrow(kind) + heading.setContentsMargins(0, 12 if row else 2, 0, 0) + grid.addWidget(heading, row * 2, 0, 1, 3) + for col, name in enumerate(names): + tile = ThemeTile(name) + tile.clicked.connect(lambda _=False, n=name: self._set_palette(n)) + self.tiles[name] = tile + grid.addWidget(tile, row * 2 + 1, col, Qt.AlignmentFlag.AlignLeft) + grid.setColumnStretch(3, 1) + card.body.addLayout(grid) card.body.addWidget(divider()) swatches = QWidget() lay = QHBoxLayout(swatches) @@ -222,7 +385,9 @@ def _build_appearance(self) -> None: self.swatches[name] = sw sw.clicked.connect(lambda _=False, n=name: self._set_accent(n)) lay.addWidget(sw) - card.body.addWidget(SettingRow("Accent color", "", swatches)) + card.body.addWidget( + SettingRow("Accent color", "Marks what is live, selected or current. Adjusted per palette.", swatches) + ) card.body.addWidget(divider()) self.animations = Toggle() self.animations.toggled.connect(self._set_animations) @@ -322,17 +487,18 @@ def refresh(self) -> None: self.feed.setText(db.get_setting("update_url", "")) idle = db.get_int("idle_threshold_sec", 300) - idx = self.idle.findData(idle) - if idx < 0: - self.idle.addItem(fmt.duration(idle * 1000), idle) - idx = self.idle.count() - 1 - self.idle.blockSignals(True) - self.idle.setCurrentIndex(idx) - self.idle.blockSignals(False) - - self.animations.set_silently(motion.enabled()) + if self.idle.index_of(idle) < 0: # a value set outside the slider keeps its own stop + stops = [s for s in IDLE_CHOICES if s[1]] + [(fmt.duration(idle * 1000, short=True), idle)] + self.idle.set_stops(sorted(stops, key=lambda s: s[1]) + [IDLE_CHOICES[-1]]) + self.idle.set_stop_value(idle) + for key, box in self.notify_boxes.items(): + box.set_silently(db.get_bool(f"notify_{key}", True)) + box.setEnabled(self.notifications.isChecked()) + + self.animations.set_silently(motion.preference()) self.mode.set_current(theme.MODES.index(theme.mode())) self.swatches[theme.accent_name()].setChecked(True) + self._sync_tiles() self.db_path.setText(f"Database: {db.db_path()}") self._fill_excluded() @@ -378,11 +544,15 @@ def _set_rewards(self, on: bool) -> None: self.ctx.window.apply_rewards_visibility() self.ctx.toast("Rewards turned on" if on else "Rewards turned off") - def _set_idle(self) -> None: - sec = self.idle.currentData() + def _set_idle(self, sec: int) -> None: db.set_setting("idle_threshold_sec", sec) self.ctx.tracker.reload_settings() - self.ctx.toast("Idle detection off" if not sec else f"Idle after {self.idle.currentText()}") + self.ctx.toast("Idle detection off" if not sec else f"Idle after {fmt.duration(sec * 1000)}") + + def _set_notifications(self, on: bool) -> None: + self._save("notifications_enabled", on) + for box in self.notify_boxes.values(): + box.setEnabled(on) def _set_clicks(self, on: bool) -> None: db.set_setting("track_clicks", on) @@ -402,6 +572,23 @@ def _set_accent(self, name: str) -> None: db.set_setting("ui_theme", name) self.ctx.window.apply_theme() + def _set_palette(self, name: str) -> None: + kind = "dark" if name in theme.DARK_PALETTES else "light" + db.set_setting(f"ui_{kind}_palette", name) + if theme.mode() != "system": + db.set_setting("ui_mode", kind) # picking a palette shows it + self.ctx.window.apply_theme() + self._sync_tiles() + + def _sync_tiles(self) -> None: + shown = theme.current().name + chosen = {theme.palette_choice("dark"), theme.palette_choice("light")} + for name, tile in self.tiles.items(): + tile.active = name == shown + if tile.isChecked() != (name in chosen): + tile.setChecked(name in chosen) + tile.update() + def _include(self, app: dict, row: QWidget) -> None: queries.set_hidden(app["app_id"], False) self.ctx.tracker.reload_settings() diff --git a/apptrackr/ui/views/village_view.py b/apptrackr/ui/views/village_view.py index f124900..155abf8 100644 --- a/apptrackr/ui/views/village_view.py +++ b/apptrackr/ui/views/village_view.py @@ -2,7 +2,7 @@ from __future__ import annotations -from PySide6.QtCore import QPointF, QRectF, Qt +from PySide6.QtCore import QPointF, QRectF, Qt, QTimer from PySide6.QtGui import QColor, QPainter, QPen from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QProgressBar, QVBoxLayout, QWidget @@ -217,7 +217,13 @@ def refresh(self) -> None: self._place_buildings() self._levels = {name: game_state.building_level(village, name) for name in game_state.BUILDINGS} if self._just_built in self._cards: - motion.flash(self._cards[self._just_built]) + card = self._cards[self._just_built] + + def celebrate() -> None: # after layout, so the card has its final geometry + motion.flash(card) + motion.burst(card.findChild(BlueprintTile), radius=30) + + QTimer.singleShot(0, card, celebrate) self._just_built = None def resizeEvent(self, event): diff --git a/apptrackr/ui/widgets/charts.py b/apptrackr/ui/widgets/charts.py index cdf77ca..6731c37 100644 --- a/apptrackr/ui/widgets/charts.py +++ b/apptrackr/ui/widgets/charts.py @@ -12,6 +12,7 @@ from PySide6.QtWidgets import QSizePolicy, QToolTip, QWidget from .. import fmt, fonts, motion, theme +from .rolling import paint_roll def _font(widget: QWidget, px: int, bold: bool = False) -> QFont: @@ -56,6 +57,42 @@ def _column(x: float, baseline: float, width: float, height: float, radius: floa return path +class _Fades: + """Per-key hover amounts (0..1) that ease in quickly and out gently.""" + + def __init__(self, owner: QWidget): + self.owner = owner + self.values: dict = {} + + def focus(self, key) -> None: + for k, v in list(self.values.items()): + if k != key and v > 0: + self._ease(k, 0.0, motion.NORMAL) + if key is not None: + self._ease(key, 1.0, motion.FASTER) + + def get(self, key) -> float: + return self.values.get(key, 0.0) + + def _ease(self, key, target: float, duration: int) -> None: + motion.tween( + self.owner, + self.get(key), + target, + duration, + lambda v: self._set(key, v), + motion.DECELERATE, + key=f"hover_{key}", + ) + + def _set(self, key, value: float) -> None: + if value <= 0.001: + self.values.pop(key, None) + else: + self.values[key] = value + self.owner.update() + + @dataclass class Bar: label: str # axis label ('' to hide) @@ -73,6 +110,7 @@ def __init__(self, height: int = 170, parent=None): self._bars: list[Bar] = [] self._highlight: int | None = None self._hover: int | None = None + self._fades = _Fades(self) self._limit: float | None = None self._empty_text = "No activity yet" # Animation state: bars ease from _from to _to; _progress runs 0..1 over the series. @@ -163,7 +201,7 @@ def mouseMoveEvent(self, event): idx = self._index_at(event.position().x()) if idx != self._hover: self._hover = idx - self.update() + self._fades.focus(idx) if idx is not None and self._bars[idx].tooltip: QToolTip.showText(event.globalPosition().toPoint(), self._bars[idx].tooltip, self) else: @@ -171,7 +209,7 @@ def mouseMoveEvent(self, event): def leaveEvent(self, _event): self._hover = None - self.update() + self._fades.focus(None) def mouseReleaseEvent(self, event): idx = self._index_at(event.position().x()) @@ -215,6 +253,13 @@ def paintEvent(self, _event): p.setPen(QPen(QColor(t.text_muted if major else t.border_strong), 1)) p.drawLine(QPointF(cx, base + 2), QPointF(cx, base + (7 if major else 4))) + # Hover cursor: a faint column behind the bar under the pointer. + for i, amount in self._fades.values.items(): + if isinstance(i, int) and i < len(self._bars): + band = QColor(t.text) + band.setAlphaF((0.05 if t.dark else 0.06) * amount) + p.fillRect(QRectF(plot.left() + slot * i, plot.top(), slot, plot.height()), band) + ink = QColor(t.ink) for i, bar in enumerate(self._bars): x = plot.left() + slot * i + (slot - bar_w) / 2 @@ -223,8 +268,10 @@ def paintEvent(self, _event): color = QColor(t.accent) if highlighted or self._highlight is None else QColor(ink) if self._limit and bar.value > self._limit: color = QColor(t.danger) - if i == self._hover: - color = QColor(t.text_dim) if color == ink else color.lighter(115) if t.dark else color.darker(110) + amount = self._fades.get(i) + if amount: + lit = QColor(t.text_dim) if color == ink else color.lighter(115) if t.dark else color.darker(110) + color = QColor(theme._mix(color.name(), lit.name(), amount)) if h > 0.5: p.setPen(Qt.PenStyle.NoPen) p.setBrush(color) @@ -268,6 +315,7 @@ def __init__(self, parent=None): self._totals: dict[str, int] = {} self._selected: date | None = date.today() self._hover: date | None = None + self._fades = _Fades(self) self._wave = 1.0 # 0..1 entrance progress after a month change self._ring: QRectF | None = None # animated selection ring while gliding self.setMouseTracking(True) @@ -368,7 +416,7 @@ def mouseMoveEvent(self, event): d = self._day_at(event.position()) if d != self._hover: self._hover = d - self.update() + self._fades.focus(d) if d: ms = self._totals.get(d.isoformat(), 0) tip = f"{fmt.long_date(d)}\n{fmt.duration(ms) if ms else 'No activity'}" @@ -376,7 +424,7 @@ def mouseMoveEvent(self, event): def leaveEvent(self, _event): self._hover = None - self.update() + self._fades.focus(None) def mouseReleaseEvent(self, event): d = self._day_at(event.position()) @@ -449,8 +497,11 @@ def paintEvent(self, _event): p.setBrush(QColor(t.heat(max(level, 1) if d == today and ms else level, today=d == today))) p.drawRoundedRect(r, radius, radius) - if d == self._hover and not future: - p.setPen(QPen(QColor(t.text_dim), 1)) + hover = self._fades.get(d) + if hover and not future: + edge = QColor(t.text_dim) + edge.setAlphaF(hover) + p.setPen(QPen(edge, 1)) p.setBrush(Qt.BrushStyle.NoBrush) p.drawRoundedRect(r.adjusted(0.5, 0.5, -0.5, -0.5), radius, radius) if d == today: @@ -627,6 +678,9 @@ def __init__(self, size: int = 156, parent=None): self._caption = "" self._hand = 0.0 # degrees, eased between seconds self._last_second = -1 + self._text = "–:––" + self._old_text = "" + self._roll = 1.0 # readout digits roll like a mechanical counter self.setAccessibleName("Session timer") def set_state(self, active: bool, session_ms: int, caption: str) -> None: @@ -639,9 +693,21 @@ def set_state(self, active: bool, session_ms: int, caption: str) -> None: self._last_second = second elif not active: self._last_second = -1 + text = fmt.clock(session_ms) if active else "–:––" + if text != self._text: + if active and self._text != "–:––" and self.isVisible() and motion.enabled(): + self._old_text = self._text + motion.tween(self, 0.0, 1.0, motion.GENTLE, self._set_roll, motion.LINEAR, key="roll") + else: + self._roll = 1.0 + self._text = text self.setToolTip(fmt.clock(session_ms) if active else caption) self.update() + def _set_roll(self, value: float) -> None: + self._roll = value + self.update() + def _set_hand(self, value: float) -> None: self._hand = value % 360 self.update() @@ -686,10 +752,15 @@ def paintEvent(self, _event): ) # Readout. - p.setPen(QColor(t.text if self._active else t.text_muted)) - p.setFont(fonts.sans(26 if self._ms < 3_600_000 else 22, 600, tabular=True)) - text = fmt.clock(self._ms) if self._active else "–:––" - p.drawText(QRectF(0, c.y() - 22, self.width(), 30), Qt.AlignmentFlag.AlignCenter, text) + color = QColor(t.text if self._active else t.text_muted) + font = fonts.sans(26 if self._ms < 3_600_000 else 22, 600, tabular=True) + readout = QRectF(0, c.y() - 22, self.width(), 30) + if self._roll < 1.0 and len(self._old_text) == len(self._text): + paint_roll(p, readout, Qt.AlignmentFlag.AlignHCenter, self._old_text, self._text, self._roll, font, color) + else: + p.setPen(color) + p.setFont(font) + p.drawText(readout, Qt.AlignmentFlag.AlignCenter, self._text) p.setFont(fonts.mono(8, 500, 12)) p.setPen(QColor(t.text_muted)) p.drawText(QRectF(0, c.y() + 10, self.width(), 14), Qt.AlignmentFlag.AlignCenter, self._caption.upper()) diff --git a/apptrackr/ui/widgets/components.py b/apptrackr/ui/widgets/components.py index 0ccb26a..0f5d845 100644 --- a/apptrackr/ui/widgets/components.py +++ b/apptrackr/ui/widgets/components.py @@ -39,6 +39,7 @@ from .. import fonts, icons, motion, theme from ..signals import bus +from .rolling import RollingLabel PAGE_MARGIN = 28 MAX_CONTENT_WIDTH = 1280 @@ -460,7 +461,8 @@ def __init__(self, caption: str, icon: str | None = None, tone: str = "accent", lay.setSpacing(6) self.caption = eyebrow(caption) lay.addWidget(self.caption) - self.value = label("–", "value") + self.value = RollingLabel("–") + set_role(self.value, "value") lay.addWidget(self.value) self.sub = label("", "caption") lay.addWidget(self.sub) @@ -483,8 +485,8 @@ def set_number( sub_role: str = "caption", tooltip: str = "", ) -> None: - """Show a numeric value. Noticeable changes count toward the new value; - the first value counts up from zero when the tile is first shown.""" + """Show a numeric value. The first value counts up from zero when the tile is first + shown, large jumps count toward the new value, and small live changes roll.""" previous, self._number, self._formatter = self._number, number, formatter self.set(self.value.text(), sub, sub_role, tooltip) current = motion.running(self, "count") @@ -498,10 +500,10 @@ def set_number( self.value.setText(formatter(number)) self._count_on_show = True return - if abs(number - previous) > max(abs(previous) * 0.02, 0.5) and self.isVisible(): + if abs(number - previous) > max(abs(previous) * 0.25, 0.5) and self.isVisible(): self._count(previous, number) else: - self.value.setText(formatter(number)) + self.value.roll_to(formatter(number)) def reset(self) -> None: """Forget the shown number so the next value counts up from zero (e.g. a different item).""" @@ -989,7 +991,7 @@ def eventFilter(self, obj, event): class Toggle(QAbstractButton): - """Animated on/off switch.""" + """On/off switch. The knob stretches while pressed and springs into place.""" def __init__(self, checked: bool = False, parent=None): super().__init__(parent) @@ -997,8 +999,12 @@ def __init__(self, checked: bool = False, parent=None): self.setCursor(Qt.CursorShape.PointingHandCursor) self.setFocusPolicy(Qt.FocusPolicy.TabFocus) self._knob = 1.0 if checked else 0.0 + self._press = 0.0 + self._hover = 0.0 super().setChecked(checked) self.toggled.connect(self._animate) + self.pressed.connect(lambda: self._tween("press", 1.0, motion.FASTER)) + self.released.connect(lambda: self._tween("press", 0.0, motion.FAST)) def sizeHint(self) -> QSize: return QSize(40, 22) @@ -1021,30 +1027,43 @@ def _set_knob(self, value: float) -> None: def _animate(self, checked: bool) -> None: motion.tween( - self, self._knob, 1.0 if checked else 0.0, motion.FAST, self._set_knob, motion.EASY_EASE, key="knob" + self, self._knob, 1.0 if checked else 0.0, motion.GENTLE, self._set_knob, motion.SPRING, key="knob" ) + def _tween(self, name: str, target: float, duration: int) -> None: + def apply(v: float) -> None: + setattr(self, f"_{name}", v) + self.update() + + motion.tween(self, getattr(self, f"_{name}"), target, duration, apply, motion.DECELERATE, key=name) + + def enterEvent(self, event): + self._tween("hover", 1.0, motion.FAST) + super().enterEvent(event) + + def leaveEvent(self, event): + self._tween("hover", 0.0, motion.NORMAL) + super().leaveEvent(event) + def paintEvent(self, _event): t = theme.current() p = QPainter(self) p.setRenderHint(QPainter.RenderHint.Antialiasing) r = QRectF(1, 2, 38, 18) - off, on = QColor(t.border_strong), QColor(t.text) - track = QColor( - int(off.red() + (on.red() - off.red()) * self._knob), - int(off.green() + (on.green() - off.green()) * self._knob), - int(off.blue() + (on.blue() - off.blue()) * self._knob), - ) + k = max(0.0, min(1.0, self._knob)) # colours never overshoot; position may + off = theme._mix(t.border_strong, t.text_muted, 0.35 * self._hover) + track = QColor(theme._mix(off, t.text, k)) if not self.isEnabled(): track.setAlphaF(0.4) p.setPen(QPen(QColor(t.accent), 2) if self.hasFocus() else Qt.PenStyle.NoPen) p.setBrush(track) p.drawRoundedRect(r, 4, 4) p.setPen(Qt.PenStyle.NoPen) - knob = QColor(t.window) if self._knob > 0.5 else QColor(t.text_dim if t.dark else "#ffffff") - p.setBrush(knob) - x = 4 + self._knob * 20 - p.drawRoundedRect(QRectF(x, 5, 12, 12), 2.5, 2.5) + p.setBrush(QColor(theme._mix(t.text_dim if t.dark else "#ffffff", t.window, k))) + stretch = 5 * self._press + width = 12 + stretch + x = 4 + self._knob * (20 - stretch) + p.drawRoundedRect(QRectF(x, 5, width, 12), 2.5, 2.5) class SettingRow(QWidget): diff --git a/apptrackr/ui/widgets/controls.py b/apptrackr/ui/widgets/controls.py new file mode 100644 index 0000000..15820e4 --- /dev/null +++ b/apptrackr/ui/widgets/controls.py @@ -0,0 +1,364 @@ +"""Painted form controls: check box and a ruler-style slider with fixed stops. + +Both follow the instrument panel rules: monochrome ink when on, accent only +for keyboard focus, and short eased motion that confirms each change. +""" + +from __future__ import annotations + +import math + +from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal +from PySide6.QtGui import QColor, QFontMetrics, QPainter, QPainterPath, QPen +from PySide6.QtWidgets import QAbstractButton, QAbstractSlider, QSizePolicy + +from .. import fonts, motion, theme + + +def _blend(a: str, b: str, t: float) -> QColor: + return QColor(theme._mix(a, b, max(0.0, min(1.0, t)))) + + +def _partial(points: list[QPointF], amount: float) -> QPainterPath: + """Polyline through *points*, trimmed to *amount* (0..1) of its length.""" + lengths = [math.hypot(b.x() - a.x(), b.y() - a.y()) for a, b in zip(points, points[1:], strict=False)] + remaining = sum(lengths) * max(0.0, min(1.0, amount)) + path = QPainterPath(points[0]) + for i, seg in enumerate(lengths): + if remaining <= 0: + break + a, b = points[i], points[i + 1] + f = min(1.0, remaining / seg) if seg else 1.0 + path.lineTo(a + (b - a) * f) + remaining -= seg + return path + + +class CheckBox(QAbstractButton): + """Check box whose box fills and then draws its check mark.""" + + BOX = 16 + + def __init__(self, text: str = "", checked: bool = False, parent=None): + super().__init__(parent) + self.setText(text) + self.setCheckable(True) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setFocusPolicy(Qt.FocusPolicy.TabFocus) + self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + self.setFont(fonts.sans(13)) + super().setChecked(checked) + self._p = 1.0 if checked else 0.0 + self._hover = 0.0 + self._press = 0.0 + self.toggled.connect(self._animate) + self.pressed.connect(lambda: self._tween_press(1.0)) + self.released.connect(lambda: self._tween_press(0.0)) + + def sizeHint(self) -> QSize: + width = self.BOX + (8 + self.fontMetrics().horizontalAdvance(self.text()) if self.text() else 0) + return QSize(width + 2, max(self.BOX, self.fontMetrics().height()) + 4) + + def set_silently(self, checked: bool) -> None: + self.blockSignals(True) + self.setChecked(checked) + self.blockSignals(False) + self._p = 1.0 if checked else 0.0 + self.update() + + def _animate(self, checked: bool) -> None: + # Checking draws in (slower, decelerating); unchecking clears quickly. + if checked: + motion.tween(self, self._p, 1.0, motion.SLOW, self._set_p, motion.DECELERATE, key="check") + else: + motion.tween(self, self._p, 0.0, motion.FAST, self._set_p, motion.ACCELERATE, key="check") + + def _set_p(self, v: float) -> None: + self._p = v + self.update() + + def _tween_press(self, target: float) -> None: + motion.tween(self, self._press, target, motion.FASTER, self._set_press, motion.EASY_EASE, key="press") + + def _set_press(self, v: float) -> None: + self._press = v + self.update() + + def _set_hover(self, v: float) -> None: + self._hover = v + self.update() + + def enterEvent(self, event): + motion.tween(self, self._hover, 1.0, motion.FAST, self._set_hover, motion.DECELERATE, key="hover") + super().enterEvent(event) + + def leaveEvent(self, event): + motion.tween(self, self._hover, 0.0, motion.NORMAL, self._set_hover, motion.EASY_EASE, key="hover") + super().leaveEvent(event) + + def paintEvent(self, _event): + t = theme.current() + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + enabled = self.isEnabled() + cy = self.height() / 2 + scale = 1 - 0.1 * self._press + size = self.BOX * scale + box = QRectF(1 + (self.BOX - size) / 2, cy - size / 2, size, size) + fill = min(1.0, self._p / 0.55) # box fills over the first half, the check draws after + draw = max(0.0, (self._p - 0.35) / 0.65) + edge = _blend(t.border_strong, t.text_muted, self._hover) + edge = _blend(edge.name(), t.text, fill) + if not enabled: + edge.setAlphaF(0.45) + p.setPen(QPen(edge, 1.25)) + p.setBrush(Qt.BrushStyle.NoBrush) + p.drawRoundedRect(box.adjusted(0.6, 0.6, -0.6, -0.6), 3, 3) + if fill > 0: + ink = QColor(t.text if enabled else t.text_muted) + ink.setAlphaF(fill) + inset = (1 - fill) * size * 0.3 + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(ink) + p.drawRoundedRect(box.adjusted(inset, inset, -inset, -inset), 3, 3) + if draw > 0: + x, y, s = box.left(), box.top(), size + pts = [ + QPointF(x + s * 0.24, y + s * 0.52), + QPointF(x + s * 0.43, y + s * 0.70), + QPointF(x + s * 0.77, y + s * 0.32), + ] + pen = QPen(QColor(t.window), 1.9, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin) + p.setPen(pen) + p.drawPath(_partial(pts, draw)) + if self.hasFocus(): + p.setPen(QPen(QColor(t.accent), 1.5)) + p.setBrush(Qt.BrushStyle.NoBrush) + p.drawRoundedRect(box.adjusted(-2.5, -2.5, 2.5, 2.5), 4.5, 4.5) + if self.text(): + p.setPen(QColor(t.text if enabled else t.text_muted)) + p.setFont(self.font()) + rect = QRectF(self.BOX + 9, 0, self.width() - self.BOX - 9, self.height()) + p.drawText(rect, int(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft), self.text()) + + +class TickSlider(QAbstractSlider): + """A ruler with fixed stops and a fader cap that glides between them. + + Stops are (label, value) pairs. ``committed`` fires with the stop's value once + a change is final: on release after dragging, or immediately for keys and clicks. + """ + + committed = Signal(object) + + TRACK_Y = 12 + KNOB_W, KNOB_H = 12, 20 + PAD = 14 + + def __init__(self, stops: list[tuple[str, object]], parent=None): + super().__init__(parent) + self.setOrientation(Qt.Orientation.Horizontal) + self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + self.setPageStep(1) + self._stops: list[tuple[str, object]] = [] + self._pos = 0.0 # knob position in stop units, eased + self._hover = 0.0 + self._grab = 0.0 + self._lit: list[float] = [] # per-stop highlight of the label under the knob + self._drag_x: float | None = None + self._committed = None + self.set_stops(stops) + self.valueChanged.connect(self._on_value) + self.sliderReleased.connect(self._on_release) + + # -- data --------------------------------------------------------------- + + def set_stops(self, stops: list[tuple[str, object]]) -> None: + self._stops = list(stops) + self.blockSignals(True) + self.setRange(0, max(0, len(self._stops) - 1)) + self.blockSignals(False) + self._lit = [1.0 if i == self.value() else 0.0 for i in range(len(self._stops))] + self._pos = float(self.value()) + self.setAccessibleDescription(", ".join(label for label, _ in self._stops)) + self.updateGeometry() + self.update() + + def stops(self) -> list[tuple[str, object]]: + return list(self._stops) + + def stop_value(self): + return self._stops[self.value()][1] if self._stops else None + + def index_of(self, value) -> int: + return next((i for i, (_, v) in enumerate(self._stops) if v == value), -1) + + def set_stop_value(self, value) -> None: + """Select the stop holding *value* without emitting or animating.""" + i = self.index_of(value) + if i < 0: + return + self.blockSignals(True) + self.setValue(i) + self.blockSignals(False) + self._committed = value + self._pos = float(i) + self._lit = [1.0 if j == i else 0.0 for j in range(len(self._stops))] + self.update() + + # -- geometry ----------------------------------------------------------- + + def sizeHint(self) -> QSize: + f = fonts.mono(9, 500, 4) + widest = max((QFontMetrics(f).horizontalAdvance(label.upper()) for label, _ in self._stops), default=20) + return QSize(max(240, (widest + 12) * len(self._stops)), 44) + + def minimumSizeHint(self) -> QSize: + return QSize(200, 44) + + def _x(self, pos: float) -> float: + span = max(1, len(self._stops) - 1) + return self.PAD + (self.width() - 2 * self.PAD) * pos / span + + def _pos_at(self, x: float) -> float: + span = max(1, len(self._stops) - 1) + width = max(1.0, self.width() - 2 * self.PAD) + return max(0.0, min(float(span), (x - self.PAD) / width * span)) + + # -- motion ------------------------------------------------------------- + + def _on_value(self, index: int) -> None: + if self._drag_x is None: + motion.tween(self, self._pos, float(index), motion.GENTLE, self._set_pos, motion.DECELERATE, key="pos") + for i in range(len(self._stops)): + target = 1.0 if i == index else 0.0 + if self._lit[i] != target: + motion.tween( + self, + self._lit[i], + target, + motion.FAST, + lambda v, i=i: self._set_lit(i, v), + motion.EASY_EASE, + key=f"lit{i}", + ) + if not self.isSliderDown(): + self._commit() + + def _on_release(self) -> None: + self._drag_x = None + motion.tween(self, self._pos, float(self.value()), motion.NORMAL, self._set_pos, motion.DECELERATE, key="pos") + self._commit() + + def _commit(self) -> None: + value = self.stop_value() + if value != self._committed: + self._committed = value + self.committed.emit(value) + + def _set_pos(self, v: float) -> None: + self._pos = v + self.update() + + def _set_lit(self, i: int, v: float) -> None: + if i < len(self._lit): + self._lit[i] = v + self.update() + + def _set_hover(self, v: float) -> None: + self._hover = v + self.update() + + def _set_grab(self, v: float) -> None: + self._grab = v + self.update() + + # -- input -------------------------------------------------------------- + + def enterEvent(self, event): + motion.tween(self, self._hover, 1.0, motion.FAST, self._set_hover, motion.DECELERATE, key="hover") + super().enterEvent(event) + + def leaveEvent(self, event): + motion.tween(self, self._hover, 0.0, motion.NORMAL, self._set_hover, motion.EASY_EASE, key="hover") + super().leaveEvent(event) + + def mousePressEvent(self, event): + if event.button() != Qt.MouseButton.LeftButton or not self._stops: + return super().mousePressEvent(event) + x = event.position().x() + on_knob = abs(x - self._x(self._pos)) <= self.KNOB_W + if on_knob: + self._drag_x = x + self.setSliderDown(True) + motion.tween(self, self._grab, 1.0, motion.FASTER, self._set_grab, motion.DECELERATE, key="grab") + else: + self.setValue(round(self._pos_at(x))) # click jumps: the knob glides there + event.accept() + + def mouseMoveEvent(self, event): + if self._drag_x is None: + return super().mouseMoveEvent(event) + self._drag_x = event.position().x() + self._pos = self._pos_at(self._drag_x) + self.setValue(round(self._pos)) + self.update() + + def mouseReleaseEvent(self, event): + if self._drag_x is not None: + motion.tween(self, self._grab, 0.0, motion.FAST, self._set_grab, motion.EASY_EASE, key="grab") + self.setSliderDown(False) + event.accept() + + def wheelEvent(self, event): + if self.hasFocus(): + super().wheelEvent(event) + else: + event.ignore() # let the page scroll instead of changing the value + + # -- paint -------------------------------------------------------------- + + def paintEvent(self, _event): + t = theme.current() + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + enabled = self.isEnabled() + ink = t.text if enabled else t.text_muted + y = self.TRACK_Y + left, right = self._x(0), self._x(max(0, len(self._stops) - 1)) + knob_x = self._x(self._pos) + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(QColor(t.border_strong)) + p.drawRoundedRect(QRectF(left - 3, y - 2, right - left + 6, 4), 2, 2) + p.setBrush(QColor(ink)) + p.drawRoundedRect(QRectF(left - 3, y - 2, knob_x - left + 3, 4), 2, 2) + label_font = fonts.mono(9, 500, 4) + p.setFont(label_font) + metrics = p.fontMetrics() + for i, (label, _value) in enumerate(self._stops): + x = self._x(i) + passed = i <= self._pos + 0.001 + tick = QColor(ink if passed else t.border_strong) + p.setPen(QPen(tick, 1)) + p.drawLine(QPointF(x, y + 5), QPointF(x, y + 9 + 2 * self._lit[i])) + text = label.upper() + color = _blend(t.text_muted, ink, self._lit[i]) + p.setPen(color) + w = metrics.horizontalAdvance(text) + tx = min(max(x - w / 2, 0), self.width() - w) + p.drawText(QPointF(tx, y + 24), text) + # Fader cap: grows a little on hover and when grabbed. + grow = 1.0 * self._hover + 1.5 * self._grab + kw, kh = self.KNOB_W + grow, self.KNOB_H + grow + knob = QRectF(knob_x - kw / 2, y - kh / 2, kw, kh) + p.setPen(QPen(QColor(t.border_strong if enabled else t.border), 1)) + p.setBrush(QColor(t.surface_alt)) + p.drawRoundedRect(knob, 3, 3) + p.setPen(QPen(QColor(ink), 1.5)) + p.drawLine(QPointF(knob_x, knob.top() + 5), QPointF(knob_x, knob.bottom() - 5)) + if self.hasFocus(): + p.setPen(QPen(QColor(t.accent), 1.5)) + p.setBrush(Qt.BrushStyle.NoBrush) + p.drawRoundedRect(knob.adjusted(-2.5, -2.5, 2.5, 2.5), 4.5, 4.5) diff --git a/apptrackr/ui/widgets/other_terms.py b/apptrackr/ui/widgets/other_terms.py new file mode 100644 index 0000000..62dfa96 --- /dev/null +++ b/apptrackr/ui/widgets/other_terms.py @@ -0,0 +1,162 @@ +"""'In other terms': tracked time retold as Everest summit days, Moon trips and novels.""" + +from __future__ import annotations + +from datetime import date + +from PySide6.QtCore import QSize, Qt, QTimer +from PySide6.QtGui import QPainter +from PySide6.QtWidgets import QFrame, QHBoxLayout, QSizePolicy, QVBoxLayout, QWidget + +from ... import perspective +from ...data import db +from .. import fmt, fonts, icons, motion, theme +from .components import Card, SegmentedControl, button, label, vdivider +from .rolling import RollingLabel + +PERIODS = (("today", "Today"), ("week", "This week"), ("all", "All time")) + + +class _Glyph(QWidget): + """Line icon that follows the theme and can change without rebinding.""" + + def __init__(self, size: int = 20, parent=None): + super().__init__(parent) + self.setFixedSize(size, size) + self.name = "" + + def set_name(self, name: str) -> None: + self.name = name + self.update() + + def paintEvent(self, _event): + if self.name: + p = QPainter(self) + p.drawPixmap(0, 0, icons.pixmap(self.name, theme.current().text_dim, self.width())) + + +class FactTile(QFrame): + """One comparison: icon, rolling figure, what it counts, and the basis for the number.""" + + def __init__(self, parent=None): + super().__init__(parent) + self.setProperty("cell", True) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + lay = QVBoxLayout(self) + lay.setContentsMargins(18, 14, 18, 16) + lay.setSpacing(4) + top = QHBoxLayout() + top.setSpacing(10) + self.glyph = _Glyph(20) + top.addWidget(self.glyph, 0, Qt.AlignmentFlag.AlignVCenter) + self.value = RollingLabel("–") + self.value.setFont(fonts.sans(28, 600, tabular=True)) + top.addWidget(self.value, 1) + lay.addLayout(top) + self.what = label("", wrap=True) + self.what.setFont(fonts.sans(13, 500)) + lay.addWidget(self.what) + self.basis = label("", "caption", wrap=True) + lay.addWidget(self.basis) + lay.addStretch(1) + self.key = "" + + def sizeHint(self) -> QSize: + return QSize(220, super().sizeHint().height()) + + def show_fact(self, fact: perspective.Fact | None, animate: bool) -> None: + if fact is None: + self.key = "" + self.glyph.set_name("") + self.value.setText("–") + self.what.setText("") + self.basis.setText("") + return + changed = fact.key != self.key + self.key = fact.key + self.glyph.set_name(fact.icon) + if animate: + self.value.roll_to(fact.value) + else: + self.value.setText(fact.value) + self.what.setText(fact.label) + self.basis.setText(fact.basis) + if animate and changed: + for w in (self.what, self.basis, self.glyph): + motion.fade(w, 0.0, 1.0, motion.GENTLE, motion.DECELERATE) + + +class OtherTermsCard(Card): + """Three comparisons for the chosen period, with a shuffle.""" + + def __init__(self, index: int | None = None, parent=None): + super().__init__("In other terms", "–", parent=parent, index=index) + self.period = SegmentedControl([text for _, text in PERIODS]) + self.period.changed.connect(self._set_period) + self.header_actions.addWidget(self.period) + self.shuffle = button("Shuffle", kind="ghost", icon="refresh-cw", on_click=self._shuffle) + self.shuffle.setToolTip("Show other comparisons") + self.header_actions.addWidget(self.shuffle) + row = QFrame() + row.setProperty("cell", True) + lay = QHBoxLayout(row) + lay.setContentsMargins(0, 0, 0, 0) + lay.setSpacing(0) + self.tiles: list[FactTile] = [] + for i in range(3): + if i: + lay.addWidget(vdivider()) + tile = FactTile() + self.tiles.append(tile) + lay.addWidget(tile, 1) + self.body.addWidget(row) + stored = db.get_setting("perspective_period", "week") + self._period = stored if stored in dict(PERIODS) else "week" + self.period.set_current([key for key, _ in PERIODS].index(self._period)) + self._offset = date.today().toordinal() # a different set each day + self._totals: dict[str, float] = {} + self._shown_offset: int | None = None + self._shown_period: str | None = None + + @property + def current_period(self) -> str: + return self._period + + def set_totals(self, today_ms: float, week_ms: float, all_ms: float) -> None: + """Called on every refresh; figures roll as the totals grow.""" + self._totals = {"today": today_ms, "week": week_ms, "all": all_ms} + self._render() + + def _set_period(self, index: int) -> None: + self._period = PERIODS[index][0] + db.set_setting("perspective_period", self._period) + self._render() + + def _shuffle(self) -> None: + self._offset += 1 + self._render() + + def _render(self) -> None: + ms = self._totals.get(self._period, 0) + minutes = ms / 60000 + phrase = {"today": "today", "week": "this week", "all": "since you started tracking"}[self._period] + if minutes < 1: + self.set_caption(f"Nothing tracked {phrase} yet. Comparisons appear as time adds up.") + for tile in self.tiles: + tile.show_fact(None, False) + self.shuffle.setEnabled(False) + return + self.set_caption(f"{fmt.duration(ms, short=True)} in apps {phrase}. That is about:") + facts = perspective.pick(minutes, len(self.tiles), self._offset) + self.shuffle.setEnabled(perspective.readable_count(minutes) > len(self.tiles)) + animate = self.isVisible() and (self._shown_period is not None) + for i, tile in enumerate(self.tiles): + fact = facts[i] if i < len(facts) else None + delay = ( + i * 70 if animate and (self._shown_offset != self._offset or self._shown_period != self._period) else 0 + ) + if delay: + QTimer.singleShot(int(delay * motion.time_scale), tile, lambda t=tile, f=fact: t.show_fact(f, True)) + else: + tile.show_fact(fact, animate) + self._shown_offset, self._shown_period = self._offset, self._period diff --git a/apptrackr/ui/widgets/rolling.py b/apptrackr/ui/widgets/rolling.py new file mode 100644 index 0000000..0769d85 --- /dev/null +++ b/apptrackr/ui/widgets/rolling.py @@ -0,0 +1,138 @@ +"""Odometer-style text: characters that change roll vertically into place. + +Used for readouts that tick (today's total, the session clock, levels and +credits). Unchanged leading and trailing characters stay put; changed +digits roll right to left with a slight stagger, like a mechanical counter. +""" + +from __future__ import annotations + +import re + +from PySide6.QtCore import QPointF, QRectF, Qt +from PySide6.QtGui import QColor, QFont, QFontMetricsF, QPainter +from PySide6.QtWidgets import QLabel + +from .. import motion + +STAGGER = 0.14 # fraction of the roll between neighbouring characters +MAX_STAGGER = 0.4 + + +def direction(old: str, new: str) -> int: + """+1 when *new* reads as a larger number than *old* (rolls up), else -1.""" + + def key(text: str) -> tuple: + numbers = [int(n) for n in re.findall(r"\d+", text.replace(",", ""))] + return (len(numbers), numbers) + + return 1 if key(new) >= key(old) else -1 + + +def paint_roll( + p: QPainter, + rect: QRectF, + align: Qt.AlignmentFlag, + old: str, + new: str, + progress: float, + font: QFont, + color: QColor, + rising: int = 1, +) -> None: + """Draw *new* inside *rect*, rolling the characters that differ from *old*.""" + fm = QFontMetricsF(font) + + def left_edge(text: str) -> float: + width = fm.horizontalAdvance(text) + if align & Qt.AlignmentFlag.AlignRight: + return rect.right() - width + if align & Qt.AlignmentFlag.AlignHCenter: + return rect.center().x() - width / 2 + return rect.left() + + baseline = rect.center().y() + (fm.ascent() - fm.descent()) / 2 + travel = fm.height() * 0.8 + p.save() + p.setFont(font) + p.setClipRect(rect.adjusted(-2, 0, 2, 0)) + + def draw(text: str, x: float, dy: float, alpha: float) -> None: + if not text or alpha <= 0.01: + return + c = QColor(color) + c.setAlphaF(color.alphaF() * max(0.0, min(1.0, alpha))) + p.setPen(c) + p.drawText(QPointF(x, baseline + dy), text) + + def roll(o: str, xo: float, n: str, xn: float, local: float) -> None: + eased = motion.DECELERATE.valueForProgress(max(0.0, min(1.0, local))) + draw(o, xo, -rising * travel * eased, 1 - eased) + draw(n, xn, rising * travel * (1 - eased), eased) + + if len(old) != len(new): + # Different lengths ("59m" -> "1h 0m"): the whole readout turns over at once. + roll(old, left_edge(old), new, left_edge(new), progress) + p.restore() + return + # Same length: unchanged characters hold still, changed ones roll right to left. + x0 = left_edge(new) + changed = [i for i, (o, n) in enumerate(zip(old, new, strict=True)) if o != n] + step = min(STAGGER, MAX_STAGGER / (len(changed) - 1)) if len(changed) > 1 else 0.0 + span = 1.0 - step * max(0, len(changed) - 1) + x = x0 + for i, (o, n) in enumerate(zip(old, new, strict=True)): + if o == n: + draw(n, x, 0, 1) + else: + rank = len(changed) - 1 - changed.index(i) # rightmost starts first + roll(o, x, n, x, (progress - rank * step) / span) + x += fm.horizontalAdvance(n) + p.restore() + + +class RollingLabel(QLabel): + """QLabel whose roll_to() rolls changed characters; setText() stays instant.""" + + DURATION = motion.SLOW + 120 + + def __init__(self, text: str = "", parent=None): + super().__init__(text, parent) + self._old = "" + self._p = 1.0 + self._rising = 1 + + def roll_to(self, text: str) -> None: + old = self.text() + if text == old: + return + if not motion.enabled() or not self.isVisible() or not old or old in ("–", "-"): + motion.tween(self, 1.0, 1.0, 0, self._set_p, key="roll") # cancels a roll in flight + self.setText(text) + return + self._old, self._rising = old, direction(old, text) + self.setText(text) + self._p = 0.0 + motion.tween(self, 0.0, 1.0, self.DURATION, self._set_p, motion.LINEAR, key="roll") + + def _set_p(self, value: float) -> None: + self._p = value + self.update() + + def paintEvent(self, event): + if self._p >= 1.0 or not self._old: + return super().paintEvent(event) + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.TextAntialiasing) + color = self.palette().color(self.foregroundRole()) + paint_roll( + p, + QRectF(self.contentsRect()), + self.alignment(), + self._old, + self.text(), + self._p, + self.font(), + color, + self._rising, + ) diff --git a/docs/banner-dark.png b/docs/banner-dark.png index 51895fb..e8a456d 100644 Binary files a/docs/banner-dark.png and b/docs/banner-dark.png differ diff --git a/docs/banner-light.png b/docs/banner-light.png index fdc2aec..6b6bb64 100644 Binary files a/docs/banner-light.png and b/docs/banner-light.png differ diff --git a/docs/screenshots/app-detail.png b/docs/screenshots/app-detail.png index a217b16..4a3d328 100644 Binary files a/docs/screenshots/app-detail.png and b/docs/screenshots/app-detail.png differ diff --git a/docs/screenshots/apps.png b/docs/screenshots/apps.png index 9961a0d..e408837 100644 Binary files a/docs/screenshots/apps.png and b/docs/screenshots/apps.png differ diff --git a/docs/screenshots/calendar.png b/docs/screenshots/calendar.png index 8c83045..fc86bb0 100644 Binary files a/docs/screenshots/calendar.png and b/docs/screenshots/calendar.png differ diff --git a/docs/screenshots/dashboard-light.png b/docs/screenshots/dashboard-light.png index 797df2f..a069596 100644 Binary files a/docs/screenshots/dashboard-light.png and b/docs/screenshots/dashboard-light.png differ diff --git a/docs/screenshots/dashboard-perspective.png b/docs/screenshots/dashboard-perspective.png new file mode 100644 index 0000000..acb030a Binary files /dev/null and b/docs/screenshots/dashboard-perspective.png differ diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png index ebebe31..2d659ac 100644 Binary files a/docs/screenshots/dashboard.png and b/docs/screenshots/dashboard.png differ diff --git a/docs/screenshots/demo.gif b/docs/screenshots/demo.gif index a8dba98..0a0502f 100644 Binary files a/docs/screenshots/demo.gif and b/docs/screenshots/demo.gif differ diff --git a/docs/screenshots/rewards.png b/docs/screenshots/rewards.png index ad1732a..4abbd87 100644 Binary files a/docs/screenshots/rewards.png and b/docs/screenshots/rewards.png differ diff --git a/docs/screenshots/settings-appearance.png b/docs/screenshots/settings-appearance.png new file mode 100644 index 0000000..bac1738 Binary files /dev/null and b/docs/screenshots/settings-appearance.png differ diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png index 3308b66..6b5200d 100644 Binary files a/docs/screenshots/settings.png and b/docs/screenshots/settings.png differ diff --git a/docs/screenshots/themes.png b/docs/screenshots/themes.png new file mode 100644 index 0000000..9de3180 Binary files /dev/null and b/docs/screenshots/themes.png differ diff --git a/docs/screenshots/village.png b/docs/screenshots/village.png index d758853..41b598f 100644 Binary files a/docs/screenshots/village.png and b/docs/screenshots/village.png differ diff --git a/docs/social-preview.png b/docs/social-preview.png index 072cb45..66709f8 100644 Binary files a/docs/social-preview.png and b/docs/social-preview.png differ diff --git a/packaging/installer.iss b/packaging/installer.iss index 3261317..652c659 100644 --- a/packaging/installer.iss +++ b/packaging/installer.iss @@ -33,6 +33,11 @@ WizardStyle=modern Name: "desktopicon"; Description: "Create a desktop shortcut"; GroupDescription: "Shortcuts:" Name: "autostart"; Description: "Start AppTrackr when I sign in"; GroupDescription: "Startup:" +[InstallDelete] +; Replace the previous build's runtime wholesale so files from an older version never mix with this one. +; User data lives in %APPDATA%\AppTrackr and is not touched. +Type: filesandordirs; Name: "{app}\_internal" + [Files] Source: "..\dist\AppTrackr\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs diff --git a/scripts/make_art.py b/scripts/make_art.py index a91759e..9108464 100644 --- a/scripts/make_art.py +++ b/scripts/make_art.py @@ -11,7 +11,6 @@ import argparse import os import sys -from dataclasses import replace from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -143,9 +142,7 @@ def social(p, t, w, h): instrument(p, t, QRectF(w - 40 - 270, 40, 270, h - 80), "Today") text(p, 40, h - 40, "github.com/H4ch1Net/AppTrackr", fonts.mono(9, 500, 6), t.text_muted) - accent = theme.ACCENTS[theme.DEFAULT_ACCENT] - dark = replace(theme.GRAPHITE, accent=accent) - light = replace(theme.PAPER, accent=accent) + dark, light = theme.build(theme.DEFAULT_DARK), theme.build(theme.DEFAULT_LIGHT) render("banner-dark.png", dark, 880, 280, banner) render("banner-light.png", light, 880, 280, banner) render("social-preview.png", dark, 640, 320, social) diff --git a/scripts/record_demo.py b/scripts/record_demo.py index 615bb66..e0fbbd4 100644 --- a/scripts/record_demo.py +++ b/scripts/record_demo.py @@ -29,7 +29,8 @@ def main() -> int: parser.add_argument("--width", type=int, default=1280) parser.add_argument("--height", type=int, default=800) parser.add_argument("--scale", type=float, default=0.6, help="GIF scale factor") - parser.add_argument("--fps", type=int, default=25, help="playback frame rate") + parser.add_argument("--fps", type=int, default=20, help="playback frame rate") + parser.add_argument("--colors", type=int, default=112, help="GIF palette size") parser.add_argument( "--slowdown", type=float, default=4.0, help="run animations this many times slower while capturing" ) @@ -112,8 +113,22 @@ def wait(ms: int) -> None: timer.start(interval) # Tour ------------------------------------------------------------------ + def scroll(view, target: int, ms: int = 500) -> None: + bar = view.verticalScrollBar() + motion.tween(view, float(bar.value()), float(target), ms, lambda v: bar.setValue(int(v)), motion.EASY_EASE) + + def scroll_to(view, widget, offset: int = 24) -> None: + y = widget.mapTo(view.widget(), widget.rect().topLeft()).y() + scroll(view, max(0, y - offset)) + window.show_page("dashboard") wait(1700) + dashboard = window._views["dashboard"] + scroll(dashboard, dashboard.verticalScrollBar().maximum()) + wait(900) + dashboard.other_terms._shuffle() + wait(1300) + dashboard.verticalScrollBar().setValue(0) window.show_page("calendar") wait(900) cal = window._views["calendar"] @@ -129,16 +144,29 @@ def wait(ms: int) -> None: wait(800) window._views["apps"].sort._group.button(2).click() wait(1000) - window.open_app(queries.find_app_id("code.exe")) - wait(1200) + window.open_app(queries.find_app_id("discord.exe")) + wait(900) + detail = window._views["app"] + scroll_to(detail, detail.limit, 260) + wait(700) + detail.limit.setValue(detail.limit.index_of(60)) # the fader glides to the new stop + wait(1100) window.show_page("rewards") wait(700) window._views["rewards"]._claim_all() - wait(1500) - window.show_page("dashboard") + wait(1600) + settings = window._views["settings"] + window.show_page("settings") + wait(400) + scroll_to(settings, settings.tiles["Graphite"], 150) + wait(800) + settings.tiles["Midnight"].click() + wait(1200) + settings.tiles["Sage"].click() + wait(1300) + settings.tiles["Paper"].click() wait(700) - db.set_setting("ui_mode", "light") - window.apply_theme() + window.show_page("dashboard") wait(1300) timer.stop() @@ -161,7 +189,9 @@ def wait(ms: int) -> None: kept[-1] = (kept[-1][0], kept[-1][1] + duration) else: kept.append((image, duration)) - images = [img.quantize(colors=128, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE) for img, _ in kept] + images = [ + img.quantize(colors=args.colors, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE) for img, _ in kept + ] durations = [max(20, d) for _, d in kept] out = Path(args.out) out.parent.mkdir(parents=True, exist_ok=True) diff --git a/scripts/screenshots.py b/scripts/screenshots.py index 7b5c6db..fcf2c1e 100644 --- a/scripts/screenshots.py +++ b/scripts/screenshots.py @@ -102,6 +102,70 @@ def shot(name: str) -> None: window.open_app(queries.find_app_id("code.exe")) shot("app-detail") + def scroll_to(view, widget, offset: int = 24) -> None: + y = widget.mapTo(view.widget(), widget.rect().topLeft()).y() + view.verticalScrollBar().setValue(max(0, y - offset)) + + dashboard = window._views["dashboard"] + window.show_page("dashboard") + scroll_to(dashboard, dashboard.other_terms, 380) + shot("dashboard-perspective") + dashboard.verticalScrollBar().setValue(0) + + settings = window._views["settings"] + window.show_page("settings") + scroll_to(settings, settings.mode.parentWidget().parentWidget(), 24) + shot("settings-appearance") + settings.verticalScrollBar().setValue(0) + + # Every palette, each with a different accent, as one montage. + from PySide6.QtCore import QRectF, Qt + from PySide6.QtGui import QColor, QImage, QPainter + + from apptrackr.ui import fonts, theme + + pairs = ( + ("Graphite", "Orange"), + ("Carbon", "Cyan"), + ("Midnight", "Blue"), + ("Paper", "Orange"), + ("Porcelain", "Purple"), + ("Sage", "Green"), + ) + tw, th, gap, cap = 640, 400, 24, 34 + montage = QImage(3 * tw + 4 * gap, 2 * (th + cap) + 3 * gap, QImage.Format.Format_RGB32) + montage.fill(QColor(theme.build("Graphite").window)) + painter = QPainter(montage) + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + window.show_page("dashboard") + for i, (palette, accent) in enumerate(pairs): + kind = "dark" if palette in theme.DARK_PALETTES else "light" + db.set_setting("ui_mode", kind) + db.set_setting(f"ui_{kind}_palette", palette) + db.set_setting("ui_theme", accent) + window.apply_theme() + window._tick() + settle() + window.toast.hide() + image = ( + window.grab() + .toImage() + .scaled(tw, th, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) + ) + x, y = gap + (i % 3) * (tw + gap), gap + (i // 3) * (th + cap + gap) + painter.drawImage(x, y, image) + painter.setPen(QColor("#edebe4")) + painter.setFont(fonts.mono(12, 500, 10)) + painter.drawText( + QRectF(x, y + th + 8, tw, 20), Qt.AlignmentFlag.AlignLeft, f"{palette.upper()} · {accent.upper()}" + ) + painter.end() + montage.save(str(out / "themes.png")) + print(f"wrote {out / 'themes.png'}") + + db.set_setting("ui_dark_palette", theme.DEFAULT_DARK) + db.set_setting("ui_light_palette", theme.DEFAULT_LIGHT) + db.set_setting("ui_theme", theme.DEFAULT_ACCENT) db.set_setting("ui_mode", "light") window.apply_theme() window.show_page("dashboard") diff --git a/tests/fixtures/make_v1_fixture.py b/tests/fixtures/make_v1_fixture.py new file mode 100644 index 0000000..627f0d7 --- /dev/null +++ b/tests/fixtures/make_v1_fixture.py @@ -0,0 +1,120 @@ +"""Regenerate tests/fixtures/v1_0_2.sql: a database written by AppTrackr v1.0.2's own code. + + python tests/fixtures/make_v1_fixture.py + +Checks out the v1.0.2 tag into a temp folder, drives its data, rewards and +village modules through a few days of use (normal, idle-ended, cross-midnight +and unfinished sessions; opens and clicks; claimed and pending rewards; a +building; changed settings) and dumps the result as SQL. Timestamps are fixed, +so the output only changes if this script does. +""" + +from __future__ import annotations + +import os +import sqlite3 +import subprocess +import sys +import tarfile +import tempfile +import time +from datetime import datetime +from io import BytesIO +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +TAG = "v1.0.2" +BASE = 1772366400.0 # 2026-03-01 12:00 UTC +DAY = 86400.0 + + +def main() -> int: + work = Path(tempfile.mkdtemp(prefix="apptrackr-v1-")) + archive = subprocess.run(["git", "-C", str(ROOT), "archive", TAG], check=True, capture_output=True).stdout + with tarfile.open(fileobj=BytesIO(archive)) as tar: + tar.extractall(work / "src", filter="data") + os.environ["APPDATA"] = str(work / "appdata") # v1.0 keeps data.sqlite under %APPDATA%\AppTrackr + sys.path.insert(0, str(work / "src")) + + from apptrackr.data import db, queries, rollup # v1.0.2 modules + from apptrackr.game import state + from apptrackr.rewards import engine, rules + + db.init_db() + code = queries.get_or_create_app("code.exe", icon_path=r"C:\Programs\VS Code\Code.exe") + chrome = queries.get_or_create_app("chrome.exe") + discord = queries.get_or_create_app("discord.exe") + helper = queries.get_or_create_app("steamwebhelper.exe") # folded into steam.exe by the v1.1 migration + steam = queries.get_or_create_app("steam.exe") + queries.set_favorite(code, True) + queries.set_category(code, "Development") + queries.set_category(chrome, "Work") + + def session(app_id: int, start: float, minutes: float, idle: bool = False) -> None: + sid = queries.start_session(app_id, start) + queries.end_session(sid, start + minutes * 60, was_idle=idle) + rollup.rollup_session(sid) + + for d in range(4): + t = BASE + d * DAY + session(code, t, 95) + session(chrome, t + 6000, 40) + session(discord, t + 9000, 25) + session(code, t + 11000, 50, idle=True) # v1.0 dropped idle-ended sessions entirely + session(helper, t + 15000, 12) + session(steam, t + 16000, 30) + day = _day(t) + for _ in range(4 + d): + queries.increment_opens(day, code) + queries.increment_opens(day, chrome) + queries.increment_clicks(day, code, 650 + 100 * d) + session(chrome, BASE + 3 * DAY + 41000, 120) # crosses midnight in most time zones + queries.start_session(discord, BASE + 3 * DAY + 50000) # never ended: v1.0 was closed mid-session + + rules.create_default_rules(code) + rules.enable_app_rewards(code, True) + for d in range(4): + engine.evaluate(_day(BASE + d * DAY)) + pending = [r["event_id"] for r in engine.unclaimed_rewards()] + for event_id in pending[: len(pending) // 2]: + engine.claim_reward(event_id) + village = state.get_village() + village["inventory"].update({"wood": village["inventory"].get("wood", 0) + 40, "stone": 30}) + state._save_village(village) + ok, message = state.build_or_upgrade("workshop") + assert ok, message + db.execute("UPDATE player_profile SET streak_days = 4, last_streak_day = ?", (_day(BASE + 3 * DAY),)) + db.commit() + + for key, value in { + "ui_theme": "Purple", + "idle_threshold_sec": "600", + "track_clicks": "1", + "autostart": "1", + "minimize_to_tray": "0", + "update_url": "https://api.github.com/repos/H4ch1Net/AppTrackr/releases/latest", + "last_update_check_day": "2026-03-04", + }.items(): + db.set_setting(key, value) + + source = sqlite3.connect(str(db._db_path())) + dump = "\n".join(source.iterdump()) + "\n" + out = HERE / "v1_0_2.sql" + out.write_text( + f"-- Written by AppTrackr {TAG} code via tests/fixtures/make_v1_fixture.py. Do not edit.\n" + dump, + encoding="utf-8", + ) + print(f"wrote {out} ({len(dump.splitlines())} lines)") + return 0 + + +def _day(ts: float) -> str: + return datetime.fromtimestamp(ts).date().isoformat() + + +if __name__ == "__main__": + os.environ["TZ"] = "UTC" # fixed day boundaries for the fixture + if hasattr(time, "tzset"): + time.tzset() + sys.exit(main()) diff --git a/tests/fixtures/v1_0_2.sql b/tests/fixtures/v1_0_2.sql new file mode 100644 index 0000000..acdc8c6 --- /dev/null +++ b/tests/fixtures/v1_0_2.sql @@ -0,0 +1,163 @@ +-- Written by AppTrackr v1.0.2 code via tests/fixtures/make_v1_fixture.py. Do not edit. +BEGIN TRANSACTION; +CREATE TABLE apps ( + app_id INTEGER PRIMARY KEY AUTOINCREMENT, + exe_name TEXT NOT NULL UNIQUE, + display_name TEXT, + icon_path TEXT, + is_favorite INTEGER NOT NULL DEFAULT 0, + category TEXT +); +INSERT INTO "apps" VALUES(1,'code.exe','VS Code','C:\Programs\VS Code\Code.exe',1,'Development'); +INSERT INTO "apps" VALUES(2,'chrome.exe','Google Chrome',NULL,0,'Work'); +INSERT INTO "apps" VALUES(3,'discord.exe','Discord',NULL,0,NULL); +INSERT INTO "apps" VALUES(4,'steamwebhelper.exe','Steam',NULL,0,NULL); +INSERT INTO "apps" VALUES(5,'steam.exe','Steam',NULL,0,NULL); +CREATE TABLE daily_rollup ( + day TEXT NOT NULL, + app_id INTEGER NOT NULL REFERENCES apps(app_id), + focused_ms INTEGER NOT NULL DEFAULT 0, + opens_count INTEGER NOT NULL DEFAULT 0, + clicks_count INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (day, app_id) +); +INSERT INTO "daily_rollup" VALUES('2026-03-01',1,5700000,4,650); +INSERT INTO "daily_rollup" VALUES('2026-03-01',2,2400000,1,0); +INSERT INTO "daily_rollup" VALUES('2026-03-01',3,1500000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-01',4,720000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-01',5,1800000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-02',1,5700000,5,750); +INSERT INTO "daily_rollup" VALUES('2026-03-02',2,2400000,1,0); +INSERT INTO "daily_rollup" VALUES('2026-03-02',3,1500000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-02',4,720000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-02',5,1800000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-03',1,5700000,6,850); +INSERT INTO "daily_rollup" VALUES('2026-03-03',2,2400000,1,0); +INSERT INTO "daily_rollup" VALUES('2026-03-03',3,1500000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-03',4,720000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-03',5,1800000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-04',1,5700000,7,950); +INSERT INTO "daily_rollup" VALUES('2026-03-04',2,9600000,1,0); +INSERT INTO "daily_rollup" VALUES('2026-03-04',3,1500000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-04',4,720000,0,0); +INSERT INTO "daily_rollup" VALUES('2026-03-04',5,1800000,0,0); +CREATE TABLE focus_events ( + event_id INTEGER PRIMARY KEY AUTOINCREMENT, + ts REAL NOT NULL, + app_id INTEGER NOT NULL REFERENCES apps(app_id), + window_title_hash TEXT, + event_type TEXT +); +CREATE TABLE player_profile ( + profile_id INTEGER PRIMARY KEY CHECK(profile_id = 1), + xp INTEGER NOT NULL DEFAULT 0, + level INTEGER NOT NULL DEFAULT 1, + credits INTEGER NOT NULL DEFAULT 0, + streak_days INTEGER NOT NULL DEFAULT 0, + last_streak_day TEXT +); +INSERT INTO "player_profile" VALUES(1,110,2,0,4,'2026-03-04'); +CREATE TABLE reward_events ( + event_id INTEGER PRIMARY KEY AUTOINCREMENT, + ts REAL NOT NULL, + app_id INTEGER NOT NULL REFERENCES apps(app_id), + rule_id INTEGER NOT NULL REFERENCES reward_rules(rule_id), + day TEXT NOT NULL, + granted_json TEXT NOT NULL, + claimed INTEGER NOT NULL DEFAULT 0 +); +INSERT INTO "reward_events" VALUES(1,1.79124211643379116e+09,1,1,'2026-03-01','{"xp": 10, "wood": 5}',0); +INSERT INTO "reward_events" VALUES(2,1.79124211643384933e+09,1,1,'2026-03-01','{"xp": 10, "wood": 5}',0); +INSERT INTO "reward_events" VALUES(3,1.79124211643385934e+09,1,1,'2026-03-01','{"xp": 10, "wood": 5}',0); +INSERT INTO "reward_events" VALUES(4,1.7912421164338746e+09,1,2,'2026-03-01','{"xp": 25, "stone": 10}',0); +INSERT INTO "reward_events" VALUES(5,1.79124211643393254e+09,1,7,'2026-03-01','{"xp": 10, "stone": 5}',0); +INSERT INTO "reward_events" VALUES(6,1.79124211643457055e+09,1,1,'2026-03-02','{"xp": 10, "wood": 5}',0); +INSERT INTO "reward_events" VALUES(7,1.79124211643459224e+09,1,1,'2026-03-02','{"xp": 10, "wood": 5}',0); +INSERT INTO "reward_events" VALUES(8,1.79124211643459868e+09,1,1,'2026-03-02','{"xp": 10, "wood": 5}',0); +INSERT INTO "reward_events" VALUES(9,1.79124211643461632e+09,1,2,'2026-03-02','{"xp": 25, "stone": 10}',0); +INSERT INTO "reward_events" VALUES(10,1.79124211643517875e+09,1,1,'2026-03-03','{"xp": 10, "wood": 5}',1); +INSERT INTO "reward_events" VALUES(11,1.79124211643519926e+09,1,1,'2026-03-03','{"xp": 10, "wood": 5}',1); +INSERT INTO "reward_events" VALUES(12,1.79124211643521356e+09,1,1,'2026-03-03','{"xp": 10, "wood": 5}',1); +INSERT INTO "reward_events" VALUES(13,1.79124211643526506e+09,1,2,'2026-03-03','{"xp": 25, "stone": 10}',1); +INSERT INTO "reward_events" VALUES(14,1.79124211643574857e+09,1,1,'2026-03-04','{"xp": 10, "wood": 5}',1); +INSERT INTO "reward_events" VALUES(15,1.79124211643576359e+09,1,1,'2026-03-04','{"xp": 10, "wood": 5}',1); +INSERT INTO "reward_events" VALUES(16,1.79124211643576931e+09,1,1,'2026-03-04','{"xp": 10, "wood": 5}',1); +INSERT INTO "reward_events" VALUES(17,1.79124211643578171e+09,1,2,'2026-03-04','{"xp": 25, "stone": 10}',1); +CREATE TABLE reward_rules ( + rule_id INTEGER PRIMARY KEY AUTOINCREMENT, + app_id INTEGER REFERENCES apps(app_id), + metric TEXT NOT NULL CHECK(metric IN ('focused_ms','opens_count','clicks_count')), + threshold INTEGER NOT NULL, + reward_json TEXT NOT NULL, + repeatable INTEGER NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1 +); +INSERT INTO "reward_rules" VALUES(1,1,'focused_ms',1800000,'{"xp": 10, "wood": 5}',1,1); +INSERT INTO "reward_rules" VALUES(2,1,'focused_ms',3600000,'{"xp": 25, "stone": 10}',1,1); +INSERT INTO "reward_rules" VALUES(3,1,'focused_ms',7200000,'{"xp": 60, "blueprints": 1}',1,1); +INSERT INTO "reward_rules" VALUES(4,1,'focused_ms',18000000,'{"xp": 150, "metal": 20}',1,1); +INSERT INTO "reward_rules" VALUES(5,1,'opens_count',10,'{"xp": 5, "food": 5}',0,1); +INSERT INTO "reward_rules" VALUES(6,1,'opens_count',50,'{"xp": 20, "wood": 10}',0,1); +INSERT INTO "reward_rules" VALUES(7,1,'clicks_count',500,'{"xp": 10, "stone": 5}',0,1); +INSERT INTO "reward_rules" VALUES(8,1,'clicks_count',2000,'{"xp": 30, "metal": 10}',0,1); +CREATE TABLE settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); +INSERT INTO "settings" VALUES('track_window_titles','0'); +INSERT INTO "settings" VALUES('rewards_enabled','1'); +INSERT INTO "settings" VALUES('polling_hz','4'); +INSERT INTO "settings" VALUES('ui_theme','Purple'); +INSERT INTO "settings" VALUES('idle_threshold_sec','600'); +INSERT INTO "settings" VALUES('track_clicks','1'); +INSERT INTO "settings" VALUES('autostart','1'); +INSERT INTO "settings" VALUES('minimize_to_tray','0'); +INSERT INTO "settings" VALUES('update_url','https://api.github.com/repos/H4ch1Net/AppTrackr/releases/latest'); +INSERT INTO "settings" VALUES('last_update_check_day','2026-03-04'); +CREATE TABLE usage_sessions ( + session_id INTEGER PRIMARY KEY AUTOINCREMENT, + app_id INTEGER NOT NULL REFERENCES apps(app_id), + start_ts REAL NOT NULL, + end_ts REAL, + duration_ms INTEGER, + was_idle INTEGER NOT NULL DEFAULT 0 +); +INSERT INTO "usage_sessions" VALUES(1,1,1772366400.0,1772372100.0,5700000,0); +INSERT INTO "usage_sessions" VALUES(2,2,1772372400.0,1772374800.0,2400000,0); +INSERT INTO "usage_sessions" VALUES(3,3,1772375400.0,1772376900.0,1500000,0); +INSERT INTO "usage_sessions" VALUES(4,1,1772377400.0,1772380400.0,3000000,1); +INSERT INTO "usage_sessions" VALUES(5,4,1772381400.0,1772382120.0,720000,0); +INSERT INTO "usage_sessions" VALUES(6,5,1772382400.0,1772384200.0,1800000,0); +INSERT INTO "usage_sessions" VALUES(7,1,1772452800.0,1772458500.0,5700000,0); +INSERT INTO "usage_sessions" VALUES(8,2,1772458800.0,1772461200.0,2400000,0); +INSERT INTO "usage_sessions" VALUES(9,3,1772461800.0,1772463300.0,1500000,0); +INSERT INTO "usage_sessions" VALUES(10,1,1772463800.0,1772466800.0,3000000,1); +INSERT INTO "usage_sessions" VALUES(11,4,1772467800.0,1772468520.0,720000,0); +INSERT INTO "usage_sessions" VALUES(12,5,1772468800.0,1772470600.0,1800000,0); +INSERT INTO "usage_sessions" VALUES(13,1,1772539200.0,1772544900.0,5700000,0); +INSERT INTO "usage_sessions" VALUES(14,2,1772545200.0,1772547600.0,2400000,0); +INSERT INTO "usage_sessions" VALUES(15,3,1772548200.0,1772549700.0,1500000,0); +INSERT INTO "usage_sessions" VALUES(16,1,1772550200.0,1772553200.0,3000000,1); +INSERT INTO "usage_sessions" VALUES(17,4,1772554200.0,1772554920.0,720000,0); +INSERT INTO "usage_sessions" VALUES(18,5,1772555200.0,1772557000.0,1800000,0); +INSERT INTO "usage_sessions" VALUES(19,1,1772625600.0,1772631300.0,5700000,0); +INSERT INTO "usage_sessions" VALUES(20,2,1772631600.0,1772634000.0,2400000,0); +INSERT INTO "usage_sessions" VALUES(21,3,1772634600.0,1772636100.0,1500000,0); +INSERT INTO "usage_sessions" VALUES(22,1,1772636600.0,1772639600.0,3000000,1); +INSERT INTO "usage_sessions" VALUES(23,4,1772640600.0,1772641320.0,720000,0); +INSERT INTO "usage_sessions" VALUES(24,5,1772641600.0,1772643400.0,1800000,0); +INSERT INTO "usage_sessions" VALUES(25,2,1772666600.0,1772673800.0,7200000,0); +INSERT INTO "usage_sessions" VALUES(26,3,1772675600.0,NULL,NULL,0); +CREATE TABLE village_state ( + profile_id INTEGER PRIMARY KEY CHECK(profile_id = 1) REFERENCES player_profile(profile_id), + state_json TEXT NOT NULL DEFAULT '{}' +); +INSERT INTO "village_state" VALUES(1,'{"buildings": {"workshop": {"level": 1}}, "villagers": 0, "inventory": {"wood": 50, "stone": 20, "metal": 0, "food": 0, "blueprints": 0}}'); +CREATE INDEX idx_sessions_app ON usage_sessions(app_id); +CREATE INDEX idx_sessions_start ON usage_sessions(start_ts); +DELETE FROM "sqlite_sequence"; +INSERT INTO "sqlite_sequence" VALUES('apps',5); +INSERT INTO "sqlite_sequence" VALUES('usage_sessions',26); +INSERT INTO "sqlite_sequence" VALUES('reward_rules',8); +INSERT INTO "sqlite_sequence" VALUES('reward_events',17); +COMMIT; diff --git a/tests/test_perspective.py b/tests/test_perspective.py new file mode 100644 index 0000000..6f05b91 --- /dev/null +++ b/tests/test_perspective.py @@ -0,0 +1,46 @@ +"""'In other terms' comparisons: readable picks, honest labels.""" + +from apptrackr import perspective as pv +from apptrackr.paths import assets_dir + + +def _stick(key: str) -> pv.Yardstick: + return next(s for s in pv.YARDSTICKS if s.key == key) + + +def test_counts_and_percentages(): + everest = _stick("everest") + assert pv.describe(28 * 60, everest).value == "2" + assert pv.describe(28 * 60, everest).label == "Everest summit days" + assert pv.describe(14 * 60, everest).label == "Everest summit day" # singular at exactly one + half = pv.describe(7 * 60, everest) + assert half.value == "50%" and half.label.startswith("of an Everest") + assert pv.describe(14 * 60 * 2.4, everest).value == "2.4" + assert pv.describe(14 * 60 * 1234, everest).value == "1,234" + + +def test_special_phrasings(): + assert pv.describe(5, _stick("walk")).value == "417 m" # short walks read in metres + assert pv.describe(600 * 60 * 2.5, _stick("language")).value == "2.5×" + + +def test_pick_is_varied_and_readable(): + for minutes in (5, 90, 283, 3000, 36000, 300000): + facts = pv.pick(minutes, 3) + assert 1 <= len(facts) <= 3 + assert len({f.key for f in facts}) == len(facts) + for f in facts: + assert 0.02 <= f.ratio <= _stick(f.key).max_count + assert pv.pick(0, 3) == [] + + +def test_shuffle_rotates(): + first = [f.key for f in pv.pick(3000, 3, offset=0)] + second = [f.key for f in pv.pick(3000, 3, offset=1)] + assert first != second + + +def test_every_yardstick_has_an_icon(): + for stick in pv.YARDSTICKS: + assert (assets_dir() / "icons" / f"{stick.icon}.svg").exists(), stick.icon + assert stick.basis and stick.many and stick.part diff --git a/tests/test_theme.py b/tests/test_theme.py new file mode 100644 index 0000000..900f695 --- /dev/null +++ b/tests/test_theme.py @@ -0,0 +1,44 @@ +"""Every palette and accent combination keeps its contrast promises.""" + +import pytest + +pytest.importorskip("PySide6.QtGui") + +from apptrackr.ui import theme # noqa: E402 + +COMBOS = [(p, a) for p in theme.PALETTES for a in theme.ACCENTS] + + +@pytest.mark.parametrize("palette,accent", COMBOS) +def test_contrast(palette, accent): + t = theme.build(palette, accent) + c = theme.contrast + for bg in (t.window, t.surface, t.sidebar, t.surface_alt): + assert c(t.text_muted, bg) >= 4.5, ("muted", bg) + assert c(t.text_dim, bg) >= 4.5, ("dim", bg) + assert c(t.accent, t.surface) >= 3.0 # bars, indicators and rings + assert c(t.accent, t.window) >= 3.0 + assert c(t.accent_text, t.window) >= 4.5 + assert c(t.accent_text, t.surface) >= 4.5 + assert c(t.on_accent, t.accent) >= 4.5 # primary button labels + assert c(t.ink, t.surface) >= 3.0 # history bars + + +def test_palettes_split_by_mode(): + assert all(t.dark for t in theme.DARK_PALETTES.values()) + assert not any(t.dark for t in theme.LIGHT_PALETTES.values()) + assert theme.DEFAULT_DARK in theme.DARK_PALETTES and theme.DEFAULT_LIGHT in theme.LIGHT_PALETTES + + +def test_configure_picks_palette_per_mode(): + try: + assert theme.configure("dark", "Blue", dark_palette="Midnight", light_palette="Sage").name == "Midnight" + assert theme.configure("light").name == "Sage" + assert theme.configure("system", system_dark=True).name == "Midnight" + assert theme.configure("system", system_dark=False).name == "Sage" + # A palette of the wrong kind is ignored rather than shown in the wrong mode. + assert theme.configure("dark", dark_palette="Paper").name == "Midnight" + finally: + theme.configure( + "dark", theme.DEFAULT_ACCENT, dark_palette=theme.DEFAULT_DARK, light_palette=theme.DEFAULT_LIGHT + ) diff --git a/tests/test_ui.py b/tests/test_ui.py index b2ee70c..b6ec485 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -127,3 +127,91 @@ def test_formatters(): assert fmt.reward({"wood": 5, "xp": 10}) == "+10 XP +5 wood" assert fmt.percent_change(150, 100) == "+50%" assert fmt.percent_change(1, 0) is None + + +def test_tick_slider_commits_final_values(qapp): + from PySide6.QtCore import Qt + from PySide6.QtTest import QTest + + from apptrackr.ui.widgets.controls import TickSlider + + slider = TickSlider([("Off", 0), ("15m", 15), ("30m", 30)]) + slider.resize(300, 44) + slider.show() + got = [] + slider.committed.connect(got.append) + slider.set_stop_value(15) + assert slider.stop_value() == 15 and got == [] # programmatic selection is silent + slider.setFocus() + QTest.keyClick(slider, Qt.Key.Key_Right) + assert got == [30] + slider.setSliderDown(True) + slider.setValue(0) + assert got == [30] # nothing while dragging + slider.setSliderDown(False) + assert got == [30, 0] + slider.set_stops([("Off", 0), ("20m", 20), ("30m", 30)]) + assert slider.index_of(20) == 1 + + +def test_notification_kinds(window, qapp): + settings = window._views["settings"] + window.show_page("settings") + qapp.processEvents() + box = settings.notify_boxes["streaks"] + assert box.isChecked() + box.click() + assert db.get_bool("notify_streaks", True) is False + settings.notifications.click() # master switch off disables the kinds + assert not box.isEnabled() + settings.notifications.click() + assert box.isEnabled() + + class FakeTray: + def __init__(self): + self.shown = [] + + def showMessage(self, title, *_args): # noqa: N802 - Qt naming + self.shown.append(title) + + def __getattr__(self, _name): + return lambda *a, **k: None + + tray = FakeTray() + window._tray = tray + window.hide() + window.notify("Streak", "x", kind="streaks") + window.notify("Daily limit reached", "y", kind="limits") + window._tray = None + assert tray.shown == ["Daily limit reached"] + + +def test_palette_tiles_switch_theme(window, qapp): + from apptrackr.ui import theme + + settings = window._views["settings"] + window.show_page("settings") + qapp.processEvents() + settings.tiles["Midnight"].click() + assert theme.current().name == "Midnight" and db.get_setting("ui_dark_palette") == "Midnight" + settings.tiles["Sage"].click() + assert theme.current().name == "Sage" and db.get_setting("ui_mode") == "light" + assert settings.tiles["Midnight"].isChecked() and settings.tiles["Sage"].isChecked() + assert settings.tiles["Sage"].active and not settings.tiles["Midnight"].active + + +def test_other_terms_card(window, qapp): + dash = window._views["dashboard"] + window.show_page("dashboard") + window._tick() + qapp.processEvents() + card = dash.other_terms + shown = [t for t in card.tiles if t.key] + assert shown, "comparisons should render for demo data" + keys = [t.key for t in card.tiles] + card._shuffle() + qapp.processEvents() + assert [t.key for t in card.tiles] != keys or not card.shuffle.isEnabled() + card.period._group.button(2).click() + qapp.processEvents() + assert card.current_period == "all" and db.get_setting("perspective_period") == "all" diff --git a/tests/test_upgrade.py b/tests/test_upgrade.py new file mode 100644 index 0000000..6a6f616 --- /dev/null +++ b/tests/test_upgrade.py @@ -0,0 +1,304 @@ +"""Upgrading from older releases keeps every record and keeps tracking. + +The fixture is a database written by AppTrackr v1.0.2's own code (see +tests/fixtures/make_v1_fixture.py), so these tests exercise the real upgrade. +""" + +import json +import re +import sqlite3 +from datetime import date, datetime, timedelta +from pathlib import Path + +import pytest + +from apptrackr import __version__, paths +from apptrackr.data import db, queries + +FIXTURES = Path(__file__).parent / "fixtures" +ROOT = Path(__file__).resolve().parents[1] + + +def _load_v1(folder: Path) -> Path: + folder.mkdir(parents=True, exist_ok=True) + path = folder / "data.sqlite" + conn = sqlite3.connect(path) + conn.executescript((FIXTURES / "v1_0_2.sql").read_text(encoding="utf-8")) + conn.close() + return path + + +def _snapshot(path: Path) -> dict: + conn = sqlite3.connect(path) + conn.row_factory = sqlite3.Row + q = lambda sql: [dict(r) for r in conn.execute(sql)] # noqa: E731 + snap = { + "apps": {r["exe_name"]: r for r in q("SELECT * FROM apps")}, + "sessions": q("SELECT * FROM usage_sessions ORDER BY session_id"), + "rollup": q("SELECT * FROM daily_rollup"), + "rules": q("SELECT * FROM reward_rules ORDER BY rule_id"), + "events": q("SELECT * FROM reward_events ORDER BY event_id"), + "profile": q("SELECT * FROM player_profile")[0], + "village": json.loads(q("SELECT state_json FROM village_state")[0]["state_json"]), + "settings": {r["key"]: r["value"] for r in q("SELECT * FROM settings")}, + "user_version": conn.execute("PRAGMA user_version").fetchone()[0], + } + conn.close() + return snap + + +@pytest.fixture +def upgraded(tmp_path): + """A v1.0.2 database opened by this version, plus snapshots from before and after.""" + folder = tmp_path / "AppTrackr" + path = _load_v1(folder) + before = _snapshot(path) + paths.set_data_dir(folder) + db.configure(path) + db.init_db() + db.close() + return folder, before, _snapshot(path) + + +def _app_totals(snap: dict, field: str = "focused_ms") -> dict[str, int]: + names = {a["app_id"]: exe for exe, a in snap["apps"].items()} + totals: dict[str, int] = {} + for row in snap["rollup"]: + exe = names[row["app_id"]] + totals[exe] = totals.get(exe, 0) + row[field] + return totals + + +def test_fixture_is_a_v1_database(): + snap = _snapshot(_load_v1(Path(__import__("tempfile").mkdtemp()) / "AppTrackr")) + assert snap["user_version"] == 0 + assert "is_hidden" not in next(iter(snap["apps"].values())) + assert any(s["end_ts"] is None for s in snap["sessions"]) # v1.0 was closed mid-session + assert any(s["was_idle"] for s in snap["sessions"]) + + +def test_schema_is_upgraded_and_backed_up(upgraded): + folder, before, after = upgraded + assert after["user_version"] == db.SCHEMA_VERSION + assert {"is_hidden", "daily_limit_ms"} <= set(next(iter(after["apps"].values()))) + backups = list(folder.glob("data-backup-schema0-*.sqlite")) + assert len(backups) == 1 + assert _snapshot(backups[0]) == before # the backup is the untouched v1.0 database + + +def test_apps_and_preferences_survive(upgraded): + _folder, before, after = upgraded + # The Steam helper process is folded into Steam; every other app is kept as it was. + assert set(after["apps"]) == set(before["apps"]) - {"steamwebhelper.exe"} + for exe in ("code.exe", "chrome.exe", "discord.exe"): + for field in ("display_name", "icon_path", "is_favorite", "category"): + assert after["apps"][exe][field] == before["apps"][exe][field] + + +def test_focused_time_is_kept_and_recovered(upgraded): + _folder, before, after = upgraded + idle_ms = int(before["settings"]["idle_threshold_sec"]) * 1000 + alias = {"steamwebhelper.exe": "steam.exe"} + names = {a["app_id"]: exe for exe, a in before["apps"].items()} + expected: dict[str, int] = {} + for s in before["sessions"]: + if s["end_ts"] is None: + continue + ms = s["duration_ms"] - (idle_ms if s["was_idle"] else 0) + exe = alias.get(names[s["app_id"]], names[s["app_id"]]) + expected[exe] = expected.get(exe, 0) + max(0, ms) + assert _app_totals(after) == expected + + old = _app_totals(before) + old["steam.exe"] += old.pop("steamwebhelper.exe") + for exe, ms in old.items(): + assert _app_totals(after)[exe] >= ms # nothing v1.0 counted is lost + assert sum(_app_totals(after).values()) > sum(old.values()) # idle-ended sessions are recovered + + +def test_opens_clicks_and_sessions_survive(upgraded): + _folder, before, after = upgraded + for field in ("opens_count", "clicks_count"): + old = _app_totals(before, field) + old["steam.exe"] = old.get("steam.exe", 0) + old.pop("steamwebhelper.exe", 0) + assert _app_totals(after, field) == old + closed = [s for s in before["sessions"] if s["end_ts"] is not None] + assert len(after["sessions"]) == len(closed) + + +def test_rewards_village_and_settings_survive(upgraded): + _folder, before, after = upgraded + assert len(after["rules"]) == len(before["rules"]) + assert [(e["event_id"], e["claimed"]) for e in after["events"]] == [ + (e["event_id"], e["claimed"]) for e in before["events"] + ] + assert after["profile"] == before["profile"] + assert after["village"] == before["village"] + for key, value in before["settings"].items(): + assert after["settings"][key] == value + + +def test_upgraded_data_works_in_this_version(upgraded): + folder, before, _after = upgraded + db.configure(folder / "data.sqlite") + from apptrackr.game import state as game_state + from apptrackr.rewards import engine + from apptrackr.ui import theme + + assert game_state.building_level(game_state.get_village(), "workshop") == 1 + # Upgrading the day after the last streak day: the running streak carries over. + db.execute("UPDATE player_profile SET last_streak_day = ?", ((date.today() - timedelta(days=1)).isoformat(),)) + db.commit() + assert engine.get_profile()["streak"] == before["profile"]["streak_days"] + pending = engine.unclaimed_rewards() + assert len(pending) == sum(1 for e in before["events"] if not e["claimed"]) + xp = engine.get_profile()["xp"] + applied = engine.claim_reward(pending[0]["event_id"]) + assert engine.get_profile()["xp"] == xp + applied.get("xp", 0) + assert theme.configure(accent=db.get_setting("ui_theme")).accent == theme.build("Graphite", "Purple").accent + assert db.get_int("idle_threshold_sec") == 600 and db.get_bool("minimize_to_tray", True) is False + theme.configure("dark", theme.DEFAULT_ACCENT) + + +def test_tracking_continues_after_upgrade(upgraded): + folder, _before, _after = upgraded + db.configure(folder / "data.sqlite") + from test_tracker import FakePlatform + + from apptrackr.core.tracker import Tracker + + start = datetime(2026, 10, 5, 12, 0).timestamp() + clock = type("Clock", (), {"t": start, "__call__": lambda self: self.t})() + platform = FakePlatform() + tracker = Tracker(platform, clock=clock) + tracker.reload_settings() + platform.exe = "chrome.exe" + tracker.tick() + for _ in range(24): + clock.t += 5 + tracker.tick() + tracker.stop() + app_id = queries.find_app_id("chrome.exe") + assert queries.app_usage_on("2026-10-05", app_id) == 120_000 + assert queries.get_app(app_id)["category"] == "Work" # same app row, not a new one + + +def test_second_start_does_nothing(upgraded): + folder, _before, after = upgraded + db.configure(folder / "data.sqlite") + db.init_db() + db.close() + assert _snapshot(folder / "data.sqlite") == after + assert len(list(folder.glob("data-backup-*.sqlite"))) == 1 + + +def test_failed_migration_leaves_data_untouched(tmp_path, monkeypatch): + folder = tmp_path / "AppTrackr" + path = _load_v1(folder) + before = _snapshot(path) + + def broken(conn): + conn.execute("ALTER TABLE apps ADD COLUMN is_hidden INTEGER NOT NULL DEFAULT 0") + conn.execute("UPDATE daily_rollup SET focused_ms = 0") + raise RuntimeError("simulated crash halfway through an upgrade") + + monkeypatch.setattr(db, "_MIGRATIONS", [(1, broken)]) + paths.set_data_dir(folder) + db.configure(path) + with pytest.raises(RuntimeError): + db.init_db() + db.close() + after = _snapshot(path) + assert after["user_version"] == 0 + assert after["apps"] == before["apps"] and after["rollup"] == before["rollup"] + + +def test_v1_updater_finds_this_release(): + """v1.0.x checks releases with this logic (copied verbatim from v1.0.2's updater/check.py).""" + + def parse_version(v): + return tuple(int(x) for x in v.strip().lstrip("v").split(".")) + + def v1_check(data, current="1.0.0"): + remote_version = data.get("tag_name", "").lstrip("v") + if parse_version(remote_version) > parse_version(current): + for asset in data.get("assets", []): + if asset.get("name", "").endswith(".exe"): + return {"version": remote_version, "url": asset["browser_download_url"]} + return None + + assert re.fullmatch(r"\d+\.\d+\.\d+", __version__), "v1.0 can only parse plain x.y.z tags" + workflow = (ROOT / ".github" / "workflows" / "release-windows.yml").read_text(encoding="utf-8") + uploads = re.findall(r"(?:packaging/Output|dist)/(AppTrackr_[A-Za-z]+\.(?:exe|zip))", workflow) + assert sorted(set(uploads)) == ["AppTrackr_Portable.zip", "AppTrackr_Setup.exe"] + release = { + "tag_name": f"v{__version__}", + "assets": [{"name": n, "browser_download_url": f"https://example.invalid/{n}"} for n in sorted(set(uploads))], + } + assert v1_check(release) == {"version": __version__, "url": "https://example.invalid/AppTrackr_Setup.exe"} + + +def test_installer_upgrades_in_place(): + iss = (ROOT / "packaging" / "installer.iss").read_text(encoding="utf-8") + assert re.search(r"^AppId=AppTrackr$", iss, re.M) # v1.0's script had no AppId, so Inno used AppName + assert "DefaultDirName={localappdata}\\AppTrackr" in iss + assert "CloseApplications=force" in iss + assert re.search(r"^Type: filesandordirs; Name: \"\{app\}\\_internal\"", iss, re.M) # no stale libraries + + +def test_startup_entry_repair(): + from apptrackr.core.autostart import needs_repair + + ours = r"C:\Users\me\AppData\Local\AppTrackr\AppTrackr.exe" + exists = lambda p: p.lower() == ours.lower() # noqa: E731 + assert needs_repair(f'"{ours}"', ours, exists) # v1.0 entry: no --minimized + assert needs_repair(r'"D:\Downloads\AppTrackr.exe"', ours, lambda p: True) # v1.0 portable copy + assert not needs_repair(f'"{ours}" --minimized', ours, exists) + assert needs_repair(r'"C:\Old\AppTrackr.exe" --minimized', ours, exists) # points at a removed copy + assert not needs_repair(r'"D:\Portable\AppTrackr.exe" --minimized', ours, lambda p: True) # another 1.1+ copy + + +def test_newer_database_opens_untouched(tmp_path): + folder = tmp_path / "AppTrackr" + path = _load_v1(folder) + paths.set_data_dir(folder) + db.configure(path) + db.init_db() + db.execute(f"PRAGMA user_version = {db.SCHEMA_VERSION + 5}") # as if a later version had migrated it + db.commit() + db.close() + for backup in folder.glob("data-backup-*.sqlite"): + backup.unlink() + db.init_db() + db.close() + assert _snapshot(path)["user_version"] == db.SCHEMA_VERSION + 5 + assert not list(folder.glob("data-backup-*.sqlite")) + + +def test_every_page_opens_on_upgraded_data(upgraded): + pytest.importorskip("PySide6.QtWidgets") + from PySide6.QtWidgets import QApplication + + from apptrackr.core.platform import NullPlatform + from apptrackr.core.tracker import Tracker + from apptrackr.ui.main import MainWindow, prepare_app + + folder, _before, _after = upgraded + db.configure(folder / "data.sqlite") + app = QApplication.instance() or QApplication([]) + prepare_app(app) + tracker = Tracker(NullPlatform()) + win = MainWindow(tracker) + win.show() + for page in ("dashboard", "calendar", "apps", "rewards", "village", "settings"): + win.show_page(page) + app.processEvents() + assert win._stack.currentWidget() is win._views[page] + win.open_app(queries.find_app_id("code.exe")) + app.processEvents() + assert win._views["app"].title.text() == "VS Code" + tracker.stop() + win._quitting = True + win.close() + win.deleteLater() + app.processEvents()