-A Windows desktop app that tracks which applications you actually use, and for how long. Time is counted only while an app has focus, so the numbers reflect reality rather than just "was it open."
+
+
+
+
-## Screenshots
+Foreground app usage tracker for Windows. Counts the time each app actually has focus,
+shows it as a dashboard, calendar and per-app history, and stays out of the way in the tray.
+
+[](https://github.com/H4ch1Net/AppTrackr/actions/workflows/ci.yml)
+[](https://github.com/H4ch1Net/AppTrackr/releases/latest)
+
+
+[](LICENSE)
+
+
+
+
-### Dashboard
-
+## Overview
-### Calendar
-
+Most "screen time" numbers measure how long a window was open. AppTrackr measures how long it was
+in front of you: time is credited only to the focused app, stops when you go idle or lock the
+screen, and is written to a local SQLite database every 30 seconds. Nothing leaves your machine.
-### Apps
-
+On top of the raw numbers it adds the things you reach for next: a heatmap calendar, per-app
+trends and sessions, daily limits with notifications, and an optional rewards layer that turns
+time in chosen apps into XP and a small village-building game.
## Features
-- **Foreground-only tracking.** Background time is never counted. If you switched away, the clock stops.
-- **Idle detection.** Configurable idle threshold (default 5 minutes) pauses tracking when you step away.
-- **Dashboard.** Live view of what you are currently using, today's total, this week's total, and your top apps.
-- **Calendar view.** Browse usage by day to spot patterns over time.
-- **Per-app detail.** Open any app to see its full session history and totals.
-- **Rewards system.** Optional progression layer with XP, levels, credits, and a resource-collection mini-game tied to your usage goals. Can be disabled entirely.
-- **Streak tracking.** Keeps a daily streak for apps you have marked as favorites, based on 30+ minutes of focused use.
-- **Theme presets.** Several accent color options. Changes apply on next launch.
-- **System tray and autostart.** Minimize to tray and optionally launch at login via the Windows registry.
-- **Data export.** Export your history to CSV or JSON. Backup and restore the SQLite database directly.
-- **In-app updates.** Point the update feed at a GitHub releases API endpoint and check manually or automatically on startup.
+| 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 |
+| 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 |
+| 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 |
+| 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 |
-## Requirements
+## Screenshots
-- Windows 10 or 11
-- Python 3.10 or newer (for running from source)
+
+
+
Dashboard with the live session, today by hour and top apps
+
Calendar heatmap with the selected day's breakdown
+
+
+
All apps for a period, filterable and sortable
+
Per-app history, limit, rewards and sessions
+
+
+
Level progress, pending rewards and earning apps
+
Village: buildings, inventory and market
+
+
+
Settings apply immediately
+
Light theme
+
+
+
+Screenshots and the animation above are generated from demo data with `python scripts/screenshots.py`
+and `python scripts/record_demo.py`.
+
+## Design
+
+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.
+
+| Element | Choice |
+| --- | --- |
+| Type | Instrument Sans (interface, tabular figures), Martian Mono (labels) |
+| Themes | Graphite (dark) and Paper (light), or follow Windows |
+| Signal color | Orange `#ff6b1a` by default, 8 presets in Settings |
+| Shape | 6 px panels, 4 px controls, 1 px borders, no shadows |
## Installation
-Download the latest release from the [Releases](../../releases) page.
+Download the latest build from [Releases](https://github.com/H4ch1Net/AppTrackr/releases/latest).
-**Standard installer (recommended)**
+| Package | Use it when |
+| --- | --- |
+| `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`. |
-1. Download `AppTrackr_Setup.exe`.
-2. Run the installer and follow the prompts.
-3. Launch AppTrackr from the Start Menu or desktop shortcut.
+Requirements: Windows 10 or 11 (64-bit). Upgrading over v1.0 keeps your data and migrates it on first start.
-**Portable build**
+## Usage
-1. Download `AppTrackr_Portable.zip`.
-2. Extract it anywhere.
-3. Run `AppTrackr.exe`.
+AppTrackr starts tracking as soon as it runs. Closing the window keeps it running in the tray;
+use **Quit** from the tray menu (or Ctrl+Q) to stop it.
-## Developer Setup
+- **Pause.** Click the tracking module at the bottom of the sidebar, use the dashboard button, or pick
+ *Pause for* in the tray menu to resume automatically after 15 minutes to 2 hours.
+- **Daily limits.** Open an app and choose a limit. You get one notification per day when it is passed;
+ the dashboard and charts mark the limit.
+- **Exclude an app.** Right-click it in any list and choose *Exclude from tracking*. Manage exclusions in
+ Settings.
+- **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.
-Clone the repo and install in editable mode with dev dependencies:
+### Keyboard shortcuts
-```bash
-pip install -e ".[dev]"
-```
+| Keys | Action |
+| --- | --- |
+| Ctrl+1 to Ctrl+5 | Dashboard, Calendar, Apps, Rewards, Village |
+| Ctrl+, | Settings |
+| Ctrl+F | Search apps |
+| Ctrl+Shift+P | Pause or resume tracking |
+| Esc / Alt+Left | Back from an app page |
+| LeftRightUpDown, PgUpPgDn | Move through days and months in the calendar |
+| F5 | Refresh the current page |
-Run the app:
+### Command line
-```bash
-python -m apptrackr
+```text
+AppTrackr.exe [--minimized] [--demo] [--data-dir PATH] [--debug] [--version]
```
-## Building from Source
+| Option | Effect |
+| --- | --- |
+| `--minimized` | Start hidden in the tray (used by the sign-in entry) |
+| `--demo` | Use generated sample data in a temporary folder. Nothing real is read or recorded. |
+| `--data-dir PATH` | Keep the database and logs in `PATH` |
+| `--debug` | Verbose logging |
-**PyInstaller bundle**
+Starting AppTrackr while it is already running brings the existing window to the front.
-```bash
-pyinstaller packaging/apptrackr.spec
-```
+### Motion
+
+Animations use Fluent 2 timing (100 to 400 ms, decelerate curves for things that enter, easy-ease for
+things that move) and only run in response to a change: a page opens, a filter changes, a value updates
+or an item is removed. Background refreshes morph values in place instead of replaying entrances.
+AppTrackr follows Windows' *Settings > Accessibility > Visual effects > Animation effects*; the
+*Animations* switch under Settings > Appearance overrides it.
+
+## Configuration
+
+All settings live in the app and apply immediately. Storage locations and two environment
+variables cover the rest.
-**Inno Setup installer**
+| Item | Default |
+| --- | --- |
+| Database | `%APPDATA%\AppTrackr\data.sqlite` |
+| Logs | `%APPDATA%\AppTrackr\logs\apptrackr.log` (rotated, 3 x 1 MB) |
+| `APPTRACKR_DATA_DIR` | Overrides the data folder, same as `--data-dir` |
+| `APPTRACKR_UPDATE_URL` | Alternative release feed (GitHub releases API URL) |
-1. Open `packaging/installer.iss` in Inno Setup.
-2. Compile the script.
-3. The installer is written to `packaging/Output/AppTrackr_Setup.exe`.
+
+How time is counted
-## Release Automation
+- The tracker samples the foreground window 4 times per second.
+- Focus on the shell (desktop, taskbar, Start, lock screen) and on background helpers is not credited to any app.
+- When there has been no input for the idle timeout (5 minutes by default), the session is closed at the
+ moment of your last input, so idle time is never counted.
+- Locking the screen closes the session the same way.
+- Committed time is split at local midnight, so late sessions land on the right days.
+- A *launch* is an app going from not running to running. Multi-process apps such as browsers count once.
+- Click counting (off by default) stores only a number per app per day.
-The workflow at `.github/workflows/release-windows.yml` handles the full build and publish pipeline. Push a version tag to trigger it:
+
+
+## Privacy
+
+- Everything is stored locally in one SQLite file. There is no account, telemetry or cloud sync.
+- Window titles, keystrokes and screen contents are never recorded.
+- The only network request is the optional daily update check to `api.github.com`.
+
+## Development
+
+Requires Python 3.10 or newer. Tracking only works on Windows, but the UI, tests and demo mode run
+anywhere PySide6 does.
```bash
-git tag v1.0.0
-git push origin v1.0.0
+git clone https://github.com/H4ch1Net/AppTrackr.git
+cd AppTrackr
+python -m venv .venv
+.venv\Scripts\activate # source .venv/bin/activate on Linux/macOS
+pip install -e ".[dev]"
+
+python -m apptrackr --demo # explore with sample data
+python -m apptrackr # real tracking (Windows)
```
-The workflow builds the PyInstaller bundle, zips it as a portable archive, compiles the Inno Setup installer, and uploads both to the GitHub release.
+| Task | Command |
+| --- | --- |
+| Tests | `pytest` |
+| Lint and format | `ruff check . && ruff format .` |
+| Regenerate screenshots | `python scripts/screenshots.py` |
+| Record the README animation | `python scripts/record_demo.py` |
+| Rebuild the README banner and social preview | `python scripts/make_art.py` |
+| Rebuild the app icon | `python scripts/make_icon.py` |
+| Build the app folder | `pyinstaller packaging/apptrackr.spec` |
+| Build the installer | `iscc /DAppVersion=1.1.0 packaging\installer.iss` |
-## Updates
+On headless Linux, Qt needs `libegl1` and `libxkbcommon0`, and tests run with `QT_QPA_PLATFORM=offscreen`
+(set automatically by `tests/conftest.py`).
-Go to **Settings > Updates**, paste in the releases API URL, and click **Check for Updates**. Enable the startup check if you want it to run automatically.
+### Releasing
-For this repo, the URL is:
+Bump `__version__` in `apptrackr/__init__.py`, then push a matching tag:
+```bash
+git tag v1.1.0
+git push origin v1.1.0
```
-https://api.github.com/repos/H4ch1Net/AppTrackr/releases/latest
+
+`.github/workflows/release-windows.yml` checks that the tag matches the version, runs the tests, builds
+the PyInstaller bundle, self-tests it, packages the portable zip and the Inno Setup installer, and attaches
+both to the GitHub release. `ci.yml` runs lint and tests on Windows and Linux for every push and pull request.
+
+### Project structure
+
+```text
+apptrackr/
+ __main__.py entry point: arguments, logging, single instance, service wiring
+ paths.py data, log and asset locations
+ 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
+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)
```
-If AppTrackr finds a newer version it will offer to download and launch the installer for you.
+```mermaid
+flowchart LR
+ P[core.platform Win32 focus, idle, lock] --> T[core.tracker]
+ T -->|30 s checkpoints| DB[(SQLite data.sqlite)]
+ W[core.process_watch launches] --> DB
+ C[core.clicks] --> DB
+ DB --> Q[data.queries]
+ Q --> UI[ui views]
+ DB --> R[rewards.engine] --> G[game.state]
+ R --> UI
+ G --> UI
+ T -->|snapshot| UI
+```
-## Privacy
+
+Troubleshooting
+
+- **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.
+- **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.
+
+
+
+## Contributing
-Window titles are off by default. If you enable title tracking in Settings, titles are hashed (SHA-256, truncated) before storage so the raw text is never saved. Mouse click counts are optional and stored as counts only, with no position or content data.
+Issues and pull requests are welcome. Keep changes focused, run `ruff check .`, `ruff format .` and `pytest`
+before pushing, and add a test when you change tracking, data or reward logic. UI changes should come with
+regenerated screenshots if they change what the README shows.
## License
-[MIT](LICENSE)
+[MIT](LICENSE). Icons from [Lucide](https://lucide.dev) (ISC, see `apptrackr/assets/icons/LICENSE`).
+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/__init__.py b/apptrackr/__init__.py
index b309b16..473b74a 100644
--- a/apptrackr/__init__.py
+++ b/apptrackr/__init__.py
@@ -1,2 +1,7 @@
-"""AppTrackr – Desktop usage time tracker."""
-__version__ = "1.0.0"
+"""AppTrackr: foreground app usage tracker for Windows."""
+
+__version__ = "1.1.0"
+
+APP_NAME = "AppTrackr"
+APP_USER_MODEL_ID = "H4ch1Net.AppTrackr"
+REPO_URL = "https://github.com/H4ch1Net/AppTrackr"
diff --git a/apptrackr/__main__.py b/apptrackr/__main__.py
index 5ad61b2..47bf569 100644
--- a/apptrackr/__main__.py
+++ b/apptrackr/__main__.py
@@ -1,68 +1,199 @@
-"""AppTrackr entry point."""
+"""Entry point: `python -m apptrackr`, the `apptrackr` script or the PyInstaller bundle.
-import sys
-import logging
-import ctypes
+Imports are absolute because PyInstaller runs this file as a top-level script.
+"""
+
+from __future__ import annotations
-from PySide6.QtWidgets import QApplication
+import argparse
+import getpass
+import hashlib
+import logging
+import logging.handlers
+import shutil
+import sys
+import tempfile
+from pathlib import Path
-from apptrackr.data import db
-from apptrackr.core.tracker import Tracker
-from apptrackr.core.process_watch import ProcessWatcher
-from apptrackr.core.events import ClickCounter
-from apptrackr.ui.main import MainWindow, _make_icon
-from apptrackr.ui import theme
+from apptrackr import APP_NAME, APP_USER_MODEL_ID, __version__, paths
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
-)
log = logging.getLogger("apptrackr")
-def main():
- # Ensure Windows taskbar groups this process as AppTrackr instead of python.exe.
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(prog="apptrackr", description="Track foreground app usage on Windows.")
+ parser.add_argument("--minimized", action="store_true", help="start hidden in the system tray")
+ parser.add_argument(
+ "--demo",
+ action="store_true",
+ help="run with generated sample data in a temporary folder (nothing real is recorded)",
+ )
+ parser.add_argument("--data-dir", metavar="PATH", help="store data in PATH instead of the default location")
+ parser.add_argument("--debug", action="store_true", help="verbose logging")
+ parser.add_argument("--self-test", action="store_true", help=argparse.SUPPRESS)
+ parser.add_argument("--version", action="version", version=f"{APP_NAME} {__version__}")
+ return parser.parse_args(argv)
+
+
+def setup_logging(debug: bool) -> None:
+ handlers: list[logging.Handler] = []
+ if sys.stderr is not None: # pythonw / windowed builds have no console
+ handlers.append(logging.StreamHandler())
+ try:
+ paths.log_dir().mkdir(parents=True, exist_ok=True)
+ handlers.append(
+ logging.handlers.RotatingFileHandler(
+ paths.log_dir() / "apptrackr.log", maxBytes=1_000_000, backupCount=3, encoding="utf-8"
+ )
+ )
+ except OSError:
+ pass
+ logging.basicConfig(
+ level=logging.DEBUG if debug else logging.INFO,
+ handlers=handlers,
+ format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
+ )
+
+ def excepthook(exc_type, exc, tb):
+ log.critical("Unhandled exception", exc_info=(exc_type, exc, tb))
+ sys.__excepthook__(exc_type, exc, tb)
+
+ sys.excepthook = excepthook
+
+
+def _instance_key() -> str:
+ """Socket name shared by every launch that uses the same data folder."""
+ folder = hashlib.sha1(str(paths.data_dir().resolve()).encode()).hexdigest()[:10]
+ return f"{APP_NAME}-{getpass.getuser()}-{folder}"
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(sys.argv[1:] if argv is None else argv)
+
+ if args.self_test:
+ return self_test()
+ if args.demo:
+ paths.set_data_dir(Path(tempfile.mkdtemp(prefix="apptrackr-demo-")))
+ elif args.data_dir:
+ paths.set_data_dir(args.data_dir)
+ setup_logging(args.debug)
+
if sys.platform.startswith("win"):
try:
- ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("H4ch1Net.AppTrackr")
+ import ctypes
+
+ ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_USER_MODEL_ID)
except Exception:
pass
- # Init database
- db.init_db()
+ from PySide6.QtCore import QLockFile, Qt
+ from PySide6.QtGui import QGuiApplication
+ from PySide6.QtNetwork import QLocalServer, QLocalSocket
+ from PySide6.QtWidgets import QApplication
+
+ QGuiApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
+ app = QApplication(sys.argv[:1])
+ app.setApplicationName(APP_NAME)
+ app.setApplicationVersion(__version__)
+ app.setOrganizationName("H4ch1Net")
+ app.setQuitOnLastWindowClosed(False)
+
+ # Single instance: a lock file decides who runs; a local socket lets a second
+ # launch ask the running instance to show its window.
+ key = _instance_key()
+ paths.data_dir().mkdir(parents=True, exist_ok=True)
+ lock = QLockFile(str(paths.data_dir() / "apptrackr.lock"))
+ lock.setStaleLockTime(0)
+ if not lock.tryLock(500):
+ probe = QLocalSocket()
+ probe.connectToServer(key)
+ if probe.waitForConnected(1000):
+ probe.write(b"show")
+ probe.flush()
+ probe.waitForBytesWritten(500)
+ log.info("Already running; asked the existing window to show")
+ return 0
+ QLocalServer.removeServer(key)
+ server = QLocalServer()
+ if not server.listen(key):
+ log.warning("Could not listen for other launches: %s", server.errorString())
+
+ from apptrackr.core.clicks import ClickCounter
+ from apptrackr.core.platform import create_platform
+ from apptrackr.core.process_watch import ProcessWatcher
+ from apptrackr.core.tracker import Tracker
+ from apptrackr.data import db
+ from apptrackr.ui.main import MainWindow, prepare_app
- # Start background services
- tracker = Tracker()
- tracker.start()
-
- watcher = ProcessWatcher()
- watcher.start()
-
- clicker = ClickCounter()
- clicker.start()
-
- # UI
- app = QApplication(sys.argv)
- app.setApplicationName("AppTrackr")
- app.setWindowIcon(_make_icon())
-
- # Load saved theme before applying stylesheet
- saved_theme = db.get_setting("ui_theme", "Cyan")
- theme.set_theme(saved_theme)
- app.setStyleSheet(theme.get_stylesheet())
+ db.init_db()
+ if args.demo:
+ from apptrackr.data import demo
- window = MainWindow(tracker)
- window.show()
+ demo.seed()
+ log.info("Demo mode: sample data in %s", paths.data_dir())
- exit_code = app.exec()
+ prepare_app(app)
- # Cleanup
- tracker.stop()
- watcher.stop()
- clicker.stop()
+ tracker = Tracker(create_platform(demo=args.demo))
+ tracker.start()
+ watcher = ProcessWatcher()
+ if tracker.supported and not args.demo:
+ watcher.start()
+ clicks = ClickCounter(tracker)
+ clicks.set_enabled(db.get_bool("track_clicks") and not args.demo)
+
+ window = MainWindow(tracker, clicks, demo=args.demo)
+ server.newConnection.connect(lambda: (server.nextPendingConnection(), window.bring_to_front()))
+ QGuiApplication.styleHints().colorSchemeChanged.connect(
+ lambda *_: db.get_setting("ui_mode", "dark") == "system" and window.apply_theme()
+ )
+
+ if not args.minimized or not window.has_tray():
+ window.show()
+
+ def shutdown():
+ log.info("Shutting down")
+ clicks.stop()
+ watcher.stop()
+ tracker.stop()
+ server.close()
+ lock.unlock()
+ if args.demo:
+ db.close()
+ shutil.rmtree(paths.data_dir(), ignore_errors=True)
+
+ app.aboutToQuit.connect(shutdown)
+ log.info("%s %s started (data: %s)", APP_NAME, __version__, paths.data_dir())
+ return app.exec()
+
+
+def self_test() -> int:
+ """Build the whole UI offscreen against a throwaway database. Used to verify packaged builds."""
+ import os
+
+ os.environ["QT_QPA_PLATFORM"] = "offscreen"
+ paths.set_data_dir(Path(tempfile.mkdtemp(prefix="apptrackr-selftest-")))
+ from PySide6.QtWidgets import QApplication
+
+ from apptrackr.core.platform import NullPlatform
+ from apptrackr.core.tracker import Tracker
+ from apptrackr.data import db, demo
+ from apptrackr.ui import fonts
+ from apptrackr.ui.main import MainWindow, prepare_app
- sys.exit(exit_code)
+ db.init_db()
+ demo.seed(days=7)
+ app = QApplication(sys.argv[:1])
+ prepare_app(app)
+ if fonts.load() != (fonts.SANS, fonts.MONO):
+ print("self-test: bundled fonts did not load", file=sys.stderr)
+ return 1
+ window = MainWindow(Tracker(NullPlatform()))
+ for page in ("dashboard", "calendar", "apps", "rewards", "village", "settings"):
+ window.show_page(page)
+ app.processEvents()
+ return 0
if __name__ == "__main__":
- main()
+ sys.exit(main())
diff --git a/apptrackr/assets/fonts/InstrumentSans-Bold.ttf b/apptrackr/assets/fonts/InstrumentSans-Bold.ttf
new file mode 100644
index 0000000..cba24b7
Binary files /dev/null and b/apptrackr/assets/fonts/InstrumentSans-Bold.ttf differ
diff --git a/apptrackr/assets/fonts/InstrumentSans-Medium.ttf b/apptrackr/assets/fonts/InstrumentSans-Medium.ttf
new file mode 100644
index 0000000..8f420ec
Binary files /dev/null and b/apptrackr/assets/fonts/InstrumentSans-Medium.ttf differ
diff --git a/apptrackr/assets/fonts/InstrumentSans-Regular.ttf b/apptrackr/assets/fonts/InstrumentSans-Regular.ttf
new file mode 100644
index 0000000..8da887c
Binary files /dev/null and b/apptrackr/assets/fonts/InstrumentSans-Regular.ttf differ
diff --git a/apptrackr/assets/fonts/InstrumentSans-SemiBold.ttf b/apptrackr/assets/fonts/InstrumentSans-SemiBold.ttf
new file mode 100644
index 0000000..14c4a4b
Binary files /dev/null and b/apptrackr/assets/fonts/InstrumentSans-SemiBold.ttf differ
diff --git a/apptrackr/assets/fonts/MartianMono-Medium.ttf b/apptrackr/assets/fonts/MartianMono-Medium.ttf
new file mode 100644
index 0000000..107a8bb
Binary files /dev/null and b/apptrackr/assets/fonts/MartianMono-Medium.ttf differ
diff --git a/apptrackr/assets/fonts/MartianMono-Regular.ttf b/apptrackr/assets/fonts/MartianMono-Regular.ttf
new file mode 100644
index 0000000..b43d1f1
Binary files /dev/null and b/apptrackr/assets/fonts/MartianMono-Regular.ttf differ
diff --git a/apptrackr/assets/fonts/OFL-InstrumentSans.txt b/apptrackr/assets/fonts/OFL-InstrumentSans.txt
new file mode 100644
index 0000000..9a39a8e
--- /dev/null
+++ b/apptrackr/assets/fonts/OFL-InstrumentSans.txt
@@ -0,0 +1,93 @@
+Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans) InstrumentSans-Italic[wdth,wght].ttf: Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apptrackr/assets/fonts/OFL-MartianMono.txt b/apptrackr/assets/fonts/OFL-MartianMono.txt
new file mode 100644
index 0000000..efbd896
--- /dev/null
+++ b/apptrackr/assets/fonts/OFL-MartianMono.txt
@@ -0,0 +1,93 @@
+Copyright 2020 The Martian Mono Project Authors (https://github.com/evilmartians/mono)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apptrackr/assets/icons/LICENSE b/apptrackr/assets/icons/LICENSE
new file mode 100644
index 0000000..718bb3f
--- /dev/null
+++ b/apptrackr/assets/icons/LICENSE
@@ -0,0 +1,43 @@
+ISC License
+
+Copyright (c) 2026 Lucide Icons and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---
+
+The following Lucide icons are derived from the Feather project:
+
+airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
+
+The MIT License (MIT) (for the icons listed above)
+
+Copyright (c) 2013-present Cole Bemis
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/apptrackr/assets/icons/activity.svg b/apptrackr/assets/icons/activity.svg
new file mode 100644
index 0000000..fb5e45e
--- /dev/null
+++ b/apptrackr/assets/icons/activity.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/archive-restore.svg b/apptrackr/assets/icons/archive-restore.svg
new file mode 100644
index 0000000..ad2972f
--- /dev/null
+++ b/apptrackr/assets/icons/archive-restore.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/arrow-left.svg b/apptrackr/assets/icons/arrow-left.svg
new file mode 100644
index 0000000..29199ac
--- /dev/null
+++ b/apptrackr/assets/icons/arrow-left.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/beer.svg b/apptrackr/assets/icons/beer.svg
new file mode 100644
index 0000000..7969e0b
--- /dev/null
+++ b/apptrackr/assets/icons/beer.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/bell.svg b/apptrackr/assets/icons/bell.svg
new file mode 100644
index 0000000..68f995e
--- /dev/null
+++ b/apptrackr/assets/icons/bell.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/calendar-days.svg b/apptrackr/assets/icons/calendar-days.svg
new file mode 100644
index 0000000..674dfed
--- /dev/null
+++ b/apptrackr/assets/icons/calendar-days.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/castle.svg b/apptrackr/assets/icons/castle.svg
new file mode 100644
index 0000000..542ab76
--- /dev/null
+++ b/apptrackr/assets/icons/castle.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/check.svg b/apptrackr/assets/icons/check.svg
new file mode 100644
index 0000000..5b752b4
--- /dev/null
+++ b/apptrackr/assets/icons/check.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/chevron-down.svg b/apptrackr/assets/icons/chevron-down.svg
new file mode 100644
index 0000000..18a4697
--- /dev/null
+++ b/apptrackr/assets/icons/chevron-down.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/chevron-left.svg b/apptrackr/assets/icons/chevron-left.svg
new file mode 100644
index 0000000..97ed83e
--- /dev/null
+++ b/apptrackr/assets/icons/chevron-left.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/chevron-right.svg b/apptrackr/assets/icons/chevron-right.svg
new file mode 100644
index 0000000..aa9eaee
--- /dev/null
+++ b/apptrackr/assets/icons/chevron-right.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/circle-check.svg b/apptrackr/assets/icons/circle-check.svg
new file mode 100644
index 0000000..be023ab
--- /dev/null
+++ b/apptrackr/assets/icons/circle-check.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/clock.svg b/apptrackr/assets/icons/clock.svg
new file mode 100644
index 0000000..a7cef67
--- /dev/null
+++ b/apptrackr/assets/icons/clock.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/cog.svg b/apptrackr/assets/icons/cog.svg
new file mode 100644
index 0000000..b0ce5f8
--- /dev/null
+++ b/apptrackr/assets/icons/cog.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/coins.svg b/apptrackr/assets/icons/coins.svg
new file mode 100644
index 0000000..f9180eb
--- /dev/null
+++ b/apptrackr/assets/icons/coins.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/crown.svg b/apptrackr/assets/icons/crown.svg
new file mode 100644
index 0000000..dc4a407
--- /dev/null
+++ b/apptrackr/assets/icons/crown.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/database.svg b/apptrackr/assets/icons/database.svg
new file mode 100644
index 0000000..6da4ad6
--- /dev/null
+++ b/apptrackr/assets/icons/database.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/download.svg b/apptrackr/assets/icons/download.svg
new file mode 100644
index 0000000..78b8605
--- /dev/null
+++ b/apptrackr/assets/icons/download.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/ellipsis.svg b/apptrackr/assets/icons/ellipsis.svg
new file mode 100644
index 0000000..a6ede1d
--- /dev/null
+++ b/apptrackr/assets/icons/ellipsis.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/external-link.svg b/apptrackr/assets/icons/external-link.svg
new file mode 100644
index 0000000..06236e8
--- /dev/null
+++ b/apptrackr/assets/icons/external-link.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/eye-off.svg b/apptrackr/assets/icons/eye-off.svg
new file mode 100644
index 0000000..4da5946
--- /dev/null
+++ b/apptrackr/assets/icons/eye-off.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/eye.svg b/apptrackr/assets/icons/eye.svg
new file mode 100644
index 0000000..370dc40
--- /dev/null
+++ b/apptrackr/assets/icons/eye.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/flame.svg b/apptrackr/assets/icons/flame.svg
new file mode 100644
index 0000000..1aba926
--- /dev/null
+++ b/apptrackr/assets/icons/flame.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/flask-conical.svg b/apptrackr/assets/icons/flask-conical.svg
new file mode 100644
index 0000000..50f6130
--- /dev/null
+++ b/apptrackr/assets/icons/flask-conical.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/folder-open.svg b/apptrackr/assets/icons/folder-open.svg
new file mode 100644
index 0000000..da1e44d
--- /dev/null
+++ b/apptrackr/assets/icons/folder-open.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/gift.svg b/apptrackr/assets/icons/gift.svg
new file mode 100644
index 0000000..adf47f9
--- /dev/null
+++ b/apptrackr/assets/icons/gift.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/hammer.svg b/apptrackr/assets/icons/hammer.svg
new file mode 100644
index 0000000..174bbe9
--- /dev/null
+++ b/apptrackr/assets/icons/hammer.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/hourglass.svg b/apptrackr/assets/icons/hourglass.svg
new file mode 100644
index 0000000..f510810
--- /dev/null
+++ b/apptrackr/assets/icons/hourglass.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/house.svg b/apptrackr/assets/icons/house.svg
new file mode 100644
index 0000000..01f7e76
--- /dev/null
+++ b/apptrackr/assets/icons/house.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/info.svg b/apptrackr/assets/icons/info.svg
new file mode 100644
index 0000000..29c3a60
--- /dev/null
+++ b/apptrackr/assets/icons/info.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/keyboard.svg b/apptrackr/assets/icons/keyboard.svg
new file mode 100644
index 0000000..e5a4a72
--- /dev/null
+++ b/apptrackr/assets/icons/keyboard.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/landmark.svg b/apptrackr/assets/icons/landmark.svg
new file mode 100644
index 0000000..aa9cf93
--- /dev/null
+++ b/apptrackr/assets/icons/landmark.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/layout-dashboard.svg b/apptrackr/assets/icons/layout-dashboard.svg
new file mode 100644
index 0000000..aab10b4
--- /dev/null
+++ b/apptrackr/assets/icons/layout-dashboard.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/layout-grid.svg b/apptrackr/assets/icons/layout-grid.svg
new file mode 100644
index 0000000..6ebe34a
--- /dev/null
+++ b/apptrackr/assets/icons/layout-grid.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/monitor.svg b/apptrackr/assets/icons/monitor.svg
new file mode 100644
index 0000000..2f92d0e
--- /dev/null
+++ b/apptrackr/assets/icons/monitor.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/moon.svg b/apptrackr/assets/icons/moon.svg
new file mode 100644
index 0000000..dfa06a9
--- /dev/null
+++ b/apptrackr/assets/icons/moon.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/mountain.svg b/apptrackr/assets/icons/mountain.svg
new file mode 100644
index 0000000..666f5b1
--- /dev/null
+++ b/apptrackr/assets/icons/mountain.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/mouse-pointer-click.svg b/apptrackr/assets/icons/mouse-pointer-click.svg
new file mode 100644
index 0000000..9feab14
--- /dev/null
+++ b/apptrackr/assets/icons/mouse-pointer-click.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/pause.svg b/apptrackr/assets/icons/pause.svg
new file mode 100644
index 0000000..0d75532
--- /dev/null
+++ b/apptrackr/assets/icons/pause.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/pencil.svg b/apptrackr/assets/icons/pencil.svg
new file mode 100644
index 0000000..33b3003
--- /dev/null
+++ b/apptrackr/assets/icons/pencil.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/play.svg b/apptrackr/assets/icons/play.svg
new file mode 100644
index 0000000..674afef
--- /dev/null
+++ b/apptrackr/assets/icons/play.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/plus.svg b/apptrackr/assets/icons/plus.svg
new file mode 100644
index 0000000..474755f
--- /dev/null
+++ b/apptrackr/assets/icons/plus.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/power.svg b/apptrackr/assets/icons/power.svg
new file mode 100644
index 0000000..ae70305
--- /dev/null
+++ b/apptrackr/assets/icons/power.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/refresh-cw.svg b/apptrackr/assets/icons/refresh-cw.svg
new file mode 100644
index 0000000..d5aa379
--- /dev/null
+++ b/apptrackr/assets/icons/refresh-cw.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/rocket.svg b/apptrackr/assets/icons/rocket.svg
new file mode 100644
index 0000000..21f8461
--- /dev/null
+++ b/apptrackr/assets/icons/rocket.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/scroll.svg b/apptrackr/assets/icons/scroll.svg
new file mode 100644
index 0000000..9d80a8e
--- /dev/null
+++ b/apptrackr/assets/icons/scroll.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/search.svg b/apptrackr/assets/icons/search.svg
new file mode 100644
index 0000000..bfb0217
--- /dev/null
+++ b/apptrackr/assets/icons/search.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/settings.svg b/apptrackr/assets/icons/settings.svg
new file mode 100644
index 0000000..4b8e6d4
--- /dev/null
+++ b/apptrackr/assets/icons/settings.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/sparkles.svg b/apptrackr/assets/icons/sparkles.svg
new file mode 100644
index 0000000..4e1ed42
--- /dev/null
+++ b/apptrackr/assets/icons/sparkles.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/star.svg b/apptrackr/assets/icons/star.svg
new file mode 100644
index 0000000..680cfed
--- /dev/null
+++ b/apptrackr/assets/icons/star.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/sun.svg b/apptrackr/assets/icons/sun.svg
new file mode 100644
index 0000000..6dc18be
--- /dev/null
+++ b/apptrackr/assets/icons/sun.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/timer.svg b/apptrackr/assets/icons/timer.svg
new file mode 100644
index 0000000..16f0073
--- /dev/null
+++ b/apptrackr/assets/icons/timer.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/trash-2.svg b/apptrackr/assets/icons/trash-2.svg
new file mode 100644
index 0000000..ad658cb
--- /dev/null
+++ b/apptrackr/assets/icons/trash-2.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/tree-pine.svg b/apptrackr/assets/icons/tree-pine.svg
new file mode 100644
index 0000000..1ce8ff6
--- /dev/null
+++ b/apptrackr/assets/icons/tree-pine.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/triangle-alert.svg b/apptrackr/assets/icons/triangle-alert.svg
new file mode 100644
index 0000000..0865391
--- /dev/null
+++ b/apptrackr/assets/icons/triangle-alert.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/trophy.svg b/apptrackr/assets/icons/trophy.svg
new file mode 100644
index 0000000..f2a4916
--- /dev/null
+++ b/apptrackr/assets/icons/trophy.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/upload.svg b/apptrackr/assets/icons/upload.svg
new file mode 100644
index 0000000..8bf7ba2
--- /dev/null
+++ b/apptrackr/assets/icons/upload.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/warehouse.svg b/apptrackr/assets/icons/warehouse.svg
new file mode 100644
index 0000000..673d31d
--- /dev/null
+++ b/apptrackr/assets/icons/warehouse.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/wheat.svg b/apptrackr/assets/icons/wheat.svg
new file mode 100644
index 0000000..92f8011
--- /dev/null
+++ b/apptrackr/assets/icons/wheat.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/x.svg b/apptrackr/assets/icons/x.svg
new file mode 100644
index 0000000..8ae10ed
--- /dev/null
+++ b/apptrackr/assets/icons/x.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/icons/zap.svg b/apptrackr/assets/icons/zap.svg
new file mode 100644
index 0000000..e551a9b
--- /dev/null
+++ b/apptrackr/assets/icons/zap.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apptrackr/assets/illustrations/blueprint.svg b/apptrackr/assets/illustrations/blueprint.svg
new file mode 100644
index 0000000..58795dd
--- /dev/null
+++ b/apptrackr/assets/illustrations/blueprint.svg
@@ -0,0 +1,7 @@
+
diff --git a/apptrackr/assets/illustrations/calendar.svg b/apptrackr/assets/illustrations/calendar.svg
new file mode 100644
index 0000000..1071b5c
--- /dev/null
+++ b/apptrackr/assets/illustrations/calendar.svg
@@ -0,0 +1,7 @@
+
diff --git a/apptrackr/assets/illustrations/clicks.svg b/apptrackr/assets/illustrations/clicks.svg
new file mode 100644
index 0000000..6d6b4ea
--- /dev/null
+++ b/apptrackr/assets/illustrations/clicks.svg
@@ -0,0 +1,9 @@
+
diff --git a/apptrackr/assets/illustrations/gift.svg b/apptrackr/assets/illustrations/gift.svg
new file mode 100644
index 0000000..7aa6a2c
--- /dev/null
+++ b/apptrackr/assets/illustrations/gift.svg
@@ -0,0 +1,11 @@
+
diff --git a/apptrackr/assets/illustrations/search.svg b/apptrackr/assets/illustrations/search.svg
new file mode 100644
index 0000000..a4fc055
--- /dev/null
+++ b/apptrackr/assets/illustrations/search.svg
@@ -0,0 +1,10 @@
+
diff --git a/apptrackr/assets/illustrations/star.svg b/apptrackr/assets/illustrations/star.svg
new file mode 100644
index 0000000..9510463
--- /dev/null
+++ b/apptrackr/assets/illustrations/star.svg
@@ -0,0 +1,7 @@
+
diff --git a/apptrackr/assets/illustrations/unplugged.svg b/apptrackr/assets/illustrations/unplugged.svg
new file mode 100644
index 0000000..109106b
--- /dev/null
+++ b/apptrackr/assets/illustrations/unplugged.svg
@@ -0,0 +1,11 @@
+
diff --git a/apptrackr/assets/illustrations/waiting.svg b/apptrackr/assets/illustrations/waiting.svg
new file mode 100644
index 0000000..600ac41
--- /dev/null
+++ b/apptrackr/assets/illustrations/waiting.svg
@@ -0,0 +1,11 @@
+
diff --git a/apptrackr/assets/logo-small.svg b/apptrackr/assets/logo-small.svg
new file mode 100644
index 0000000..de30da8
--- /dev/null
+++ b/apptrackr/assets/logo-small.svg
@@ -0,0 +1,9 @@
+
diff --git a/apptrackr/assets/logo.svg b/apptrackr/assets/logo.svg
new file mode 100644
index 0000000..36cf726
--- /dev/null
+++ b/apptrackr/assets/logo.svg
@@ -0,0 +1,9 @@
+
diff --git a/apptrackr/core/autostart.py b/apptrackr/core/autostart.py
new file mode 100644
index 0000000..a92fb49
--- /dev/null
+++ b/apptrackr/core/autostart.py
@@ -0,0 +1,62 @@
+"""Launch-at-login integration (HKCU Run key on Windows)."""
+
+from __future__ import annotations
+
+import logging
+import sys
+
+log = logging.getLogger(__name__)
+
+_RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
+_VALUE = "AppTrackr"
+
+
+def supported() -> bool:
+ return sys.platform.startswith("win")
+
+
+def command() -> str:
+ """Command line stored in the Run key. Starts hidden in the tray."""
+ if getattr(sys, "frozen", False):
+ return f'"{sys.executable}" --minimized'
+ exe = sys.executable
+ if exe.lower().endswith("python.exe"):
+ exe = exe[:-10] + "pythonw.exe" # no console window at login
+ return f'"{exe}" -m apptrackr --minimized'
+
+
+def is_enabled() -> bool:
+ if not supported():
+ return False
+ import winreg
+
+ try:
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _RUN_KEY) as key:
+ winreg.QueryValueEx(key, _VALUE)
+ return True
+ except FileNotFoundError:
+ return False
+ except OSError:
+ log.exception("Could not read autostart entry")
+ return False
+
+
+def set_enabled(enable: bool) -> bool:
+ """Create or remove the Run entry. Returns True on success."""
+ if not supported():
+ return False
+ import winreg
+
+ try:
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _RUN_KEY, 0, winreg.KEY_SET_VALUE) as key:
+ if enable:
+ winreg.SetValueEx(key, _VALUE, 0, winreg.REG_SZ, command())
+ else:
+ try:
+ winreg.DeleteValue(key, _VALUE)
+ except FileNotFoundError:
+ pass
+ return True
+ except OSError:
+ log.exception("Could not update autostart entry")
+ return False
diff --git a/apptrackr/core/clicks.py b/apptrackr/core/clicks.py
new file mode 100644
index 0000000..b399337
--- /dev/null
+++ b/apptrackr/core/clicks.py
@@ -0,0 +1,82 @@
+"""Opt-in mouse click counter. Stores counts per app per day, nothing else."""
+
+from __future__ import annotations
+
+import logging
+import threading
+from collections import Counter
+from datetime import date
+
+from ..data import db, queries
+
+log = logging.getLogger(__name__)
+
+
+class ClickCounter:
+ """Counts global mouse clicks and attributes them to the tracked app."""
+
+ FLUSH_SEC = 20.0
+
+ def __init__(self, tracker) -> None:
+ self._tracker = tracker
+ self._listener = None
+ self._counts: Counter[tuple[str, int]] = Counter()
+ self._lock = threading.Lock()
+ self._stop = threading.Event()
+ self._flusher: threading.Thread | None = None
+
+ @property
+ def running(self) -> bool:
+ return self._listener is not None
+
+ def set_enabled(self, enabled: bool) -> None:
+ if enabled and not self.running:
+ self._start()
+ elif not enabled and self.running:
+ self.stop()
+
+ def _start(self) -> None:
+ if not self._tracker.supported:
+ return
+ try:
+ from pynput import mouse
+ except Exception:
+ log.warning("pynput unavailable; click counting disabled")
+ return
+ self._listener = mouse.Listener(on_click=self._on_click)
+ self._listener.daemon = True
+ self._listener.start()
+ self._stop.clear()
+ self._flusher = threading.Thread(target=self._flush_loop, daemon=True, name="click-flush")
+ self._flusher.start()
+ log.info("Click counter started")
+
+ def stop(self) -> None:
+ if self._listener is not None:
+ self._listener.stop()
+ self._listener = None
+ self._stop.set()
+ self.flush()
+
+ def _on_click(self, _x, _y, _button, pressed) -> None:
+ if not pressed:
+ return
+ # Runs inside the low-level mouse hook: never block here.
+ app_id = self._tracker.current_app_id
+ if app_id is not None:
+ with self._lock:
+ self._counts[(date.today().isoformat(), app_id)] += 1
+
+ def _flush_loop(self) -> None:
+ while not self._stop.wait(self.FLUSH_SEC):
+ self.flush()
+ db.close()
+
+ def flush(self) -> None:
+ with self._lock:
+ pending, self._counts = self._counts, Counter()
+ try:
+ for (day, app_id), count in pending.items():
+ queries.increment_clicks(day, app_id, count)
+ except Exception:
+ log.exception("Failed to store click counts")
diff --git a/apptrackr/core/events.py b/apptrackr/core/events.py
deleted file mode 100644
index 8e194ff..0000000
--- a/apptrackr/core/events.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""Global mouse click counter (opt-in). Uses pynput."""
-
-from __future__ import annotations
-
-import logging
-import ctypes
-import ctypes.wintypes
-import threading
-import time
-from datetime import date
-
-import psutil
-
-from ..data import db, queries
-
-log = logging.getLogger(__name__)
-
-
-class ClickCounter:
- """Counts global mouse clicks attributed to the foreground app. Opt-in only."""
-
- def __init__(self) -> None:
- self._running = False
- self._thread: threading.Thread | None = None
- self._listener = None
-
- def start(self) -> None:
- if db.get_setting("track_clicks", "0") != "1":
- log.info("Click tracking disabled")
- return
- try:
- from pynput import mouse
- self._running = True
- self._listener = mouse.Listener(on_click=self._on_click)
- self._listener.start()
- log.info("Click counter started")
- except ImportError:
- log.warning("pynput not installed – click tracking unavailable")
-
- def stop(self) -> None:
- self._running = False
- if self._listener:
- self._listener.stop()
-
- def _on_click(self, x, y, button, pressed) -> None:
- if not pressed or not self._running:
- return
- try:
- hwnd = ctypes.windll.user32.GetForegroundWindow() # type: ignore[attr-defined]
- pid = ctypes.wintypes.DWORD()
- ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) # type: ignore[attr-defined]
- proc = psutil.Process(pid.value)
- exe = proc.name().lower()
- app_id = queries.get_or_create_app(exe)
- queries.increment_clicks(date.today().isoformat(), app_id)
- except Exception:
- pass
diff --git a/apptrackr/core/idle.py b/apptrackr/core/idle.py
deleted file mode 100644
index 27926d2..0000000
--- a/apptrackr/core/idle.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""Idle detection utilities (Windows)."""
-
-from __future__ import annotations
-
-import ctypes
-
-
-class LASTINPUTINFO(ctypes.Structure):
- _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
-
-
-def get_idle_seconds() -> float:
- """Return seconds since last user input."""
- lii = LASTINPUTINFO()
- lii.cbSize = ctypes.sizeof(LASTINPUTINFO)
- if ctypes.windll.user32.GetLastInputInfo(ctypes.byref(lii)): # type: ignore[attr-defined]
- millis = ctypes.windll.kernel32.GetTickCount() - lii.dwTime # type: ignore[attr-defined]
- return millis / 1000.0
- return 0.0
diff --git a/apptrackr/core/limits.py b/apptrackr/core/limits.py
new file mode 100644
index 0000000..a7ad85a
--- /dev/null
+++ b/apptrackr/core/limits.py
@@ -0,0 +1,30 @@
+"""Daily per-app time limits."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from ..data import queries
+
+
+@dataclass
+class LimitMonitor:
+ """Reports each app at most once per day when it passes its daily limit."""
+
+ _notified: set[tuple[str, int]] = field(default_factory=set)
+
+ def check(self, live_app_id: int | None = None, live_ms: int = 0) -> list[dict]:
+ day = queries.today_str()
+ self._notified = {key for key in self._notified if key[0] == day}
+ reached = []
+ for app in queries.apps_with_limits():
+ key = (day, app["app_id"])
+ if key in self._notified:
+ continue
+ used = queries.app_usage_on(day, app["app_id"])
+ if app["app_id"] == live_app_id:
+ used += live_ms
+ if used >= app["daily_limit_ms"]:
+ self._notified.add(key)
+ reached.append(app | {"used_ms": used})
+ return reached
diff --git a/apptrackr/core/platform.py b/apptrackr/core/platform.py
new file mode 100644
index 0000000..8c97049
--- /dev/null
+++ b/apptrackr/core/platform.py
@@ -0,0 +1,198 @@
+"""OS integration: which app has focus, how long the user has been idle, lock state.
+
+Tracking is implemented for Windows. Other platforms get a NullPlatform so the
+UI can still run (useful for development, demos and screenshots).
+"""
+
+from __future__ import annotations
+
+import ctypes
+import logging
+import sys
+import time
+from dataclasses import dataclass
+from typing import Protocol
+
+import psutil
+
+log = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class ForegroundApp:
+ pid: int
+ exe_name: str
+ exe_path: str | None
+
+
+class Platform(Protocol):
+ supported: bool
+
+ def foreground_app(self) -> ForegroundApp | None: ...
+
+ def idle_seconds(self) -> float: ...
+
+ def is_locked(self) -> bool: ...
+
+
+class NullPlatform:
+ """No-op platform: nothing is ever in focus."""
+
+ supported = False
+
+ def foreground_app(self) -> ForegroundApp | None:
+ return None
+
+ def idle_seconds(self) -> float:
+ return 0.0
+
+ def is_locked(self) -> bool:
+ return False
+
+
+class DemoPlatform:
+ """Pretends a fixed rotation of apps has focus. Used by --demo."""
+
+ supported = True
+ ROTATION = (
+ ("code.exe", 1500),
+ ("chrome.exe", 600),
+ ("windowsterminal.exe", 420),
+ ("slack.exe", 300),
+ ("figma.exe", 480),
+ )
+
+ def __init__(self, start: float | None = None) -> None:
+ self._start = time.time() if start is None else start
+
+ def foreground_app(self) -> ForegroundApp | None:
+ cycle = sum(sec for _, sec in self.ROTATION)
+ pos = (time.time() - self._start) % cycle
+ for exe, sec in self.ROTATION:
+ if pos < sec:
+ return ForegroundApp(0, exe, None)
+ pos -= sec
+ return None
+
+ def idle_seconds(self) -> float:
+ return 0.0
+
+ def is_locked(self) -> bool:
+ return False
+
+
+class _LASTINPUTINFO(ctypes.Structure):
+ _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
+
+
+class WindowsPlatform:
+ """Win32 implementation using user32/kernel32 through ctypes."""
+
+ supported = True
+ _DESKTOP_READOBJECTS = 0x0001
+ _UWP_HOST = "applicationframehost.exe"
+
+ def __init__(self) -> None:
+ from ctypes import wintypes
+
+ self._wt = wintypes
+ u = self._user32 = ctypes.WinDLL("user32", use_last_error=True) # type: ignore[attr-defined]
+ k = self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined]
+
+ u.GetForegroundWindow.argtypes = []
+ u.GetForegroundWindow.restype = wintypes.HWND
+ u.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
+ u.GetWindowThreadProcessId.restype = wintypes.DWORD
+ u.GetLastInputInfo.argtypes = [ctypes.POINTER(_LASTINPUTINFO)]
+ u.GetLastInputInfo.restype = wintypes.BOOL
+ u.OpenInputDesktop.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ u.OpenInputDesktop.restype = wintypes.HANDLE
+ u.CloseDesktop.argtypes = [wintypes.HANDLE]
+ u.CloseDesktop.restype = wintypes.BOOL
+ self._enum_proc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) # type: ignore[attr-defined]
+ u.EnumChildWindows.argtypes = [wintypes.HWND, self._enum_proc, wintypes.LPARAM]
+ u.EnumChildWindows.restype = wintypes.BOOL
+ k.GetTickCount.argtypes = []
+ k.GetTickCount.restype = wintypes.DWORD
+
+ self._last_key: tuple[int, int] | None = None
+ self._last_app: ForegroundApp | None = None
+
+ def _pid_of(self, hwnd) -> int:
+ pid = self._wt.DWORD()
+ self._user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
+ return int(pid.value)
+
+ def _uwp_child_pid(self, hwnd, host_pid: int) -> int:
+ """UWP apps are hosted by ApplicationFrameHost; find the real app process."""
+ found: list[int] = []
+
+ def callback(child, _lparam):
+ pid = self._pid_of(child)
+ if pid and pid != host_pid:
+ found.append(pid)
+ return False
+ return True
+
+ self._user32.EnumChildWindows(hwnd, self._enum_proc(callback), 0)
+ return found[0] if found else host_pid
+
+ def foreground_app(self) -> ForegroundApp | None:
+ hwnd = self._user32.GetForegroundWindow()
+ if not hwnd:
+ return None
+ pid = self._pid_of(hwnd)
+ if not pid:
+ return None
+ key = (int(hwnd), pid)
+ if key == self._last_key and self._last_app is not None:
+ return self._last_app
+ try:
+ proc = psutil.Process(pid)
+ name = proc.name()
+ if name.lower() == self._UWP_HOST:
+ child = self._uwp_child_pid(hwnd, pid)
+ if child != pid:
+ proc = psutil.Process(child)
+ name = proc.name()
+ try:
+ path = proc.exe()
+ except (psutil.AccessDenied, psutil.ZombieProcess, OSError):
+ path = None # elevated or protected process: still track by name
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ return None
+ app = ForegroundApp(proc.pid, name, path)
+ # A UWP frame can be sampled before its app window attaches; retry next time.
+ if name.lower() != self._UWP_HOST:
+ self._last_key, self._last_app = key, app
+ return app
+
+ def idle_seconds(self) -> float:
+ info = _LASTINPUTINFO()
+ info.cbSize = ctypes.sizeof(_LASTINPUTINFO)
+ if not self._user32.GetLastInputInfo(ctypes.byref(info)):
+ return 0.0
+ # Both values are 32-bit tick counts; mask to survive the 49.7 day wrap.
+ millis = (int(self._kernel32.GetTickCount()) - int(info.dwTime)) & 0xFFFFFFFF
+ return millis / 1000.0
+
+ def is_locked(self) -> bool:
+ # OpenInputDesktop fails while the lock screen or a secure desktop is active.
+ hdesk = self._user32.OpenInputDesktop(0, False, self._DESKTOP_READOBJECTS)
+ if not hdesk:
+ return True
+ self._user32.CloseDesktop(hdesk)
+ return False
+
+
+def create_platform(demo: bool = False) -> Platform:
+ if demo:
+ return DemoPlatform()
+ if sys.platform.startswith("win"):
+ try:
+ return WindowsPlatform()
+ except Exception:
+ log.exception("Win32 integration unavailable; tracking disabled")
+ else:
+ log.warning("Foreground tracking is only implemented for Windows (running on %s)", sys.platform)
+ return NullPlatform()
diff --git a/apptrackr/core/process_watch.py b/apptrackr/core/process_watch.py
index 12a6aae..21e14f3 100644
--- a/apptrackr/core/process_watch.py
+++ b/apptrackr/core/process_watch.py
@@ -1,4 +1,8 @@
-"""Process watch – detect new process launches by diffing the PID set."""
+"""Launch counter: counts how often each tracked app is started.
+
+A launch is an executable going from "not running" to "running". Multi-process
+apps such as browsers therefore count once, not once per child process.
+"""
from __future__ import annotations
@@ -9,48 +13,66 @@
import psutil
-from ..data import queries
+from ..data import catalog, db, queries
log = logging.getLogger(__name__)
+# How long a launch of a not-yet-known app is remembered while waiting for the
+# tracker to see it in focus for the first time.
+_PENDING_TTL = 600.0
-class ProcessWatcher:
- """Periodically diffs running processes to detect new app launches."""
+class ProcessWatcher:
def __init__(self, interval: float = 5.0) -> None:
self._interval = interval
- self._running = False
+ self._stop = threading.Event()
self._thread: threading.Thread | None = None
- self._known_pids: set[int] = set()
+ self._running: set[str] | None = None
+ self._pending: dict[str, float] = {}
def start(self) -> None:
- self._known_pids = {p.pid for p in psutil.process_iter(["pid"])}
- self._running = True
- self._thread = threading.Thread(target=self._loop, daemon=True, name="proc-watch")
+ self._stop.clear()
+ self._thread = threading.Thread(target=self._loop, daemon=True, name="launch-watch")
self._thread.start()
def stop(self) -> None:
- self._running = False
+ self._stop.set()
def _loop(self) -> None:
- while self._running:
+ while not self._stop.is_set():
try:
- self._check()
+ self.check(self._running_names())
except Exception:
- log.exception("ProcessWatcher error")
- time.sleep(self._interval)
-
- def _check(self) -> None:
- current = set()
- for proc in psutil.process_iter(["pid", "name", "exe"]):
- current.add(proc.pid)
- if proc.pid not in self._known_pids:
- try:
- exe = proc.info["name"] # type: ignore[index]
- exe_path = proc.info.get("exe") # type: ignore[union-attr]
- if exe:
- app_id = queries.get_or_create_app(exe.lower(), icon_path=exe_path)
- queries.increment_opens(date.today().isoformat(), app_id)
- except Exception:
- pass
- self._known_pids = current
+ log.exception("Launch watcher failed")
+ self._stop.wait(self._interval)
+ db.close()
+
+ @staticmethod
+ def _running_names() -> set[str]:
+ names = set()
+ for proc in psutil.process_iter(["name"]):
+ name = proc.info.get("name") # type: ignore[union-attr]
+ if name:
+ names.add(catalog.canonical_exe(name))
+ return names
+
+ def check(self, running: set[str], now: float | None = None) -> None:
+ """Process one snapshot of running executable names."""
+ now = time.time() if now is None else now
+ if self._running is None:
+ self._running = running # apps already open at startup are not launches
+ return
+ launched = {n for n in running - self._running if catalog.is_trackable(n)}
+ self._running = running
+
+ today = date.today().isoformat()
+ for name in launched:
+ self._pending[name] = now
+ for name, seen in list(self._pending.items()):
+ if name not in running or now - seen > _PENDING_TTL:
+ del self._pending[name]
+ continue
+ app_id = queries.find_app_id(name)
+ if app_id is not None:
+ queries.increment_opens(today, app_id)
+ del self._pending[name]
diff --git a/apptrackr/core/tracker.py b/apptrackr/core/tracker.py
index eec2380..587dc5c 100644
--- a/apptrackr/core/tracker.py
+++ b/apptrackr/core/tracker.py
@@ -1,249 +1,254 @@
-"""Foreground window tracker – polls the active window and records focus sessions."""
+"""Foreground tracker: samples the focused app and records focus sessions.
+
+Time is committed to the database in small checkpoints, so totals are live,
+a crash loses at most one checkpoint interval, and sessions that cross
+midnight are split between days.
+"""
from __future__ import annotations
-import ctypes
-import ctypes.wintypes
-import hashlib
import logging
-import os
import threading
import time
-from dataclasses import dataclass, field
-from datetime import date
-
-import psutil
+from dataclasses import dataclass
+from typing import Callable
-from ..data import db, queries, rollup
+from ..data import catalog, db, queries
+from .platform import Platform
log = logging.getLogger(__name__)
-# Win32 API bindings
-user32 = ctypes.windll.user32 # type: ignore[attr-defined]
-kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
+STATUS_TRACKING = "tracking"
+STATUS_IDLE = "idle"
+STATUS_PAUSED = "paused"
+STATUS_LOCKED = "locked"
+STATUS_WAITING = "waiting" # nothing trackable in focus
+STATUS_UNSUPPORTED = "unsupported"
-# System / ignored executables
-_IGNORED_EXES = frozenset({
- "explorer.exe", "searchui.exe", "shellexperiencehost.exe",
- "startmenuexperiencehost.exe", "textinputhost.exe", "lockapp.exe",
- "systemsettings.exe", "searchhost.exe", "widgets.exe",
-})
+@dataclass(frozen=True)
+class Snapshot:
+ """Thread-safe view of the tracker for the UI."""
-@dataclass
-class _TrackerState:
- current_app_id: int | None = None
- current_session_id: int | None = None
- current_exe: str | None = None
- current_start: float = 0.0
- paused: bool = False
- running: bool = False
- session_locked: bool = False
+ status: str
+ app_id: int | None = None
+ exe_name: str | None = None
+ session_start: float = 0.0
+ session_ms: int = 0
+ uncommitted_ms: int = 0
+ paused_until: float | None = None
class Tracker:
- """Polls the foreground window and attributes time to apps."""
-
- def __init__(self) -> None:
- self._state = _TrackerState()
+ """Polls the platform for the focused app and attributes time to it."""
+
+ CHECKPOINT_SEC = 30.0
+ # A pause between samples longer than this means the machine slept or the
+ # process was suspended; the session is closed at the last sample.
+ GAP_SEC = 15.0
+ # Focus that changes with no input for this long was not caused by the user,
+ # so the previous session ends at the last input.
+ SWITCH_IDLE_SEC = 30.0
+
+ def __init__(self, platform: Platform, clock: Callable[[], float] = time.time) -> None:
+ self._platform = platform
+ self._clock = clock
+ self._lock = threading.RLock()
self._thread: threading.Thread | None = None
- self._lock = threading.Lock()
- self._callbacks: list = []
- self._idle_threshold: int = 300 # seconds
- self._poll_interval: float = 0.25 # 4 Hz
- self._track_titles: bool = False
+ self._stop = threading.Event()
+
+ self._idle_threshold = 300
+ self._poll_interval = 0.25
+ self._excluded: set[str] = set()
+
+ self._app_id: int | None = None
+ self._exe: str | None = None
+ self._session_id: int | None = None
+ self._session_start = 0.0
+ self._committed_until = 0.0
+ self._next_checkpoint = 0.0
+ self._last_tick: float | None = None
+ self._paused = False
+ self._paused_until: float | None = None
+ self._status = STATUS_WAITING if platform.supported else STATUS_UNSUPPORTED
# ------------------------------------------------------------------
- # Public control
+ # Lifecycle
# ------------------------------------------------------------------
def start(self) -> None:
- db.init_db()
- self._load_settings()
- self._state.running = True
+ self.reload_settings()
+ if not self._platform.supported:
+ log.info("Tracker not started: platform unsupported")
+ return
+ self._stop.clear()
self._thread = threading.Thread(target=self._loop, daemon=True, name="tracker")
self._thread.start()
- log.info("Tracker started (poll %.0f Hz)", 1 / self._poll_interval)
+ log.info("Tracker started (%.1f Hz, idle after %ss)", 1 / self._poll_interval, self._idle_threshold)
def stop(self) -> None:
- self._state.running = False
- self._flush()
+ self._stop.set()
+ if self._thread and self._thread.is_alive() and self._thread is not threading.current_thread():
+ self._thread.join(timeout=2)
+ with self._lock:
+ self._close(self._clock())
+
+ def reload_settings(self) -> None:
+ with self._lock:
+ self._idle_threshold = max(0, db.get_int("idle_threshold_sec", 300))
+ hz = min(max(db.get_int("polling_hz", 4), 1), 10)
+ self._poll_interval = 1.0 / hz
+ self._excluded = queries.hidden_exes()
+ if self._exe in self._excluded:
+ self._close(self._clock())
+
+ # ------------------------------------------------------------------
+ # Pause / resume
+ # ------------------------------------------------------------------
- def pause(self) -> None:
+ def pause(self, minutes: float | None = None) -> None:
+ """Pause tracking, optionally resuming automatically after *minutes*."""
with self._lock:
- self._state.paused = True
- self._flush_unlocked()
+ now = self._clock()
+ self._close(now)
+ self._paused = True
+ self._paused_until = now + minutes * 60 if minutes else None
+ self._status = STATUS_PAUSED
def resume(self) -> None:
with self._lock:
- self._state.paused = False
+ self._paused = False
+ self._paused_until = None
+ self._status = STATUS_WAITING
@property
def paused(self) -> bool:
- return self._state.paused
+ return self._paused
@property
- def current_exe(self) -> str | None:
- return self._state.current_exe
+ def supported(self) -> bool:
+ return self._platform.supported
@property
def current_app_id(self) -> int | None:
- return self._state.current_app_id
-
- @property
- def session_elapsed_ms(self) -> int:
- s = self._state
- if s.current_start and s.current_app_id and not s.paused:
- return int((time.time() - s.current_start) * 1000)
- return 0
+ """Lock-free read for hot paths such as the mouse hook."""
+ return self._app_id
- def on_change(self, callback) -> None:
- """Register callback(app_id, exe_name) for focus changes."""
- self._callbacks.append(callback)
-
- # ------------------------------------------------------------------
- # Settings
- # ------------------------------------------------------------------
-
- def _load_settings(self) -> None:
- self._idle_threshold = int(db.get_setting("idle_threshold_sec", "300"))
- self._track_titles = db.get_setting("track_window_titles", "0") == "1"
- hz = int(db.get_setting("polling_hz", "4"))
- self._poll_interval = 1.0 / max(hz, 1)
-
- def reload_settings(self) -> None:
- self._load_settings()
+ def snapshot(self) -> Snapshot:
+ with self._lock:
+ now = self._clock()
+ if self._app_id is None:
+ return Snapshot(self._status, paused_until=self._paused_until)
+ return Snapshot(
+ status=self._status,
+ app_id=self._app_id,
+ exe_name=self._exe,
+ session_start=self._session_start,
+ session_ms=int(max(0.0, now - self._session_start) * 1000),
+ uncommitted_ms=int(max(0.0, now - self._committed_until) * 1000),
+ paused_until=self._paused_until,
+ )
# ------------------------------------------------------------------
- # Main loop
+ # Sampling
# ------------------------------------------------------------------
def _loop(self) -> None:
- while self._state.running:
+ while not self._stop.is_set():
try:
- self._tick()
+ self.tick()
except Exception:
- log.exception("Tracker tick error")
- time.sleep(self._poll_interval)
+ log.exception("Tracker tick failed")
+ self._stop.wait(self._poll_interval)
+ db.close()
- def _tick(self) -> None:
+ def tick(self) -> None:
+ """Take one sample. Public so tests can drive the tracker deterministically."""
with self._lock:
- if self._state.paused or self._is_locked():
- if self._state.current_app_id:
- self._flush_unlocked()
- return
-
- # Idle detection
- if self._idle_threshold > 0 and self._get_idle_seconds() > self._idle_threshold:
- if self._state.current_app_id:
- self._flush_unlocked(was_idle=True)
+ now = self._clock()
+ last_tick, self._last_tick = self._last_tick, now
+ if last_tick is not None and now - last_tick > self.GAP_SEC:
+ self._close(last_tick)
+
+ if self._paused:
+ if self._paused_until is not None and now >= self._paused_until:
+ self.resume()
+ else:
+ return
+
+ idle = self._platform.idle_seconds() if self._idle_threshold else 0.0
+ # Checkpoints only commit time up to the last input, so a session
+ # that ends in idleness never has the idle stretch already counted.
+ last_input = now - idle
+
+ if self._platform.is_locked():
+ self._close(last_input)
+ self._status = STATUS_LOCKED
return
- hwnd = user32.GetForegroundWindow()
- if not hwnd:
+ if self._idle_threshold and idle >= self._idle_threshold:
+ self._close(last_input, was_idle=True)
+ self._status = STATUS_IDLE
return
- pid = ctypes.wintypes.DWORD()
- user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
- pid_val = pid.value
- if not pid_val:
+ fg = self._platform.foreground_app()
+ if fg is None:
+ if self._app_id is not None and now >= self._next_checkpoint:
+ self._checkpoint(last_input)
return
- try:
- proc = psutil.Process(pid_val)
- exe_name = proc.name().lower()
- exe_path = proc.exe()
- except (psutil.NoSuchProcess, psutil.AccessDenied):
- return
+ # A focus change nobody caused (a popup while the user is away) should
+ # not credit the away time to the previous app.
+ switch_end = last_input if idle >= self.SWITCH_IDLE_SEC else now
- if exe_name in _IGNORED_EXES:
+ exe = catalog.canonical_exe(fg.exe_name)
+ if not catalog.is_trackable(exe) or exe in self._excluded:
+ self._close(switch_end)
+ self._status = STATUS_WAITING
return
- # Same app as before → nothing to do
- if exe_name == self._state.current_exe:
+ if exe == self._exe:
+ self._status = STATUS_TRACKING
+ if now >= self._next_checkpoint:
+ self._checkpoint(last_input)
return
- # App changed – close old session, open new
- self._switch_app(exe_name, exe_path, hwnd)
-
- def _switch_app(self, exe_name: str, exe_path: str, hwnd: int) -> None:
- now = time.time()
-
- # Close previous session
- if self._state.current_session_id is not None:
- queries.end_session(self._state.current_session_id, now)
- rollup.rollup_session(self._state.current_session_id)
-
- # Get or create app
- app_id = queries.get_or_create_app(exe_name, icon_path=exe_path)
- session_id = queries.start_session(app_id, now)
- today = date.today().isoformat()
- queries.increment_opens(today, app_id)
-
- # Optional title tracking
- if self._track_titles:
- title_hash = self._hash_title(hwnd)
- queries.log_focus_event(app_id, "focus_in", title_hash)
-
- self._state.current_app_id = app_id
- self._state.current_session_id = session_id
- self._state.current_exe = exe_name
- self._state.current_start = now
-
- for cb in self._callbacks:
- try:
- cb(app_id, exe_name)
- except Exception:
- log.exception("Callback error")
-
- def _flush(self) -> None:
- with self._lock:
- self._flush_unlocked()
-
- def _flush_unlocked(self, was_idle: bool = False) -> None:
- if self._state.current_session_id is not None:
- queries.end_session(self._state.current_session_id, was_idle=was_idle)
- rollup.rollup_session(self._state.current_session_id)
- self._state.current_app_id = None
- self._state.current_session_id = None
- self._state.current_exe = None
- self._state.current_start = 0.0
- for cb in self._callbacks:
- try:
- cb(None, None)
- except Exception:
- log.exception("Callback error")
+ self._close(switch_end)
+ self._open(exe, fg.exe_path, now)
# ------------------------------------------------------------------
- # Win32 helpers
+ # Session bookkeeping (call with the lock held)
# ------------------------------------------------------------------
- @staticmethod
- def _get_idle_seconds() -> float:
- """Seconds since last user input (keyboard/mouse)."""
-
- class LASTINPUTINFO(ctypes.Structure):
- _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
-
- lii = LASTINPUTINFO()
- lii.cbSize = ctypes.sizeof(LASTINPUTINFO)
- if user32.GetLastInputInfo(ctypes.byref(lii)):
- millis = kernel32.GetTickCount() - lii.dwTime
- return millis / 1000.0
- return 0.0
-
- @staticmethod
- def _is_locked() -> bool:
- """Check if the workstation is locked."""
- # OpenInputDesktop returns NULL when desktop is locked / switched
- hdesk = user32.OpenInputDesktop(0, False, 0x0001) # DESKTOP_READOBJECTS
- if hdesk:
- user32.CloseDesktop(hdesk)
- return False
- return True
-
- @staticmethod
- def _hash_title(hwnd: int) -> str:
- buf = ctypes.create_unicode_buffer(512)
- user32.GetWindowTextW(hwnd, buf, 512)
- return hashlib.sha256(buf.value.encode()).hexdigest()[:16]
+ def _open(self, exe: str, exe_path: str | None, now: float) -> None:
+ self._app_id = queries.get_or_create_app(exe, icon_path=exe_path)
+ self._session_id = queries.start_session(self._app_id, now)
+ self._exe = exe
+ self._session_start = now
+ self._committed_until = now
+ self._next_checkpoint = now + self.CHECKPOINT_SEC
+ self._status = STATUS_TRACKING
+
+ def _checkpoint(self, now: float, was_idle: bool = False) -> None:
+ """Commit focus time up to *now* (never moves backwards)."""
+ if self._app_id is None or self._session_id is None:
+ return
+ end = max(now, self._committed_until)
+ if end > self._committed_until:
+ queries.add_focus_span(self._app_id, self._committed_until, end)
+ self._committed_until = end
+ queries.update_session_end(self._session_id, end, was_idle=was_idle)
+ db.commit()
+ self._next_checkpoint = self._clock() + self.CHECKPOINT_SEC
+
+ def _close(self, end: float, was_idle: bool = False) -> None:
+ if self._app_id is None:
+ return
+ try:
+ self._checkpoint(end, was_idle=was_idle)
+ finally:
+ self._app_id = None
+ self._exe = None
+ self._session_id = None
+ self._session_start = 0.0
+ self._committed_until = 0.0
diff --git a/apptrackr/data/catalog.py b/apptrackr/data/catalog.py
new file mode 100644
index 0000000..79177ab
--- /dev/null
+++ b/apptrackr/data/catalog.py
@@ -0,0 +1,158 @@
+"""Knowledge about Windows executables: aliases, friendly names and noise filters.
+
+Shared by the tracker (what to record) and the queries (what to list), so both
+agree on which processes count as real apps.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import PurePath
+
+# Shell surfaces and OS overlays. Focus on these is never attributed to an app.
+SYSTEM_EXES = frozenset(
+ {
+ "explorer.exe",
+ "searchui.exe",
+ "searchhost.exe",
+ "searchapp.exe",
+ "shellexperiencehost.exe",
+ "startmenuexperiencehost.exe",
+ "shellhost.exe",
+ "textinputhost.exe",
+ "lockapp.exe",
+ "logonui.exe",
+ "widgets.exe",
+ "widgetservice.exe",
+ "applicationframehost.exe",
+ "consent.exe",
+ "dwm.exe",
+ "taskmgr.exe.mui",
+ }
+)
+
+# Processes that may own a focused window briefly or appear in launch counts
+# but are not apps a person "uses". Hidden from every list.
+BACKGROUND_EXES = frozenset(
+ {
+ "system",
+ "registry",
+ "idle",
+ "taskhostw.exe",
+ "runtimebroker.exe",
+ "searchindexer.exe",
+ "conhost.exe",
+ "svchost.exe",
+ "sihost.exe",
+ "ctfmon.exe",
+ "csrss.exe",
+ "winlogon.exe",
+ "fontdrvhost.exe",
+ "smartscreen.exe",
+ "securityhealthsystray.exe",
+ }
+)
+
+BACKGROUND_SUBSTRINGS = ("crashpad", "crashhandler", "updater", "helper")
+
+# Helper processes that host an app's main UI are folded into the app.
+EXE_ALIASES = {
+ "steamwebhelper.exe": "steam.exe",
+ "msedgewebview2.exe": "msedge.exe",
+}
+
+NAME_OVERRIDES = {
+ "code.exe": "VS Code",
+ "code - insiders.exe": "VS Code Insiders",
+ "cursor.exe": "Cursor",
+ "devenv.exe": "Visual Studio",
+ "pycharm64.exe": "PyCharm",
+ "idea64.exe": "IntelliJ IDEA",
+ "windowsterminal.exe": "Windows Terminal",
+ "wt.exe": "Windows Terminal",
+ "powershell.exe": "PowerShell",
+ "pwsh.exe": "PowerShell",
+ "cmd.exe": "Command Prompt",
+ "claude.exe": "Claude",
+ "chatgpt.exe": "ChatGPT",
+ "steam.exe": "Steam",
+ "discord.exe": "Discord",
+ "slack.exe": "Slack",
+ "spotify.exe": "Spotify",
+ "obsidian.exe": "Obsidian",
+ "notion.exe": "Notion",
+ "figma.exe": "Figma",
+ "zoom.exe": "Zoom",
+ "chrome.exe": "Google Chrome",
+ "firefox.exe": "Firefox",
+ "msedge.exe": "Microsoft Edge",
+ "brave.exe": "Brave",
+ "opera.exe": "Opera",
+ "vivaldi.exe": "Vivaldi",
+ "teams.exe": "Microsoft Teams",
+ "ms-teams.exe": "Microsoft Teams",
+ "outlook.exe": "Outlook",
+ "olk.exe": "Outlook",
+ "winword.exe": "Word",
+ "excel.exe": "Excel",
+ "powerpnt.exe": "PowerPoint",
+ "onenote.exe": "OneNote",
+ "notepad.exe": "Notepad",
+ "notepad++.exe": "Notepad++",
+ "vlc.exe": "VLC",
+ "obs64.exe": "OBS Studio",
+ "taskmgr.exe": "Task Manager",
+ "apptrackr.exe": "AppTrackr",
+}
+
+
+def canonical_exe(exe_name: str) -> str:
+ """Lowercase, strip directories and fold helper aliases into their app."""
+ key = PurePath((exe_name or "").strip()).name.lower()
+ return EXE_ALIASES.get(key, key)
+
+
+def is_system(exe_name: str) -> bool:
+ return canonical_exe(exe_name) in SYSTEM_EXES
+
+
+def is_background(exe_name: str) -> bool:
+ name = canonical_exe(exe_name)
+ if not name or name in BACKGROUND_EXES:
+ return True
+ return any(token in name for token in BACKGROUND_SUBSTRINGS)
+
+
+def is_trackable(exe_name: str) -> bool:
+ """True when focus on this executable should be recorded."""
+ name = canonical_exe(exe_name)
+ return bool(name) and not is_system(name) and not is_background(name)
+
+
+def is_listable(exe_name: str) -> bool:
+ """True when the app should appear in lists and totals."""
+ return is_trackable(exe_name)
+
+
+def friendly_name(exe_name: str) -> str:
+ """Turn an executable name into a readable label ("my_tool.exe" -> "My Tool")."""
+ key = canonical_exe(exe_name)
+ if not key:
+ return "Unknown App"
+ if key in NAME_OVERRIDES:
+ return NAME_OVERRIDES[key]
+ raw = key[:-4] if key.endswith(".exe") else key
+ raw = re.sub(r"[_\-.]+", " ", raw)
+ raw = re.sub(r"\s+", " ", raw).strip()
+ if not raw:
+ return "Unknown App"
+ return " ".join(part[:1].upper() + part[1:] for part in raw.split(" "))
+
+
+def display_name(app: dict) -> str:
+ """Name to show for an app row, falling back to a friendly exe name."""
+ shown = (app.get("display_name") or "").strip()
+ exe = (app.get("exe_name") or "").strip().lower()
+ if not shown or shown.lower() == exe:
+ return friendly_name(exe)
+ return shown
diff --git a/apptrackr/data/db.py b/apptrackr/data/db.py
index 249b43f..e011c17 100644
--- a/apptrackr/data/db.py
+++ b/apptrackr/data/db.py
@@ -1,45 +1,182 @@
-"""SQLite database manager for AppTrackr."""
+"""SQLite access layer: per-thread connections, schema migrations and settings."""
from __future__ import annotations
-import os
+import logging
import sqlite3
import threading
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
+
+from .. import paths
+
+log = logging.getLogger(__name__)
-_DB_DIR = Path(os.environ.get("APPDATA", Path.home())) / "AppTrackr"
-_DB_PATH = _DB_DIR / "data.sqlite"
_SCHEMA = Path(__file__).with_name("schema.sql")
+SCHEMA_VERSION = 1
_local = threading.local()
+_generation = 0
+_gen_lock = threading.Lock()
+_path_override: Path | None = None
+
+
+def configure(path: str | Path | None) -> None:
+ """Point the data layer at a different database file.
+ Every thread reconnects lazily on its next query.
+ """
+ global _path_override, _generation
+ with _gen_lock:
+ _path_override = Path(path) if path else None
+ _generation += 1
-def _db_path() -> Path:
- return _DB_PATH
+
+def db_path() -> Path:
+ return _path_override or paths.db_path()
def get_connection() -> sqlite3.Connection:
- """Return a thread-local SQLite connection (created once per thread)."""
+ """Return this thread's connection, reconnecting after configure()."""
conn: sqlite3.Connection | None = getattr(_local, "conn", None)
- if conn is None:
- _DB_DIR.mkdir(parents=True, exist_ok=True)
- conn = sqlite3.connect(str(_db_path()), check_same_thread=False)
- conn.row_factory = sqlite3.Row
- conn.execute("PRAGMA journal_mode=WAL")
- conn.execute("PRAGMA foreign_keys=ON")
- _local.conn = conn
+ if conn is not None and getattr(_local, "gen", -1) == _generation:
+ return conn
+ if conn is not None:
+ conn.close()
+ target = db_path()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ conn = sqlite3.connect(str(target), timeout=15, check_same_thread=False)
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA foreign_keys=ON")
+ conn.execute("PRAGMA synchronous=NORMAL")
+ _local.conn = conn
+ _local.gen = _generation
return conn
+def close() -> None:
+ """Close the calling thread's connection, if any."""
+ conn: sqlite3.Connection | None = getattr(_local, "conn", None)
+ if conn is not None:
+ conn.close()
+ _local.conn = None
+
+
+def _table_exists(conn: sqlite3.Connection, name: str) -> bool:
+ row = conn.execute("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", (name,)).fetchone()
+ return row is not None
+
+
+def _columns(conn: sqlite3.Connection, table: str) -> set[str]:
+ return {r["name"] for r in conn.execute(f"PRAGMA table_info({table})")}
+
+
def init_db() -> None:
- """Create tables if they don't exist."""
+ """Create the schema on first run and migrate older databases."""
conn = get_connection()
- schema_sql = _SCHEMA.read_text(encoding="utf-8")
- conn.executescript(schema_sql)
+ fresh = not _table_exists(conn, "apps")
+ 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)
+ migrate(conn)
+ version = target
+ conn.execute(f"PRAGMA user_version = {int(version)}")
conn.commit()
+# ---------------------------------------------------------------------------
+# Migrations
+# ---------------------------------------------------------------------------
+
+
+def _migrate_v1(conn: sqlite3.Connection) -> None:
+ """v1.0 -> v1.1.
+
+ Adds per-app exclusion and daily limits, and rebuilds focused time from the
+ raw sessions. v1.0 dropped whole sessions that ended in idle and charged
+ sessions that crossed midnight to the start day; the rebuild recovers both.
+ """
+ from .spans import split_by_day
+
+ cols = _columns(conn, "apps")
+ if "is_hidden" not in cols:
+ conn.execute("ALTER TABLE apps ADD COLUMN is_hidden INTEGER NOT NULL DEFAULT 0")
+ if "daily_limit_ms" not in cols:
+ conn.execute("ALTER TABLE apps ADD COLUMN daily_limit_ms INTEGER")
+ _merge_alias_apps(conn)
+
+ row = conn.execute("SELECT value FROM settings WHERE key = 'idle_threshold_sec'").fetchone()
+ idle_ms = int(row["value"]) * 1000 if row and str(row["value"]).isdigit() else 300_000
+
+ totals: dict[tuple[str, int], int] = {}
+ sessions = conn.execute(
+ "SELECT app_id, start_ts, duration_ms, was_idle FROM usage_sessions "
+ "WHERE end_ts IS NOT NULL AND duration_ms > 0"
+ ).fetchall()
+ for s in sessions:
+ ms = s["duration_ms"] - (idle_ms if s["was_idle"] else 0)
+ if ms <= 0:
+ continue
+ for day, part in split_by_day(s["start_ts"], s["start_ts"] + ms / 1000):
+ key = (day, s["app_id"])
+ totals[key] = totals.get(key, 0) + part
+
+ conn.execute("UPDATE daily_rollup SET focused_ms = 0")
+ conn.executemany(
+ "INSERT INTO daily_rollup (day, app_id, focused_ms) VALUES (?, ?, ?) "
+ "ON CONFLICT(day, app_id) DO UPDATE SET focused_ms = excluded.focused_ms",
+ [(day, app_id, ms) for (day, app_id), ms in totals.items()],
+ )
+ conn.execute("DELETE FROM usage_sessions WHERE end_ts IS NULL")
+
+
+def _merge_alias_apps(conn: sqlite3.Connection) -> None:
+ """Fold rows for helper executables (e.g. steamwebhelper.exe) into their app."""
+ from .catalog import EXE_ALIASES
+
+ for alias, canonical in EXE_ALIASES.items():
+ old = conn.execute("SELECT app_id FROM apps WHERE exe_name = ?", (alias,)).fetchone()
+ if not old:
+ continue
+ new = conn.execute("SELECT app_id FROM apps WHERE exe_name = ?", (canonical,)).fetchone()
+ if not new:
+ conn.execute(
+ "UPDATE apps SET exe_name = ?, display_name = NULL WHERE app_id = ?", (canonical, old["app_id"])
+ )
+ continue
+ old_id, new_id = old["app_id"], new["app_id"]
+ conn.execute(
+ "INSERT INTO daily_rollup (day, app_id, focused_ms, opens_count, clicks_count) "
+ "SELECT day, ?, focused_ms, opens_count, clicks_count FROM daily_rollup WHERE app_id = ? "
+ "ON CONFLICT(day, app_id) DO UPDATE SET focused_ms = focused_ms + excluded.focused_ms, "
+ "opens_count = opens_count + excluded.opens_count, clicks_count = clicks_count + excluded.clicks_count",
+ (new_id, old_id),
+ )
+ conn.execute("DELETE FROM daily_rollup WHERE app_id = ?", (old_id,))
+ if conn.execute("SELECT 1 FROM reward_rules WHERE app_id = ?", (new_id,)).fetchone():
+ # Keep the alias's rules for its reward history, but don't pay out twice.
+ conn.execute("UPDATE reward_rules SET enabled = 0 WHERE app_id = ?", (old_id,))
+ for table in ("usage_sessions", "focus_events", "reward_rules", "reward_events"):
+ if _table_exists(conn, table):
+ conn.execute(f"UPDATE {table} SET app_id = ? WHERE app_id = ?", (new_id, old_id))
+ conn.execute("DELETE FROM apps WHERE app_id = ?", (old_id,))
+
+
+_MIGRATIONS: list[tuple[int, Callable[[sqlite3.Connection], None]]] = [
+ (1, _migrate_v1),
+]
+
+
+# ---------------------------------------------------------------------------
+# Query helpers
+# ---------------------------------------------------------------------------
+
+
def execute(sql: str, params: tuple[Any, ...] = ()) -> sqlite3.Cursor:
return get_connection().execute(sql, params)
@@ -61,14 +198,28 @@ def fetchall(sql: str, params: tuple[Any, ...] = ()) -> list[sqlite3.Row]:
# ---------------------------------------------------------------------------
-# Settings helpers
+# Settings
# ---------------------------------------------------------------------------
+
def get_setting(key: str, default: str = "") -> str:
row = fetchone("SELECT value FROM settings WHERE key = ?", (key,))
return row["value"] if row else default
-def set_setting(key: str, value: str) -> None:
- execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, value))
+def get_bool(key: str, default: bool = False) -> bool:
+ return get_setting(key, "1" if default else "0") == "1"
+
+
+def get_int(key: str, default: int = 0) -> int:
+ try:
+ return int(get_setting(key, str(default)))
+ except ValueError:
+ return default
+
+
+def set_setting(key: str, value: str | int | bool) -> None:
+ if isinstance(value, bool):
+ value = "1" if value else "0"
+ execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, str(value)))
commit()
diff --git a/apptrackr/data/demo.py b/apptrackr/data/demo.py
new file mode 100644
index 0000000..2c30608
--- /dev/null
+++ b/apptrackr/data/demo.py
@@ -0,0 +1,128 @@
+"""Deterministic sample data for --demo, screenshots and tests."""
+
+from __future__ import annotations
+
+import json
+import random
+from datetime import date, datetime, timedelta
+
+from . import db
+from .spans import split_by_day
+
+# exe, category, weekday weight, weekend weight, favorite
+DEMO_APPS = [
+ ("code.exe", "Development", 3.4, 0.9, True),
+ ("chrome.exe", "Work", 2.2, 1.7, False),
+ ("windowsterminal.exe", "Development", 1.1, 0.2, False),
+ ("slack.exe", "Communication", 0.9, 0.1, False),
+ ("figma.exe", "Work", 0.8, 0.1, False),
+ ("obsidian.exe", "Study", 0.6, 0.7, True),
+ ("discord.exe", "Social", 0.6, 1.3, False),
+ ("spotify.exe", "Entertainment", 0.3, 0.5, False),
+ ("olk.exe", "Communication", 0.5, 0.05, False),
+ ("excel.exe", "Work", 0.4, 0.02, False),
+ ("steam.exe", "Games", 0.05, 1.6, False),
+ ("notion.exe", "Work", 0.35, 0.25, False),
+ ("ms-teams.exe", "Communication", 0.4, 0.0, False),
+]
+HIDDEN = {"ms-teams.exe"}
+LIMITS = {"discord.exe": 45 * 60 * 1000}
+REWARD_APPS = ("code.exe", "obsidian.exe", "chrome.exe")
+
+
+def _day_blocks(rng: random.Random, weekend: bool) -> list[tuple[float, float]]:
+ """Active hour ranges for a day."""
+ if weekend:
+ blocks = [
+ (10.5 + rng.random(), 13 + rng.random()),
+ (15 + rng.random(), 17.5 + rng.random()),
+ (20 + rng.random(), 23 + rng.random() * 0.6),
+ ]
+ return [b for b in blocks if rng.random() < 0.8]
+ start = 8.4 + rng.random() * 1.0
+ return [
+ (start, 12.2 + rng.random() * 0.5),
+ (13.1 + rng.random() * 0.4, 17.6 + rng.random() * 1.2),
+ (20.3 + rng.random(), 22.0 + rng.random()),
+ ]
+
+
+def seed(days: int = 120, seed_value: int = 7, now: datetime | None = None) -> None:
+ """Fill the configured database with sample history ending at *now*."""
+ rng = random.Random(seed_value)
+ now = now or datetime.now()
+ db.init_db()
+
+ app_ids: dict[str, int] = {}
+ for exe, category, _wd, _we, fav in DEMO_APPS:
+ cur = db.execute(
+ "INSERT OR IGNORE INTO apps (exe_name, display_name, is_favorite, category, is_hidden, daily_limit_ms) "
+ "VALUES (?, NULL, ?, ?, ?, ?)",
+ (exe, int(fav), category, int(exe in HIDDEN), LIMITS.get(exe)),
+ )
+ row = db.fetchone("SELECT app_id FROM apps WHERE exe_name = ?", (exe,))
+ app_ids[exe] = row["app_id"] if row else int(cur.lastrowid)
+
+ sessions: list[tuple] = []
+ rollup: dict[tuple[str, int], list[int]] = {}
+ cutoff = now.timestamp() - 90
+
+ for offset in range(days, -1, -1):
+ d = now.date() - timedelta(days=offset)
+ weekend = d.weekday() >= 5
+ if rng.random() < (0.12 if weekend else 0.04):
+ continue # a day off
+ weights = [(exe, we if weekend else wd) for exe, _c, wd, we, _f in DEMO_APPS]
+ exes = [w[0] for w in weights]
+ wts = [w[1] for w in weights]
+ for start_h, end_h in _day_blocks(rng, weekend):
+ t = datetime.combine(d, datetime.min.time()).timestamp() + start_h * 3600
+ end = datetime.combine(d, datetime.min.time()).timestamp() + end_h * 3600
+ while t < end and t < cutoff:
+ exe = rng.choices(exes, wts)[0]
+ length = min(rng.expovariate(1 / (14 * 60)) + 45, 75 * 60)
+ stop = min(t + length, end, cutoff)
+ if stop - t >= 5:
+ sessions.append((app_ids[exe], t, stop, int((stop - t) * 1000)))
+ for day, ms in split_by_day(t, stop):
+ rollup.setdefault((day, app_ids[exe]), [0, 0, 0])[0] += ms
+ t = stop + rng.choice((2, 5, 10, 30, 60, 240))
+
+ for vals in rollup.values():
+ minutes = vals[0] / 60000
+ vals[1] = max(1, min(6, int(minutes // 50) + rng.randint(0, 2)))
+ vals[2] = int(minutes * rng.uniform(8, 30))
+
+ db.executemany("INSERT INTO usage_sessions (app_id, start_ts, end_ts, duration_ms) VALUES (?, ?, ?, ?)", sessions)
+ db.executemany(
+ "INSERT INTO daily_rollup (day, app_id, focused_ms, opens_count, clicks_count) VALUES (?, ?, ?, ?, ?) "
+ "ON CONFLICT(day, app_id) DO UPDATE SET focused_ms = excluded.focused_ms, "
+ "opens_count = excluded.opens_count, clicks_count = excluded.clicks_count",
+ [(day, app_id, *vals) for (day, app_id), vals in rollup.items()],
+ )
+
+ _seed_rewards(app_ids)
+ for key, value in {"track_clicks": "1", "auto_update_check": "0"}.items():
+ db.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, value))
+ db.commit()
+
+
+def _seed_rewards(app_ids: dict[str, int]) -> None:
+ from ..rewards import engine, rules
+
+ for exe in REWARD_APPS:
+ rules.enable_app_rewards(app_ids[exe], True)
+ yesterday = (date.today() - timedelta(days=1)).isoformat()
+ engine.evaluate(yesterday)
+ db.execute("UPDATE reward_events SET claimed = 1")
+ db.execute(
+ "UPDATE player_profile SET xp = 1240, level = 13, credits = 85, streak_days = 9, "
+ "last_streak_day = ? WHERE profile_id = 1",
+ (yesterday,),
+ )
+ village = {
+ "buildings": {"workshop": {"level": 3}, "storage": {"level": 2}, "house": {"level": 2}, "lab": {"level": 1}},
+ "villagers": 2,
+ "inventory": {"wood": 142, "stone": 96, "metal": 38, "food": 61, "blueprints": 3},
+ }
+ db.execute("UPDATE village_state SET state_json = ? WHERE profile_id = 1", (json.dumps(village),))
diff --git a/apptrackr/data/export.py b/apptrackr/data/export.py
index 6d10049..85cfa07 100644
--- a/apptrackr/data/export.py
+++ b/apptrackr/data/export.py
@@ -1,48 +1,97 @@
-"""Export / import helpers for AppTrackr data."""
+"""Export, backup and restore."""
from __future__ import annotations
import csv
-import io
import json
-import shutil
+import sqlite3
from pathlib import Path
-from . import db
+from . import catalog, db
+_EXPORT_SQL = (
+ "SELECT r.day, a.exe_name, a.display_name, a.category, r.focused_ms, r.opens_count, r.clicks_count "
+ "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id "
+ "WHERE a.is_hidden = 0 ORDER BY r.day, r.focused_ms DESC"
+)
+_FIELDS = ["day", "exe_name", "app", "category", "focused_ms", "focused_minutes", "opens_count", "clicks_count"]
-def export_csv(filepath: str | Path) -> None:
- """Export daily_rollup joined with apps as CSV."""
- rows = db.fetchall(
- "SELECT r.day, a.exe_name, a.display_name, r.focused_ms, r.opens_count, r.clicks_count "
- "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id ORDER BY r.day, r.focused_ms DESC"
- )
+
+def _export_rows() -> list[dict]:
+ rows = []
+ for r in db.fetchall(_EXPORT_SQL):
+ if not catalog.is_listable(r["exe_name"]):
+ continue
+ rows.append(
+ {
+ "day": r["day"],
+ "exe_name": r["exe_name"],
+ "app": catalog.display_name(dict(r)),
+ "category": r["category"] or "",
+ "focused_ms": r["focused_ms"],
+ "focused_minutes": round(r["focused_ms"] / 60000, 1),
+ "opens_count": r["opens_count"],
+ "clicks_count": r["clicks_count"],
+ }
+ )
+ return rows
+
+
+def export_csv(filepath: str | Path) -> int:
+ """Write per-day, per-app usage as CSV. Returns the number of rows."""
+ rows = _export_rows()
with open(filepath, "w", newline="", encoding="utf-8") as f:
- writer = csv.writer(f)
- writer.writerow(["day", "exe_name", "display_name", "focused_ms", "opens_count", "clicks_count"])
- for row in rows:
- writer.writerow([row["day"], row["exe_name"], row["display_name"],
- row["focused_ms"], row["opens_count"], row["clicks_count"]])
-
-
-def export_json(filepath: str | Path) -> None:
- """Export daily_rollup joined with apps as JSON."""
- rows = db.fetchall(
- "SELECT r.day, a.exe_name, a.display_name, r.focused_ms, r.opens_count, r.clicks_count "
- "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id ORDER BY r.day, r.focused_ms DESC"
- )
- data = [dict(r) for r in rows]
+ writer = csv.DictWriter(f, fieldnames=_FIELDS)
+ writer.writeheader()
+ writer.writerows(rows)
+ return len(rows)
+
+
+def export_json(filepath: str | Path) -> int:
+ rows = _export_rows()
with open(filepath, "w", encoding="utf-8") as f:
- json.dump(data, f, indent=2)
+ json.dump(rows, f, indent=2)
+ return len(rows)
def backup_db(dest: str | Path) -> None:
- """Copy the entire SQLite file as a backup."""
- src = db._db_path()
- shutil.copy2(str(src), str(dest))
+ """Write a consistent copy of the live database (WAL contents included)."""
+ dest = Path(dest)
+ if dest.exists():
+ dest.unlink()
+ target = sqlite3.connect(str(dest))
+ try:
+ db.get_connection().backup(target)
+ finally:
+ target.close()
+
+
+class RestoreError(Exception):
+ pass
+
+
+def validate_backup(src: str | Path) -> None:
+ """Raise RestoreError unless *src* looks like an AppTrackr database."""
+ try:
+ conn = sqlite3.connect(Path(src).resolve().as_uri() + "?mode=ro", uri=True)
+ try:
+ tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
+ if conn.execute("PRAGMA integrity_check").fetchone()[0] != "ok":
+ raise RestoreError("The backup file is damaged.")
+ finally:
+ conn.close()
+ except sqlite3.DatabaseError as exc:
+ raise RestoreError("The file is not a SQLite database.") from exc
+ if not {"apps", "daily_rollup", "usage_sessions"} <= tables:
+ raise RestoreError("The file is not an AppTrackr backup.")
def restore_db(src: str | Path) -> None:
- """Replace the current database with a backup file. App must restart after."""
- dest = db._db_path()
- shutil.copy2(str(src), str(dest))
+ """Replace the live database with *src*, then migrate it to the current schema."""
+ validate_backup(src)
+ source = sqlite3.connect(str(src))
+ try:
+ source.backup(db.get_connection())
+ finally:
+ source.close()
+ db.init_db()
diff --git a/apptrackr/data/queries.py b/apptrackr/data/queries.py
index bfbfa5c..cba9431 100644
--- a/apptrackr/data/queries.py
+++ b/apptrackr/data/queries.py
@@ -1,133 +1,95 @@
-"""Query helpers for AppTrackr analytics."""
+"""Read and write helpers for apps, sessions and daily aggregates."""
from __future__ import annotations
-import time
-import re
from datetime import date, datetime, timedelta
-from pathlib import Path
-
-from . import db
-
-
-_DASHBOARD_HIDDEN_EXES = {
- "system",
- "registry",
- "idle",
- "dwm.exe",
- "taskhostw.exe",
- "runtimebroker.exe",
- "searchhost.exe",
- "searchindexer.exe",
- "shellexperiencehost.exe",
- "startmenuexperiencehost.exe",
- "textinputhost.exe",
- "applicationframehost.exe",
- "widgetservice.exe",
- "widgets.exe",
- "conhost.exe",
-}
+from . import catalog, db
+from .spans import split_by_day, split_by_hour
+
+CATEGORIES = ("Work", "Study", "Development", "Communication", "Games", "Social", "Entertainment", "Tools")
+
+SORT_FOCUSED = "focused"
+SORT_LEAST = "least"
+SORT_OPENS = "opens"
+SORT_CLICKS = "clicks"
-_HELPER_EXE_SUBSTRINGS = (
- "helper",
- "crashpad",
- "updater",
-)
-
-
-_NAME_OVERRIDES = {
- "code.exe": "VS Code",
- "claude.exe": "Claude",
- "steam.exe": "Steam",
- "steamwebhelper.exe": "Steam",
- "discord.exe": "Discord",
- "chrome.exe": "Google Chrome",
- "firefox.exe": "Firefox",
- "msedge.exe": "Microsoft Edge",
- "teams.exe": "Microsoft Teams",
- "notepad.exe": "Notepad",
- "notepad++.exe": "Notepad++",
+_ORDER_SQL = {
+ SORT_FOCUSED: "focused_ms DESC",
+ SORT_LEAST: "focused_ms ASC",
+ SORT_OPENS: "opens_count DESC, focused_ms DESC",
+ SORT_CLICKS: "clicks_count DESC, focused_ms DESC",
}
-def normalize_app_name(exe_name: str) -> str:
- """Convert exe/process names into readable app labels."""
- key = (exe_name or "").strip().lower()
- if not key:
- return "Unknown App"
- if key in _NAME_OVERRIDES:
- return _NAME_OVERRIDES[key]
+# ---------------------------------------------------------------------------
+# Dates
+# ---------------------------------------------------------------------------
- raw = Path(key).name
- if raw.endswith(".exe"):
- raw = raw[:-4]
- raw = raw.replace("_", " ").replace("-", " ")
- raw = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", raw)
- raw = re.sub(r"\s+", " ", raw).strip()
+def today_str() -> str:
+ return date.today().isoformat()
- if not raw:
- return "Unknown App"
- return " ".join(part.capitalize() for part in raw.split(" "))
+def days_ago(n: int) -> str:
+ return (date.today() - timedelta(days=n)).isoformat()
-def is_dashboard_hidden_process(exe_name: str) -> bool:
- """Return True for process names we don't want in Dashboard Top Apps."""
- name = (exe_name or "").lower().strip()
- if not name:
- return True
- if name in _DASHBOARD_HIDDEN_EXES:
- return True
- return any(token in name for token in _HELPER_EXE_SUBSTRINGS)
+
+def week_start() -> str:
+ today = date.today()
+ return (today - timedelta(days=today.weekday())).isoformat()
# ---------------------------------------------------------------------------
-# App CRUD
+# Apps
# ---------------------------------------------------------------------------
-def get_or_create_app(
- exe_name: str,
- display_name: str | None = None,
- icon_path: str | None = None,
-) -> int:
- """Return app_id for *exe_name*, creating the row if needed."""
- exe_name = (exe_name or "").strip().lower()
- preferred_name = (display_name or normalize_app_name(exe_name)).strip()
- row = db.fetchone(
- "SELECT app_id, display_name, icon_path FROM apps WHERE exe_name = ?",
- (exe_name,),
- )
+def find_app_id(exe_name: str) -> int | None:
+ row = db.fetchone("SELECT app_id FROM apps WHERE exe_name = ?", (catalog.canonical_exe(exe_name),))
+ return row["app_id"] if row else None
+
+
+def get_or_create_app(exe_name: str, icon_path: str | None = None) -> int:
+ """Return the app_id for *exe_name*, creating the row on first sight."""
+ exe = catalog.canonical_exe(exe_name)
+ row = db.fetchone("SELECT app_id, display_name, icon_path FROM apps WHERE exe_name = ?", (exe,))
if row:
- # Backfill friendly display name and icon for older rows.
- current_display = (row["display_name"] or "").strip()
- needs_display = (not current_display) or (current_display.lower() == exe_name)
- current_icon = row["icon_path"]
- if needs_display or (icon_path and not current_icon):
+ needs_name = not (row["display_name"] or "").strip()
+ needs_icon = bool(icon_path) and not row["icon_path"]
+ if needs_name or needs_icon:
db.execute(
- "UPDATE apps SET display_name = COALESCE(?, display_name), "
+ "UPDATE apps SET display_name = COALESCE(display_name, ?), "
"icon_path = COALESCE(icon_path, ?) WHERE app_id = ?",
- (preferred_name if needs_display else None, icon_path, row["app_id"]),
+ (catalog.friendly_name(exe), icon_path, row["app_id"]),
)
db.commit()
return row["app_id"]
-
cur = db.execute(
"INSERT INTO apps (exe_name, display_name, icon_path) VALUES (?, ?, ?)",
- (exe_name, preferred_name, icon_path),
+ (exe, catalog.friendly_name(exe), icon_path),
)
db.commit()
- return cur.lastrowid # type: ignore[return-value]
+ return int(cur.lastrowid)
def get_app(app_id: int) -> dict | None:
row = db.fetchone("SELECT * FROM apps WHERE app_id = ?", (app_id,))
- return dict(row) if row else None
+ if not row:
+ return None
+ app = dict(row)
+ app["name"] = catalog.display_name(app)
+ return app
-def list_apps() -> list[dict]:
- return [dict(r) for r in db.fetchall("SELECT * FROM apps ORDER BY display_name")]
+def hidden_apps() -> list[dict]:
+ rows = db.fetchall("SELECT * FROM apps WHERE is_hidden = 1")
+ apps = [dict(r) | {"name": catalog.display_name(dict(r))} for r in rows]
+ return sorted(apps, key=lambda a: a["name"].lower())
+
+
+def hidden_exes() -> set[str]:
+ return {r["exe_name"] for r in db.fetchall("SELECT exe_name FROM apps WHERE is_hidden = 1")}
def set_favorite(app_id: int, is_fav: bool) -> None:
@@ -136,64 +98,67 @@ def set_favorite(app_id: int, is_fav: bool) -> None:
def set_category(app_id: int, category: str | None) -> None:
- db.execute("UPDATE apps SET category = ? WHERE app_id = ?", (category, app_id))
+ db.execute("UPDATE apps SET category = ? WHERE app_id = ?", (category or None, app_id))
db.commit()
-# ---------------------------------------------------------------------------
-# Sessions
-# ---------------------------------------------------------------------------
+def set_display_name(app_id: int, name: str | None) -> None:
+ db.execute("UPDATE apps SET display_name = ? WHERE app_id = ?", ((name or "").strip() or None, app_id))
+ db.commit()
-def start_session(app_id: int, ts: float | None = None) -> int:
- ts = ts or time.time()
- cur = db.execute(
- "INSERT INTO usage_sessions (app_id, start_ts) VALUES (?, ?)",
- (app_id, ts),
- )
+
+def set_hidden(app_id: int, hidden: bool) -> None:
+ db.execute("UPDATE apps SET is_hidden = ? WHERE app_id = ?", (int(hidden), app_id))
db.commit()
- return cur.lastrowid # type: ignore[return-value]
-def end_session(session_id: int, ts: float | None = None, was_idle: bool = False) -> None:
- ts = ts or time.time()
- db.execute(
- "UPDATE usage_sessions SET end_ts = ?, duration_ms = CAST((? - start_ts) * 1000 AS INTEGER), was_idle = ? "
- "WHERE session_id = ?",
- (ts, ts, int(was_idle), session_id),
- )
+def set_daily_limit(app_id: int, limit_ms: int | None) -> None:
+ db.execute("UPDATE apps SET daily_limit_ms = ? WHERE app_id = ?", (limit_ms or None, app_id))
db.commit()
+def apps_with_limits() -> list[dict]:
+ rows = db.fetchall("SELECT * FROM apps WHERE daily_limit_ms IS NOT NULL AND daily_limit_ms > 0 AND is_hidden = 0")
+ return [dict(r) | {"name": catalog.display_name(dict(r))} for r in rows]
+
+
# ---------------------------------------------------------------------------
-# Focus events (debug / window-title tracking)
+# Sessions and aggregates (written by the tracker)
# ---------------------------------------------------------------------------
-def log_focus_event(app_id: int, event_type: str, title_hash: str | None = None) -> None:
- db.execute(
- "INSERT INTO focus_events (ts, app_id, window_title_hash, event_type) VALUES (?, ?, ?, ?)",
- (time.time(), app_id, title_hash, event_type),
+
+def start_session(app_id: int, ts: float) -> int:
+ cur = db.execute(
+ "INSERT INTO usage_sessions (app_id, start_ts, end_ts, duration_ms) VALUES (?, ?, ?, 0)",
+ (app_id, ts, ts),
)
db.commit()
+ return int(cur.lastrowid)
-# ---------------------------------------------------------------------------
-# Daily rollup
-# ---------------------------------------------------------------------------
-
-def add_focused_time(day: str, app_id: int, ms: int) -> None:
+def update_session_end(session_id: int, end_ts: float, was_idle: bool = False) -> None:
db.execute(
- "INSERT INTO daily_rollup (day, app_id, focused_ms) VALUES (?, ?, ?) "
- "ON CONFLICT(day, app_id) DO UPDATE SET focused_ms = focused_ms + ?",
- (day, app_id, ms, ms),
+ "UPDATE usage_sessions SET end_ts = ?, duration_ms = MAX(0, CAST((? - start_ts) * 1000 AS INTEGER)), "
+ "was_idle = ? WHERE session_id = ?",
+ (end_ts, end_ts, int(was_idle), session_id),
)
- db.commit()
-def increment_opens(day: str, app_id: int) -> None:
+def add_focus_span(app_id: int, start_ts: float, end_ts: float) -> None:
+ """Credit [start_ts, end_ts) of focus to *app_id*, split across local days."""
+ for day, ms in split_by_day(start_ts, end_ts):
+ db.execute(
+ "INSERT INTO daily_rollup (day, app_id, focused_ms) VALUES (?, ?, ?) "
+ "ON CONFLICT(day, app_id) DO UPDATE SET focused_ms = focused_ms + excluded.focused_ms",
+ (day, app_id, ms),
+ )
+
+
+def increment_opens(day: str, app_id: int, count: int = 1) -> None:
db.execute(
- "INSERT INTO daily_rollup (day, app_id, opens_count) VALUES (?, ?, 1) "
- "ON CONFLICT(day, app_id) DO UPDATE SET opens_count = opens_count + 1",
- (day, app_id),
+ "INSERT INTO daily_rollup (day, app_id, opens_count) VALUES (?, ?, ?) "
+ "ON CONFLICT(day, app_id) DO UPDATE SET opens_count = opens_count + excluded.opens_count",
+ (day, app_id, count),
)
db.commit()
@@ -201,137 +166,150 @@ def increment_opens(day: str, app_id: int) -> None:
def increment_clicks(day: str, app_id: int, count: int = 1) -> None:
db.execute(
"INSERT INTO daily_rollup (day, app_id, clicks_count) VALUES (?, ?, ?) "
- "ON CONFLICT(day, app_id) DO UPDATE SET clicks_count = clicks_count + ?",
- (day, app_id, count, count),
+ "ON CONFLICT(day, app_id) DO UPDATE SET clicks_count = clicks_count + excluded.clicks_count",
+ (day, app_id, count),
)
db.commit()
# ---------------------------------------------------------------------------
-# Analytic queries
+# Analytics
# ---------------------------------------------------------------------------
-def today_str() -> str:
- return date.today().isoformat()
-
-
-def today_total_ms() -> int:
- row = db.fetchone(
- "SELECT COALESCE(SUM(focused_ms), 0) AS total FROM daily_rollup WHERE day = ?",
- (today_str(),),
- )
- return row["total"] if row else 0
-
-
-def top_apps_today(limit: int = 10) -> list[dict]:
- rows = db.fetchall(
- "SELECT a.app_id, a.exe_name, a.display_name, a.icon_path, a.is_favorite, "
- " r.focused_ms, r.opens_count, r.clicks_count "
- "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id "
- "WHERE r.day = ? ORDER BY r.focused_ms DESC LIMIT ?",
- (today_str(), limit),
- )
- return [dict(r) for r in rows]
-
-
-def dashboard_top_apps_today(limit: int = 10) -> list[dict]:
- """Top apps for dashboard with system/helper processes filtered out."""
- rows = top_apps_today(limit=200)
- filtered = [r for r in rows if not is_dashboard_hidden_process(r.get("exe_name", ""))]
- return filtered[:limit]
-
-def top_apps_range(start_day: str, end_day: str, limit: int = 20) -> list[dict]:
+def _visible(rows) -> list[dict]:
+ out = []
+ for r in rows:
+ app = dict(r)
+ if not catalog.is_listable(app.get("exe_name", "")):
+ continue
+ app["name"] = catalog.display_name(app)
+ out.append(app)
+ return out
+
+
+def top_apps(
+ start_day: str,
+ end_day: str,
+ sort: str = SORT_FOCUSED,
+ limit: int | None = 20,
+ category: str | None = None,
+ favorites_only: bool = False,
+ search: str = "",
+) -> list[dict]:
+ """Aggregate usage per app for an inclusive day range."""
+ where = ["r.day BETWEEN ? AND ?", "a.is_hidden = 0"]
+ params: list = [start_day, end_day]
+ if category:
+ where.append("a.category = ?")
+ params.append(category)
+ if favorites_only:
+ where.append("a.is_favorite = 1")
+ having = {
+ SORT_OPENS: "SUM(r.opens_count) > 0",
+ SORT_CLICKS: "SUM(r.clicks_count) > 0",
+ }.get(sort, "SUM(r.focused_ms) > 0")
rows = db.fetchall(
- "SELECT a.app_id, a.exe_name, a.display_name, a.icon_path, a.is_favorite, "
- " SUM(r.focused_ms) AS focused_ms, SUM(r.opens_count) AS opens_count, "
- " SUM(r.clicks_count) AS clicks_count "
+ "SELECT a.app_id, a.exe_name, a.display_name, a.icon_path, a.is_favorite, a.category, "
+ " a.daily_limit_ms, SUM(r.focused_ms) AS focused_ms, SUM(r.opens_count) AS opens_count, "
+ " SUM(r.clicks_count) AS clicks_count, COUNT(DISTINCT CASE WHEN r.focused_ms > 0 "
+ " THEN r.day END) AS active_days "
"FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id "
- "WHERE r.day BETWEEN ? AND ? GROUP BY a.app_id ORDER BY focused_ms DESC LIMIT ?",
- (start_day, end_day, limit),
+ f"WHERE {' AND '.join(where)} GROUP BY a.app_id HAVING {having} "
+ f"ORDER BY {_ORDER_SQL.get(sort, _ORDER_SQL[SORT_FOCUSED])}",
+ tuple(params),
)
- return [dict(r) for r in rows]
-
-
-def week_range() -> tuple[str, str]:
- today = date.today()
- start = today - timedelta(days=today.weekday())
- return start.isoformat(), today.isoformat()
+ apps = _visible(rows)
+ if search:
+ q = search.strip().lower()
+ apps = [a for a in apps if q in a["name"].lower() or q in a["exe_name"]]
+ return apps[:limit] if limit else apps
-def weekly_totals(limit: int = 20) -> list[dict]:
- s, e = week_range()
- return top_apps_range(s, e, limit)
+def total_ms(start_day: str, end_day: str) -> int:
+ return sum(a["focused_ms"] for a in top_apps(start_day, end_day, limit=None))
-def daily_totals_range(start_day: str, end_day: str) -> list[dict]:
- """Total focused_ms per day (for calendar heatmap)."""
+def daily_totals(start_day: str, end_day: str) -> dict[str, int]:
+ """Focused milliseconds per day for an inclusive range (days without data omitted)."""
rows = db.fetchall(
- "SELECT day, SUM(focused_ms) AS total_ms FROM daily_rollup "
- "WHERE day BETWEEN ? AND ? GROUP BY day ORDER BY day",
+ "SELECT r.day, a.exe_name, SUM(r.focused_ms) AS ms FROM daily_rollup r "
+ "JOIN apps a ON a.app_id = r.app_id WHERE r.day BETWEEN ? AND ? AND a.is_hidden = 0 "
+ "GROUP BY r.day, a.exe_name",
(start_day, end_day),
)
- return [dict(r) for r in rows]
-
-
-def day_breakdown(day: str) -> list[dict]:
- rows = db.fetchall(
- "SELECT a.app_id, a.exe_name, a.display_name, a.icon_path, "
- " r.focused_ms, r.opens_count, r.clicks_count "
- "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id "
- "WHERE r.day = ? ORDER BY r.focused_ms DESC",
- (day,),
+ totals: dict[str, int] = {}
+ for r in rows:
+ if r["ms"] and catalog.is_listable(r["exe_name"]):
+ totals[r["day"]] = totals.get(r["day"], 0) + r["ms"]
+ return totals
+
+
+def hourly_totals(day: str, app_id: int | None = None) -> list[int]:
+ """Focused milliseconds for each hour (0-23) of *day*, built from sessions."""
+ d = date.fromisoformat(day)
+ start = datetime.combine(d, datetime.min.time()).timestamp()
+ end = datetime.combine(d + timedelta(days=1), datetime.min.time()).timestamp()
+ sql = (
+ "SELECT s.start_ts, s.end_ts, a.exe_name FROM usage_sessions s JOIN apps a ON a.app_id = s.app_id "
+ "WHERE s.end_ts > ? AND s.start_ts < ? AND a.is_hidden = 0"
)
- return [dict(r) for r in rows]
+ params: tuple = (start, end)
+ if app_id is not None:
+ sql += " AND s.app_id = ?"
+ params += (app_id,)
+ hours = [0] * 24
+ for s in db.fetchall(sql, params):
+ if not catalog.is_listable(s["exe_name"]):
+ continue
+ for hour_dt, ms in split_by_hour(max(s["start_ts"], start), min(s["end_ts"], end)):
+ hours[hour_dt.hour] += ms
+ return hours
def app_daily_history(app_id: int, days: int = 30) -> list[dict]:
- start = (date.today() - timedelta(days=days)).isoformat()
+ """One entry per day for the last *days* days (including today), zero-filled."""
+ start = date.today() - timedelta(days=days - 1)
rows = db.fetchall(
- "SELECT day, focused_ms, opens_count, clicks_count FROM daily_rollup "
- "WHERE app_id = ? AND day >= ? ORDER BY day",
- (app_id, start),
+ "SELECT day, focused_ms, opens_count, clicks_count FROM daily_rollup WHERE app_id = ? AND day >= ?",
+ (app_id, start.isoformat()),
)
- return [dict(r) for r in rows]
+ by_day = {r["day"]: dict(r) for r in rows}
+ history = []
+ for i in range(days):
+ d = (start + timedelta(days=i)).isoformat()
+ history.append(by_day.get(d, {"day": d, "focused_ms": 0, "opens_count": 0, "clicks_count": 0}))
+ return history
-def most_used(days: int = 7, limit: int = 20) -> list[dict]:
- start = (date.today() - timedelta(days=days)).isoformat()
- return top_apps_range(start, today_str(), limit)
+def app_summary(app_id: int) -> dict:
+ row = db.fetchone(
+ "SELECT MIN(day) AS first_day, MAX(CASE WHEN focused_ms > 0 THEN day END) AS last_day, "
+ "COALESCE(SUM(focused_ms), 0) AS total_ms, "
+ "COUNT(CASE WHEN focused_ms > 0 THEN 1 END) AS active_days "
+ "FROM daily_rollup WHERE app_id = ?",
+ (app_id,),
+ )
+ longest = db.fetchone("SELECT COALESCE(MAX(duration_ms), 0) AS ms FROM usage_sessions WHERE app_id = ?", (app_id,))
+ summary = dict(row) if row else {"first_day": None, "last_day": None, "total_ms": 0, "active_days": 0}
+ summary["longest_session_ms"] = longest["ms"] if longest else 0
+ return summary
-def least_used(days: int = 7, limit: int = 20) -> list[dict]:
- start = (date.today() - timedelta(days=days)).isoformat()
+def recent_sessions(app_id: int, limit: int = 25, min_ms: int = 1000) -> list[dict]:
rows = db.fetchall(
- "SELECT a.app_id, a.exe_name, a.display_name, a.icon_path, a.is_favorite, "
- " SUM(r.focused_ms) AS focused_ms, SUM(r.opens_count) AS opens_count "
- "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id "
- "WHERE r.day BETWEEN ? AND ? GROUP BY a.app_id ORDER BY focused_ms ASC LIMIT ?",
- (start, today_str(), limit),
+ "SELECT session_id, start_ts, end_ts, duration_ms, was_idle FROM usage_sessions "
+ "WHERE app_id = ? AND duration_ms >= ? ORDER BY start_ts DESC LIMIT ?",
+ (app_id, min_ms, limit),
)
return [dict(r) for r in rows]
-def most_opened(days: int = 7, limit: int = 20) -> list[dict]:
- start = (date.today() - timedelta(days=days)).isoformat()
- rows = db.fetchall(
- "SELECT a.app_id, a.exe_name, a.display_name, a.icon_path, a.is_favorite, "
- " SUM(r.opens_count) AS opens_count, SUM(r.focused_ms) AS focused_ms "
- "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id "
- "WHERE r.day BETWEEN ? AND ? GROUP BY a.app_id ORDER BY opens_count DESC LIMIT ?",
- (start, today_str(), limit),
- )
- return [dict(r) for r in rows]
+def app_usage_on(day: str, app_id: int) -> int:
+ row = db.fetchone("SELECT focused_ms FROM daily_rollup WHERE day = ? AND app_id = ?", (day, app_id))
+ return row["focused_ms"] if row else 0
-def most_clicked(days: int = 7, limit: int = 20) -> list[dict]:
- start = (date.today() - timedelta(days=days)).isoformat()
- rows = db.fetchall(
- "SELECT a.app_id, a.exe_name, a.display_name, a.icon_path, a.is_favorite, "
- " SUM(r.clicks_count) AS clicks_count, SUM(r.focused_ms) AS focused_ms "
- "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id "
- "WHERE r.day BETWEEN ? AND ? AND r.clicks_count > 0 "
- "GROUP BY a.app_id ORDER BY clicks_count DESC LIMIT ?",
- (start, today_str(), limit),
- )
- return [dict(r) for r in rows]
+def first_tracked_day() -> str | None:
+ row = db.fetchone("SELECT MIN(day) AS d FROM daily_rollup WHERE focused_ms > 0")
+ return row["d"] if row else None
diff --git a/apptrackr/data/rollup.py b/apptrackr/data/rollup.py
deleted file mode 100644
index 018026e..0000000
--- a/apptrackr/data/rollup.py
+++ /dev/null
@@ -1,30 +0,0 @@
-"""Rollup engine – builds daily aggregates from raw sessions."""
-
-from __future__ import annotations
-
-import time
-from datetime import date, datetime
-
-from . import db, queries
-
-
-def rollup_session(session_id: int) -> None:
- """Add a completed session's duration into the daily_rollup table."""
- row = db.fetchone(
- "SELECT app_id, start_ts, duration_ms, was_idle FROM usage_sessions WHERE session_id = ?",
- (session_id,),
- )
- if not row or row["duration_ms"] is None:
- return
- if row["was_idle"]:
- return # Don't count idle time
- day = datetime.fromtimestamp(row["start_ts"]).date().isoformat()
- queries.add_focused_time(day, row["app_id"], row["duration_ms"])
-
-
-def flush_current_session(app_id: int, session_id: int, now: float | None = None) -> int:
- """End the current session and roll it up. Returns new session_id."""
- now = now or time.time()
- queries.end_session(session_id, now)
- rollup_session(session_id)
- return queries.start_session(app_id, now)
diff --git a/apptrackr/data/schema.sql b/apptrackr/data/schema.sql
index 26d548c..0af2b20 100644
--- a/apptrackr/data/schema.sql
+++ b/apptrackr/data/schema.sql
@@ -1,12 +1,16 @@
--- AppTrackr database schema
+-- AppTrackr database schema (latest). Older databases are upgraded by the
+-- migrations in db.py, so only add statements here that are safe to run
+-- against a v1.0 database.
CREATE TABLE IF NOT EXISTS 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
+ 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,
+ is_hidden INTEGER NOT NULL DEFAULT 0,
+ daily_limit_ms INTEGER
);
CREATE TABLE IF NOT EXISTS usage_sessions (
@@ -21,14 +25,16 @@ CREATE INDEX IF NOT EXISTS idx_sessions_app ON usage_sessions(app_id);
CREATE INDEX IF NOT EXISTS idx_sessions_start ON usage_sessions(start_ts);
CREATE TABLE IF NOT EXISTS 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,
+ 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)
);
+CREATE INDEX IF NOT EXISTS idx_rollup_app ON daily_rollup(app_id, day);
+-- Kept for compatibility with v1.0 databases; no longer written.
CREATE TABLE IF NOT EXISTS focus_events (
event_id INTEGER PRIMARY KEY AUTOINCREMENT,
ts REAL NOT NULL,
@@ -37,7 +43,7 @@ CREATE TABLE IF NOT EXISTS focus_events (
event_type TEXT
);
--- Rewards tables
+-- Rewards
CREATE TABLE IF NOT EXISTS reward_rules (
rule_id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id INTEGER REFERENCES apps(app_id),
@@ -72,21 +78,19 @@ CREATE TABLE IF NOT EXISTS village_state (
state_json TEXT NOT NULL DEFAULT '{}'
);
--- Settings
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
--- Insert defaults
INSERT OR IGNORE INTO player_profile (profile_id) VALUES (1);
INSERT OR IGNORE INTO village_state (profile_id, state_json)
VALUES (1, '{"buildings":{},"villagers":0,"inventory":{"wood":0,"stone":0,"metal":0,"food":0,"blueprints":0}}');
INSERT OR IGNORE INTO settings (key, value) VALUES
('idle_threshold_sec', '300'),
- ('track_window_titles', '0'),
('track_clicks', '0'),
- ('autostart', '0'),
('minimize_to_tray', '1'),
('rewards_enabled', '1'),
+ ('notifications_enabled', '1'),
+ ('auto_update_check', '1'),
('polling_hz', '4');
diff --git a/apptrackr/data/spans.py b/apptrackr/data/spans.py
new file mode 100644
index 0000000..9465fe3
--- /dev/null
+++ b/apptrackr/data/spans.py
@@ -0,0 +1,37 @@
+"""Helpers for splitting time spans at local midnight."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from datetime import time as dtime
+
+
+def split_by_day(start_ts: float, end_ts: float) -> list[tuple[str, int]]:
+ """Split [start_ts, end_ts) into (YYYY-MM-DD, milliseconds) parts per local day."""
+ parts: list[tuple[str, int]] = []
+ if end_ts <= start_ts:
+ return parts
+ cursor = start_ts
+ while cursor < end_ts:
+ day = datetime.fromtimestamp(cursor).date()
+ next_midnight = datetime.combine(day + timedelta(days=1), dtime.min).timestamp()
+ stop = min(end_ts, next_midnight)
+ ms = int(round((stop - cursor) * 1000))
+ if ms > 0:
+ parts.append((day.isoformat(), ms))
+ cursor = stop
+ return parts
+
+
+def split_by_hour(start_ts: float, end_ts: float) -> list[tuple[datetime, int]]:
+ """Split a span into (local hour start, milliseconds) parts."""
+ parts: list[tuple[datetime, int]] = []
+ cursor = start_ts
+ while cursor < end_ts:
+ dt = datetime.fromtimestamp(cursor).replace(minute=0, second=0, microsecond=0)
+ stop = min(end_ts, (dt + timedelta(hours=1)).timestamp())
+ ms = int(round((stop - cursor) * 1000))
+ if ms > 0:
+ parts.append((dt, ms))
+ cursor = stop
+ return parts
diff --git a/apptrackr/game/economy.py b/apptrackr/game/economy.py
index ca8a083..99d085d 100644
--- a/apptrackr/game/economy.py
+++ b/apptrackr/game/economy.py
@@ -1,13 +1,45 @@
-"""Economy / balance tables for the Neon Village."""
+"""Balance values for rewards and the village."""
-# XP required per level (cumulative, so level N needs LEVEL_XP[N] total)
-def xp_for_level(level: int) -> int:
- return level * 100
+from __future__ import annotations
+
+XP_PER_LEVEL = 100
+CREDITS_PER_LEVEL = 10 # granted per level reached, times the level number
+
+RESOURCES = ("wood", "stone", "metal", "food", "blueprints")
+BASE_RESOURCE_CAP = 100
+STORAGE_CAP_PER_LEVEL = 50
+
+WORKSHOP_XP_PCT = 5 # bonus XP per workshop level
+LAB_RESOURCE_PCT = 10 # bonus resources per lab level
+TAVERN_STREAK_PCT = 10 # bonus streak rewards per tavern level
+
+STREAK_GOAL_MS = 30 * 60 * 1000 # favorite-app time needed for a streak day
-# Streak reward tiers
STREAK_REWARDS = {
- 3: {"xp": 20, "wood": 10, "food": 5},
- 7: {"xp": 50, "stone": 15, "metal": 5},
+ 3: {"xp": 20, "wood": 10, "food": 5},
+ 7: {"xp": 50, "stone": 15, "metal": 5},
14: {"xp": 100, "metal": 20, "blueprints": 1},
30: {"xp": 250, "blueprints": 2, "credits": 50},
}
+
+# Credits needed to buy a bundle of resources at the market.
+MARKET = {
+ "wood": (10, 5),
+ "food": (10, 5),
+ "stone": (10, 8),
+ "metal": (5, 10),
+ "blueprints": (1, 40),
+}
+
+
+def level_for_xp(xp: int) -> int:
+ return 1 + max(0, xp) // XP_PER_LEVEL
+
+
+def level_progress(xp: int) -> tuple[int, int]:
+ """(XP earned inside the current level, XP the level requires)."""
+ return max(0, xp) % XP_PER_LEVEL, XP_PER_LEVEL
+
+
+def resource_cap(storage_level: int) -> int:
+ return BASE_RESOURCE_CAP + STORAGE_CAP_PER_LEVEL * storage_level
diff --git a/apptrackr/game/state.py b/apptrackr/game/state.py
index df250b0..b2d6cbd 100644
--- a/apptrackr/game/state.py
+++ b/apptrackr/game/state.py
@@ -1,115 +1,152 @@
-"""Neon Village game state and economy."""
+"""Village: buildings, inventory and the credit market."""
from __future__ import annotations
import json
from ..data import db
+from . import economy
-# Building definitions: name → {cost, unlock_level, bonus_description}
BUILDINGS = {
- "workshop": {"wood": 20, "stone": 10, "unlock_level": 1, "max_level": 5,
- "desc": "Produces bonus XP (+5% per level)"},
- "storage": {"wood": 15, "stone": 15, "unlock_level": 1, "max_level": 5,
- "desc": "Increases resource cap (+50 per level)"},
- "house": {"wood": 25, "food": 10, "unlock_level": 2, "max_level": 5,
- "desc": "Adds +1 villager per level"},
- "lab": {"stone": 20, "metal": 15, "blueprints": 1, "unlock_level": 3, "max_level": 3,
- "desc": "Unlocks advanced reward tiers"},
- "tavern": {"wood": 30, "food": 20, "unlock_level": 4, "max_level": 3,
- "desc": "Streak bonuses +10% per level"},
- "monument": {"stone": 50, "metal": 30, "blueprints": 3, "unlock_level": 5, "max_level": 1,
- "desc": "Prestige! Cosmetic crown effect"},
+ "workshop": {
+ "wood": 20,
+ "stone": 10,
+ "unlock_level": 1,
+ "max_level": 5,
+ "desc": f"+{economy.WORKSHOP_XP_PCT}% XP from rewards per level",
+ },
+ "storage": {
+ "wood": 15,
+ "stone": 15,
+ "unlock_level": 1,
+ "max_level": 5,
+ "desc": f"+{economy.STORAGE_CAP_PER_LEVEL} resource capacity per level",
+ },
+ "house": {"wood": 25, "food": 10, "unlock_level": 2, "max_level": 5, "desc": "+1 villager per level"},
+ "lab": {
+ "stone": 20,
+ "metal": 15,
+ "blueprints": 1,
+ "unlock_level": 3,
+ "max_level": 3,
+ "desc": f"+{economy.LAB_RESOURCE_PCT}% resources from rewards per level",
+ },
+ "tavern": {
+ "wood": 30,
+ "food": 20,
+ "unlock_level": 4,
+ "max_level": 3,
+ "desc": f"+{economy.TAVERN_STREAK_PCT}% streak rewards per level",
+ },
+ "monument": {
+ "stone": 50,
+ "metal": 30,
+ "blueprints": 3,
+ "unlock_level": 5,
+ "max_level": 1,
+ "desc": "Prestige crown on your profile",
+ },
}
def get_village() -> dict:
row = db.fetchone("SELECT state_json FROM village_state WHERE profile_id = 1")
- if row:
- return json.loads(row["state_json"])
- return {"buildings": {}, "villagers": 0, "inventory": {
- "wood": 0, "stone": 0, "metal": 0, "food": 0, "blueprints": 0
- }}
+ state = json.loads(row["state_json"]) if row else {}
+ state.setdefault("buildings", {})
+ state.setdefault("villagers", 0)
+ inv = state.setdefault("inventory", {})
+ for r in economy.RESOURCES:
+ inv.setdefault(r, 0)
+ return state
-def _save_village(state: dict) -> None:
- db.execute("UPDATE village_state SET state_json = ? WHERE profile_id = 1",
- (json.dumps(state),))
- db.commit()
+def save_village(state: dict) -> None:
+ db.execute("UPDATE village_state SET state_json = ? WHERE profile_id = 1", (json.dumps(state),))
-def can_build(building_name: str) -> tuple[bool, str]:
- """Check if player can build/upgrade a building. Returns (ok, reason)."""
- if building_name not in BUILDINGS:
- return False, "Unknown building"
+def building_level(village: dict, name: str) -> int:
+ return int(village.get("buildings", {}).get(name, {}).get("level", 0))
- spec = BUILDINGS[building_name]
- profile = db.fetchone("SELECT level FROM player_profile WHERE profile_id = 1")
- if not profile or profile["level"] < spec["unlock_level"]:
- return False, f"Requires player level {spec['unlock_level']}"
- village = get_village()
- current_level = village["buildings"].get(building_name, {}).get("level", 0)
- if current_level >= spec["max_level"]:
- return False, "Already at max level"
+def resource_cap(village: dict | None = None) -> int:
+ village = village or get_village()
+ return economy.resource_cap(building_level(village, "storage"))
+
- inv = village.get("inventory", {})
- cost_mult = current_level + 1 # Cost scales with level
- for resource in ("wood", "stone", "metal", "food", "blueprints"):
- needed = spec.get(resource, 0) * cost_mult
- if inv.get(resource, 0) < needed:
- return False, f"Not enough {resource} (need {needed}, have {inv.get(resource, 0)})"
+def build_cost(name: str, current_level: int) -> dict[str, int]:
+ spec = BUILDINGS[name]
+ mult = current_level + 1
+ return {r: spec[r] * mult for r in economy.RESOURCES if spec.get(r)}
- return True, "OK"
+def _player_level() -> int:
+ row = db.fetchone("SELECT level FROM player_profile WHERE profile_id = 1")
+ return row["level"] if row else 1
-def build_or_upgrade(building_name: str) -> tuple[bool, str]:
- """Attempt to build or upgrade a building. Returns (success, message)."""
- ok, reason = can_build(building_name)
+
+def can_build(name: str) -> tuple[bool, str]:
+ """Check whether a building can be built or upgraded. Returns (ok, reason)."""
+ if name not in BUILDINGS:
+ return False, "Unknown building"
+ spec = BUILDINGS[name]
+ if _player_level() < spec["unlock_level"]:
+ return False, f"Unlocks at level {spec['unlock_level']}"
+ village = get_village()
+ level = building_level(village, name)
+ if level >= spec["max_level"]:
+ return False, "Max level"
+ inv = village["inventory"]
+ missing = [f"{need - inv.get(r, 0)} {r}" for r, need in build_cost(name, level).items() if inv.get(r, 0) < need]
+ if missing:
+ return False, "Need " + ", ".join(missing)
+ return True, "Ready"
+
+
+def build_or_upgrade(name: str) -> tuple[bool, str]:
+ ok, reason = can_build(name)
if not ok:
return False, reason
-
- spec = BUILDINGS[building_name]
village = get_village()
- current_level = village["buildings"].get(building_name, {}).get("level", 0)
- cost_mult = current_level + 1
-
- # Deduct resources
- inv = village.get("inventory", {})
- for resource in ("wood", "stone", "metal", "food", "blueprints"):
- needed = spec.get(resource, 0) * cost_mult
- if needed > 0:
- inv[resource] = inv.get(resource, 0) - needed
-
- # Upgrade building
- village["buildings"][building_name] = {"level": current_level + 1}
-
- # House gives villagers
- if building_name == "house":
+ level = building_level(village, name)
+ for r, need in build_cost(name, level).items():
+ village["inventory"][r] -= need
+ village["buildings"][name] = {"level": level + 1}
+ if name == "house":
village["villagers"] = village.get("villagers", 0) + 1
-
- village["inventory"] = inv
- _save_village(village)
- return True, f"{building_name.title()} upgraded to level {current_level + 1}!"
+ save_village(village)
+ db.commit()
+ verb = "built" if level == 0 else f"upgraded to level {level + 1}"
+ return True, f"{name.title()} {verb}"
+
+
+def buy(resource: str) -> tuple[bool, str]:
+ """Spend credits on a bundle of *resource* at the market."""
+ if resource not in economy.MARKET:
+ return False, "Not for sale"
+ amount, price = economy.MARKET[resource]
+ profile = db.fetchone("SELECT credits FROM player_profile WHERE profile_id = 1")
+ credits = profile["credits"] if profile else 0
+ if credits < price:
+ return False, f"Need {price - credits} more credits"
+ village = get_village()
+ cap = resource_cap(village)
+ have = village["inventory"].get(resource, 0)
+ if have >= cap:
+ return False, f"{resource.title()} storage is full"
+ village["inventory"][resource] = min(cap, have + amount)
+ save_village(village)
+ db.execute("UPDATE player_profile SET credits = credits - ? WHERE profile_id = 1", (price,))
+ db.commit()
+ return True, f"Bought {amount} {resource}"
def get_bonuses() -> dict:
- """Calculate active bonuses from buildings."""
village = get_village()
- buildings = village.get("buildings", {})
- bonuses = {
- "xp_bonus_pct": 0,
- "resource_cap_bonus": 0,
- "streak_bonus_pct": 0,
+ return {
+ "xp_bonus_pct": building_level(village, "workshop") * economy.WORKSHOP_XP_PCT,
+ "resource_bonus_pct": building_level(village, "lab") * economy.LAB_RESOURCE_PCT,
+ "streak_bonus_pct": building_level(village, "tavern") * economy.TAVERN_STREAK_PCT,
+ "resource_cap": resource_cap(village),
"villagers": village.get("villagers", 0),
- "has_monument": False,
+ "has_monument": building_level(village, "monument") >= 1,
}
- if "workshop" in buildings:
- bonuses["xp_bonus_pct"] = buildings["workshop"].get("level", 0) * 5
- if "storage" in buildings:
- bonuses["resource_cap_bonus"] = buildings["storage"].get("level", 0) * 50
- if "tavern" in buildings:
- bonuses["streak_bonus_pct"] = buildings["tavern"].get("level", 0) * 10
- if "monument" in buildings:
- bonuses["has_monument"] = buildings["monument"].get("level", 0) >= 1
- return bonuses
diff --git a/apptrackr/packaging/__init__.py b/apptrackr/packaging/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/apptrackr/paths.py b/apptrackr/paths.py
new file mode 100644
index 0000000..3429e89
--- /dev/null
+++ b/apptrackr/paths.py
@@ -0,0 +1,46 @@
+"""Filesystem locations for AppTrackr data, logs and bundled assets."""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+
+_override: Path | None = None
+
+
+def set_data_dir(path: str | os.PathLike[str] | None) -> None:
+ """Override the data directory (used by --data-dir, --demo and tests)."""
+ global _override
+ _override = Path(path) if path else None
+
+
+def data_dir() -> Path:
+ """Directory holding the database, logs and other per-user state."""
+ if _override is not None:
+ return _override
+ env = os.environ.get("APPTRACKR_DATA_DIR", "").strip()
+ if env:
+ return Path(env)
+ if sys.platform.startswith("win"):
+ return Path(os.environ.get("APPDATA") or Path.home()) / "AppTrackr"
+ if sys.platform == "darwin":
+ return Path.home() / "Library" / "Application Support" / "AppTrackr"
+ xdg = os.environ.get("XDG_DATA_HOME")
+ return (Path(xdg) if xdg else Path.home() / ".local" / "share") / "apptrackr"
+
+
+def db_path() -> Path:
+ return data_dir() / "data.sqlite"
+
+
+def log_dir() -> Path:
+ return data_dir() / "logs"
+
+
+def assets_dir() -> Path:
+ """Bundled assets, resolved for both source checkouts and PyInstaller builds."""
+ base = getattr(sys, "_MEIPASS", None)
+ if base:
+ return Path(base) / "apptrackr" / "assets"
+ return Path(__file__).with_name("assets")
diff --git a/apptrackr/rewards/engine.py b/apptrackr/rewards/engine.py
index 3946961..0726b23 100644
--- a/apptrackr/rewards/engine.py
+++ b/apptrackr/rewards/engine.py
@@ -1,4 +1,4 @@
-"""Reward evaluation engine – checks milestones and issues rewards."""
+"""Reward evaluation: milestones per app, claiming, levels and streaks."""
from __future__ import annotations
@@ -7,160 +7,270 @@
import time
from datetime import date, timedelta
-from ..data import db
+from ..data import catalog, db
+from ..game import economy
+from ..game import state as game_state
log = logging.getLogger(__name__)
+def enabled() -> bool:
+ return db.get_bool("rewards_enabled", True)
+
+
def evaluate(day: str | None = None) -> list[dict]:
- """Evaluate all enabled rules against the rollup for *day*. Returns newly granted rewards."""
- day = day or date.today().isoformat()
- if db.get_setting("rewards_enabled", "1") != "1":
+ """Grant rewards for milestones reached on *day*. Returns the new grants."""
+ if not enabled():
return []
-
- rules = db.fetchall("SELECT * FROM reward_rules WHERE enabled = 1")
+ day = day or date.today().isoformat()
granted: list[dict] = []
-
+ rules = db.fetchall(
+ "SELECT r.* FROM reward_rules r JOIN apps a ON a.app_id = r.app_id WHERE r.enabled = 1 AND a.is_hidden = 0"
+ )
for rule in rules:
- app_id = rule["app_id"]
metric = rule["metric"]
- threshold = rule["threshold"]
-
- # Get current metric value from rollup
+ if metric not in ("focused_ms", "opens_count", "clicks_count"):
+ continue
row = db.fetchone(
- f"SELECT COALESCE({metric}, 0) AS val FROM daily_rollup WHERE day = ? AND app_id = ?",
- (day, app_id),
+ f"SELECT {metric} AS val FROM daily_rollup WHERE day = ? AND app_id = ?",
+ (day, rule["app_id"]),
)
- if not row:
- continue
- current_val = row["val"]
- if current_val < threshold:
+ value = row["val"] if row else 0
+ if value < rule["threshold"]:
continue
-
- # Check if already granted today for this rule
if rule["repeatable"]:
- # For repeatable rules, count how many times threshold has been crossed
- times_earned = current_val // threshold
- times_granted = db.fetchone(
- "SELECT COUNT(*) AS cnt FROM reward_events WHERE rule_id = ? AND day = ?",
+ earned = value // rule["threshold"]
+ done = db.fetchone(
+ "SELECT COUNT(*) AS n FROM reward_events WHERE rule_id = ? AND day = ?",
(rule["rule_id"], day),
- )
- already = times_granted["cnt"] if times_granted else 0
- times_to_grant = times_earned - already
+ )["n"]
+ count = earned - done
else:
- existing = db.fetchone(
- "SELECT 1 FROM reward_events WHERE rule_id = ? AND app_id = ?",
- (rule["rule_id"], app_id),
- )
- if existing:
- continue
- times_to_grant = 1
-
- reward_json = rule["reward_json"]
- for _ in range(max(0, times_to_grant)):
+ exists = db.fetchone("SELECT 1 FROM reward_events WHERE rule_id = ?", (rule["rule_id"],))
+ count = 0 if exists else 1
+ for _ in range(max(0, count)):
db.execute(
"INSERT INTO reward_events (ts, app_id, rule_id, day, granted_json) VALUES (?, ?, ?, ?, ?)",
- (time.time(), app_id, rule["rule_id"], day, reward_json),
+ (time.time(), rule["app_id"], rule["rule_id"], day, rule["reward_json"]),
+ )
+ granted.append(
+ {"app_id": rule["app_id"], "rule_id": rule["rule_id"], "reward": json.loads(rule["reward_json"])}
)
- granted.append({"app_id": app_id, "rule_id": rule["rule_id"], "reward": json.loads(reward_json)})
-
if granted:
db.commit()
log.info("Granted %d reward(s) for %s", len(granted), day)
return granted
+def evaluate_recent() -> list[dict]:
+ """Evaluate today and yesterday, so milestones hit just before midnight are kept."""
+ yesterday = (date.today() - timedelta(days=1)).isoformat()
+ return evaluate(yesterday) + evaluate()
+
+
def unclaimed_rewards() -> list[dict]:
rows = db.fetchall(
- "SELECT re.*, a.display_name, a.exe_name FROM reward_events re "
- "JOIN apps a ON a.app_id = re.app_id WHERE re.claimed = 0 ORDER BY re.ts DESC"
+ "SELECT re.*, a.display_name, a.exe_name, r.metric, r.threshold FROM reward_events re "
+ "JOIN apps a ON a.app_id = re.app_id JOIN reward_rules r ON r.rule_id = re.rule_id "
+ "WHERE re.claimed = 0 ORDER BY re.ts DESC"
)
- return [dict(r) for r in rows]
+ out = []
+ for r in rows:
+ item = dict(r)
+ item["name"] = catalog.display_name(item)
+ item["reward"] = json.loads(item["granted_json"])
+ out.append(item)
+ return out
+
+
+def unclaimed_by_app() -> list[dict]:
+ """Pending rewards grouped per app, with summed amounts."""
+ groups: dict[int, dict] = {}
+ for item in unclaimed_rewards():
+ group = groups.setdefault(
+ item["app_id"],
+ {
+ "app_id": item["app_id"],
+ "name": item["name"],
+ "exe_name": item["exe_name"],
+ "event_ids": [],
+ "reward": {},
+ },
+ )
+ group["event_ids"].append(item["event_id"])
+ for key, value in item["reward"].items():
+ group["reward"][key] = group["reward"].get(key, 0) + value
+ return sorted(groups.values(), key=lambda g: -len(g["event_ids"]))
+
+
+def unclaimed_count() -> int:
+ row = db.fetchone("SELECT COUNT(*) AS n FROM reward_events WHERE claimed = 0")
+ return row["n"] if row else 0
+
+
+def _apply(reward: dict, bonus_pct: int = 0) -> dict:
+ """Add a reward to the profile and village. Returns what was actually applied."""
+ bonuses = game_state.get_bonuses()
+ applied: dict = {}
+
+ xp = int(reward.get("xp", 0))
+ if xp:
+ xp = round(xp * (100 + bonuses["xp_bonus_pct"] + bonus_pct) / 100)
+ applied["xp"] = xp
+
+ village = game_state.get_village()
+ cap = game_state.resource_cap(village)
+ inv = village["inventory"]
+ for res in economy.RESOURCES:
+ amount = int(reward.get(res, 0))
+ if not amount:
+ continue
+ amount = round(amount * (100 + bonuses["resource_bonus_pct"] + bonus_pct) / 100)
+ before = inv.get(res, 0)
+ inv[res] = max(before, min(cap, before + amount))
+ if inv[res] > before:
+ applied[res] = inv[res] - before
+ game_state.save_village(village)
+
+ profile = get_profile()
+ credits = int(reward.get("credits", 0))
+ new_xp = profile["xp"] + xp
+ new_level = max(profile["level"], economy.level_for_xp(new_xp))
+ for lvl in range(profile["level"] + 1, new_level + 1):
+ credits += economy.CREDITS_PER_LEVEL * lvl
+ if new_level > profile["level"]:
+ applied["level_up"] = new_level
+ if credits:
+ applied["credits"] = credits
+ db.execute(
+ "UPDATE player_profile SET xp = ?, level = ?, credits = credits + ? WHERE profile_id = 1",
+ (new_xp, new_level, credits),
+ )
+ return applied
def claim_reward(event_id: int) -> dict | None:
- """Claim a reward event and apply it to the player profile."""
row = db.fetchone("SELECT * FROM reward_events WHERE event_id = ? AND claimed = 0", (event_id,))
if not row:
return None
-
- reward = json.loads(row["granted_json"])
-
- # Apply XP/credits
- if "xp" in reward:
- db.execute("UPDATE player_profile SET xp = xp + ? WHERE profile_id = 1", (reward["xp"],))
- # Level up every 100 XP
- profile = db.fetchone("SELECT xp, level FROM player_profile WHERE profile_id = 1")
- if profile:
- new_level = 1 + profile["xp"] // 100
- if new_level > profile["level"]:
- db.execute("UPDATE player_profile SET level = ? WHERE profile_id = 1", (new_level,))
-
- if "credits" in reward:
- db.execute("UPDATE player_profile SET credits = credits + ? WHERE profile_id = 1", (reward["credits"],))
-
- # Apply resources to village inventory
- resource_keys = {"wood", "stone", "metal", "food", "blueprints"}
- village = db.fetchone("SELECT state_json FROM village_state WHERE profile_id = 1")
- if village:
- state = json.loads(village["state_json"])
- inv = state.get("inventory", {})
- for key in resource_keys:
- if key in reward:
- inv[key] = inv.get(key, 0) + reward[key]
- state["inventory"] = inv
- db.execute("UPDATE village_state SET state_json = ? WHERE profile_id = 1", (json.dumps(state),))
-
+ applied = _apply(json.loads(row["granted_json"]))
db.execute("UPDATE reward_events SET claimed = 1 WHERE event_id = ?", (event_id,))
db.commit()
- return reward
+ return applied
-def claim_all() -> list[dict]:
- unclaimed = unclaimed_rewards()
- results = []
- for r in unclaimed:
- result = claim_reward(r["event_id"])
- if result:
- results.append(result)
- return results
+def claim_many(event_ids: list[int] | None = None) -> dict:
+ """Claim the given pending rewards (all when None). Returns the summed amounts applied."""
+ if event_ids is None:
+ event_ids = [item["event_id"] for item in unclaimed_rewards()]
+ total: dict = {}
+ for event_id in event_ids:
+ applied = claim_reward(event_id) or {}
+ for key, value in applied.items():
+ if key == "level_up":
+ total[key] = max(total.get(key, 0), value)
+ else:
+ total[key] = total.get(key, 0) + value
+ return total
-def update_streak() -> int:
- """Update daily streak. Call once per day. Returns new streak count."""
- today = date.today().isoformat()
- yesterday = (date.today() - timedelta(days=1)).isoformat()
+# ---------------------------------------------------------------------------
+# Profile and streaks
+# ---------------------------------------------------------------------------
- profile = db.fetchone("SELECT * FROM player_profile WHERE profile_id = 1")
- if not profile:
+
+def get_profile() -> dict:
+ row = db.fetchone("SELECT * FROM player_profile WHERE profile_id = 1")
+ profile = dict(row) if row else {"xp": 0, "level": 1, "credits": 0, "streak_days": 0, "last_streak_day": None}
+ profile["streak"] = current_streak(profile)
+ return profile
+
+
+def current_streak(profile: dict) -> int:
+ """Streak length as of today: a streak survives until a full day is missed."""
+ last = profile.get("last_streak_day")
+ if not last:
return 0
+ today = date.today()
+ if last in (today.isoformat(), (today - timedelta(days=1)).isoformat()):
+ return int(profile.get("streak_days") or 0)
+ return 0
- if profile["last_streak_day"] == today:
- return profile["streak_days"]
- # Check if user tracked any favorite app for 30+ min today
+def favorites_ms(day: str) -> int:
row = db.fetchone(
- "SELECT COALESCE(SUM(r.focused_ms), 0) AS total "
- "FROM daily_rollup r JOIN apps a ON a.app_id = r.app_id "
- "WHERE r.day = ? AND a.is_favorite = 1",
- (today,),
+ "SELECT COALESCE(SUM(r.focused_ms), 0) AS total FROM daily_rollup r "
+ "JOIN apps a ON a.app_id = r.app_id WHERE r.day = ? AND a.is_favorite = 1 AND a.is_hidden = 0",
+ (day,),
)
- if not row or row["total"] < 30 * 60 * 1000:
- return profile["streak_days"]
+ return row["total"] if row else 0
+
- if profile["last_streak_day"] == yesterday:
- new_streak = profile["streak_days"] + 1
- else:
- new_streak = 1
+def update_streak(extra_ms: int = 0) -> dict | None:
+ """Extend the streak once today's favorite-app goal is met.
+ Returns {"streak": n, "reward": {...}} when the streak grew, else None.
+ """
+ today = date.today().isoformat()
+ profile = get_profile()
+ if profile.get("last_streak_day") == today:
+ return None
+ if favorites_ms(today) + extra_ms < economy.STREAK_GOAL_MS:
+ return None
+ streak = profile["streak"] + 1
db.execute(
"UPDATE player_profile SET streak_days = ?, last_streak_day = ? WHERE profile_id = 1",
- (new_streak, today),
+ (streak, today),
)
+ result: dict = {"streak": streak}
+ tier = economy.STREAK_REWARDS.get(streak)
+ if tier and enabled():
+ bonus = game_state.get_bonuses()["streak_bonus_pct"]
+ result["reward"] = _apply(tier, bonus_pct=bonus)
db.commit()
- return new_streak
+ return result
-def get_profile() -> dict:
- row = db.fetchone("SELECT * FROM player_profile WHERE profile_id = 1")
- return dict(row) if row else {}
+# ---------------------------------------------------------------------------
+# Progress toward the next milestone
+# ---------------------------------------------------------------------------
+
+
+def next_milestones(day: str | None = None) -> list[dict]:
+ """For each app earning rewards: today's focus time and the next focus milestone."""
+ day = day or date.today().isoformat()
+ rows = db.fetchall(
+ "SELECT r.app_id, r.threshold, r.reward_json, r.repeatable, a.exe_name, a.display_name, "
+ "a.icon_path, COALESCE(d.focused_ms, 0) AS focused_ms "
+ "FROM reward_rules r JOIN apps a ON a.app_id = r.app_id "
+ "LEFT JOIN daily_rollup d ON d.app_id = r.app_id AND d.day = ? "
+ "WHERE r.enabled = 1 AND r.metric = 'focused_ms' AND a.is_hidden = 0 ORDER BY r.threshold",
+ (day,),
+ )
+ by_app: dict[int, dict] = {}
+ for r in rows:
+ app = by_app.setdefault(
+ r["app_id"],
+ {
+ "app_id": r["app_id"],
+ "name": catalog.display_name(dict(r)),
+ "exe_name": r["exe_name"],
+ "icon_path": r["icon_path"],
+ "focused_ms": r["focused_ms"],
+ "next": None,
+ },
+ )
+ used = r["focused_ms"]
+ target = r["threshold"]
+ if r["repeatable"]:
+ target = (used // r["threshold"] + 1) * r["threshold"]
+ elif used >= target:
+ continue
+ reward = json.loads(r["reward_json"])
+ nxt = app["next"]
+ if nxt is None or target < nxt["target_ms"]:
+ app["next"] = {"target_ms": target, "reward": reward}
+ elif target == nxt["target_ms"]:
+ for key, value in reward.items():
+ nxt["reward"][key] = nxt["reward"].get(key, 0) + value
+ return sorted(by_app.values(), key=lambda a: a["name"].lower())
diff --git a/apptrackr/rewards/rules.py b/apptrackr/rewards/rules.py
index 31eb0fd..5efd698 100644
--- a/apptrackr/rewards/rules.py
+++ b/apptrackr/rewards/rules.py
@@ -1,91 +1,49 @@
-"""Reward rules configuration (defaults and helpers)."""
+"""Per-app reward rules."""
from __future__ import annotations
import json
+
from ..data import db
+MINUTE = 60 * 1000
+# (metric, threshold, reward, repeatable)
DEFAULT_RULES = [
- # (metric, threshold, reward_json, repeatable)
- ("focused_ms", 30 * 60 * 1000, {"xp": 10, "wood": 5}, True),
- ("focused_ms", 60 * 60 * 1000, {"xp": 25, "stone": 10}, True),
- ("focused_ms", 2 * 60 * 60 * 1000, {"xp": 60, "blueprints": 1}, True),
- ("focused_ms", 5 * 60 * 60 * 1000, {"xp": 150, "metal": 20}, True),
- ("opens_count", 10, {"xp": 5, "food": 5}, False),
- ("opens_count", 50, {"xp": 20, "wood": 10}, False),
+ ("focused_ms", 30 * MINUTE, {"xp": 10, "wood": 5}, True),
+ ("focused_ms", 60 * MINUTE, {"xp": 25, "stone": 10}, True),
+ ("focused_ms", 120 * MINUTE, {"xp": 60, "blueprints": 1}, True),
+ ("focused_ms", 300 * MINUTE, {"xp": 150, "metal": 20}, True),
+ ("opens_count", 3, {"xp": 5, "food": 5}, False),
+ ("opens_count", 10, {"xp": 20, "wood": 10}, False),
("clicks_count", 500, {"xp": 10, "stone": 5}, False),
("clicks_count", 2000, {"xp": 30, "metal": 10}, False),
]
-def create_default_rules(app_id: int) -> None:
- """Seed default reward rules for a given app."""
- for metric, threshold, reward, repeatable in DEFAULT_RULES:
- existing = db.fetchone(
- "SELECT 1 FROM reward_rules WHERE app_id = ? AND metric = ? AND threshold = ?",
- (app_id, metric, threshold),
- )
- if not existing:
- db.execute(
- "INSERT INTO reward_rules (app_id, metric, threshold, reward_json, repeatable, enabled) "
- "VALUES (?, ?, ?, ?, ?, ?)",
- (app_id, metric, threshold, json.dumps(reward), int(repeatable), 0),
- )
- db.commit()
-
-
-def list_rules(app_id: int | None = None) -> list[dict]:
- if app_id is not None:
- rows = db.fetchall("SELECT * FROM reward_rules WHERE app_id = ?", (app_id,))
- else:
- rows = db.fetchall("SELECT * FROM reward_rules")
- return [dict(r) for r in rows]
-
-
-def add_rule(app_id: int, metric: str, threshold: int, reward: dict,
- repeatable: bool = False) -> int:
- cur = db.execute(
- "INSERT INTO reward_rules (app_id, metric, threshold, reward_json, repeatable) "
- "VALUES (?, ?, ?, ?, ?)",
- (app_id, metric, threshold, json.dumps(reward), int(repeatable)),
+def ensure_app_rules(app_id: int) -> None:
+ """Create the default (disabled) rule set for an app if it has none."""
+ row = db.fetchone("SELECT COUNT(*) AS n FROM reward_rules WHERE app_id = ?", (app_id,))
+ if row and row["n"]:
+ return
+ db.executemany(
+ "INSERT INTO reward_rules (app_id, metric, threshold, reward_json, repeatable, enabled) "
+ "VALUES (?, ?, ?, ?, ?, 0)",
+ [(app_id, m, t, json.dumps(r), int(rep)) for m, t, r, rep in DEFAULT_RULES],
)
db.commit()
- return cur.lastrowid # type: ignore[return-value]
-
-
-def toggle_rule(rule_id: int, enabled: bool) -> None:
- db.execute("UPDATE reward_rules SET enabled = ? WHERE rule_id = ?",
- (int(enabled), rule_id))
- db.commit()
-
-
-def delete_rule(rule_id: int) -> None:
- db.execute("DELETE FROM reward_rules WHERE rule_id = ?", (rule_id,))
- db.commit()
def enable_app_rewards(app_id: int, enabled: bool = True) -> None:
- """Enable or disable all reward rules for a specific app."""
- db.execute("UPDATE reward_rules SET enabled = ? WHERE app_id = ?",
- (int(enabled), app_id))
+ ensure_app_rules(app_id)
+ db.execute("UPDATE reward_rules SET enabled = ? WHERE app_id = ?", (int(enabled), app_id))
db.commit()
def app_rewards_enabled(app_id: int) -> bool:
- """Check if an app has any enabled reward rules."""
- row = db.fetchone(
- "SELECT COUNT(*) as cnt FROM reward_rules WHERE app_id = ? AND enabled = 1",
- (app_id,)
- )
- return row and row["cnt"] > 0
+ row = db.fetchone("SELECT COUNT(*) AS n FROM reward_rules WHERE app_id = ? AND enabled = 1", (app_id,))
+ return bool(row and row["n"])
-def ensure_app_rules(app_id: int) -> None:
- """Ensure an app has default reward rules created."""
- existing = db.fetchone(
- "SELECT COUNT(*) as cnt FROM reward_rules WHERE app_id = ?",
- (app_id,)
- )
- if not existing or existing["cnt"] == 0:
- create_default_rules(app_id)
+def earning_app_ids() -> set[int]:
+ return {r["app_id"] for r in db.fetchall("SELECT DISTINCT app_id FROM reward_rules WHERE enabled = 1")}
diff --git a/apptrackr/ui/fmt.py b/apptrackr/ui/fmt.py
new file mode 100644
index 0000000..00aa90c
--- /dev/null
+++ b/apptrackr/ui/fmt.py
@@ -0,0 +1,97 @@
+"""Text formatting for durations, dates and rewards."""
+
+from __future__ import annotations
+
+from datetime import date, datetime
+
+RESOURCE_LABELS = {
+ "xp": "XP",
+ "credits": "credits",
+ "wood": "wood",
+ "stone": "stone",
+ "metal": "metal",
+ "food": "food",
+ "blueprints": "blueprints",
+}
+_REWARD_ORDER = ("xp", "credits", "wood", "stone", "metal", "food", "blueprints")
+
+
+def duration(ms: int | float, short: bool = False) -> str:
+ """'2h 15m', '45m', '30s'. With short=True seconds are dropped above a minute."""
+ seconds = max(0, int(ms // 1000))
+ if seconds < 60:
+ return f"{seconds}s"
+ minutes, seconds = divmod(seconds, 60)
+ if minutes < 60:
+ return f"{minutes}m" if short or not seconds or minutes >= 10 else f"{minutes}m {seconds}s"
+ hours, minutes = divmod(minutes, 60)
+ return f"{hours}h {minutes}m" if minutes else f"{hours}h"
+
+
+def clock(ms: int | float) -> str:
+ """Live timer format: '1:04:09' or '4:09'."""
+ seconds = max(0, int(ms // 1000))
+ hours, rem = divmod(seconds, 3600)
+ minutes, seconds = divmod(rem, 60)
+ return f"{hours}:{minutes:02d}:{seconds:02d}" if hours else f"{minutes}:{seconds:02d}"
+
+
+def axis(ms: int | float) -> str:
+ """Compact engraved axis label: 0, 15M, 1H, 1H30, 12H."""
+ minutes = int(ms // 60000)
+ if minutes == 0:
+ return "0"
+ if minutes < 60:
+ return f"{minutes}M"
+ hours, rest = divmod(minutes, 60)
+ return f"{hours}H{rest:02d}" if rest else f"{hours}H"
+
+
+def percent_change(current: float, previous: float) -> str | None:
+ if previous <= 0:
+ return None
+ change = (current - previous) / previous * 100
+ return f"{change:+.0f}%"
+
+
+def long_date(d: date | str) -> str:
+ d = date.fromisoformat(d) if isinstance(d, str) else d
+ return f"{d:%A}, {d:%B} {d.day}"
+
+
+def short_date(d: date | str) -> str:
+ d = date.fromisoformat(d) if isinstance(d, str) else d
+ return f"{d:%b} {d.day}"
+
+
+def relative_day(d: date | str | None) -> str:
+ if not d:
+ return "Never"
+ d = date.fromisoformat(d) if isinstance(d, str) else d
+ delta = (date.today() - d).days
+ if delta == 0:
+ return "Today"
+ if delta == 1:
+ return "Yesterday"
+ if delta < 7:
+ return f"{delta} days ago"
+ return short_date(d) if d.year == date.today().year else f"{short_date(d)}, {d.year}"
+
+
+def time_of_day(ts: float) -> str:
+ dt = datetime.fromtimestamp(ts)
+ return dt.strftime("%H:%M")
+
+
+def reward(reward: dict, sep: str = " ") -> str:
+ parts = []
+ for key in _REWARD_ORDER:
+ if reward.get(key):
+ parts.append(f"+{reward[key]} {RESOURCE_LABELS[key]}")
+ if reward.get("level_up"):
+ parts.append(f"Level {reward['level_up']}")
+ return sep.join(parts)
+
+
+def count(n: int) -> str:
+ return f"{n:,}"
diff --git a/apptrackr/ui/fonts.py b/apptrackr/ui/fonts.py
new file mode 100644
index 0000000..18b200a
--- /dev/null
+++ b/apptrackr/ui/fonts.py
@@ -0,0 +1,51 @@
+"""Bundled typefaces: Instrument Sans for the interface, Martian Mono for engraved labels.
+
+Both are SIL Open Font License fonts shipped in assets/fonts (see the OFL-*.txt files).
+"""
+
+from __future__ import annotations
+
+import logging
+from functools import lru_cache
+
+from PySide6.QtGui import QFont, QFontDatabase
+
+from .. import paths
+
+log = logging.getLogger(__name__)
+
+SANS = "Instrument Sans"
+MONO = "Martian Mono"
+_FALLBACK_SANS = ("Segoe UI Variable Text", "Segoe UI", "Inter", "Noto Sans", "Ubuntu")
+_FALLBACK_MONO = ("Cascadia Mono", "Consolas", "JetBrains Mono", "DejaVu Sans Mono")
+
+
+@lru_cache(maxsize=1)
+def load() -> tuple[str, str]:
+ """Register the bundled fonts once; returns the (sans, mono) families in use."""
+ for path in sorted((paths.assets_dir() / "fonts").glob("*.ttf")):
+ if QFontDatabase.addApplicationFont(str(path)) < 0:
+ log.warning("Could not load font %s", path.name)
+ families = set(QFontDatabase.families())
+ sans = SANS if SANS in families else next((f for f in _FALLBACK_SANS if f in families), "")
+ mono = MONO if MONO in families else next((f for f in _FALLBACK_MONO if f in families), "monospace")
+ return sans, mono
+
+
+def sans(px: int = 13, weight: int = 400, tabular: bool = False) -> QFont:
+ font = QFont(load()[0])
+ font.setPixelSize(px)
+ font.setWeight(QFont.Weight(weight))
+ if tabular:
+ font.setFeature(QFont.Tag("tnum"), 1)
+ return font
+
+
+def mono(px: int = 10, weight: int = 500, tracking: float = 8.0) -> QFont:
+ """Engraved-label face: small, tracked out by *tracking* percent."""
+ font = QFont(load()[1])
+ font.setPixelSize(px)
+ font.setWeight(QFont.Weight(weight))
+ if tracking:
+ font.setLetterSpacing(QFont.SpacingType.PercentageSpacing, 100 + tracking)
+ return font
diff --git a/apptrackr/ui/icons.py b/apptrackr/ui/icons.py
new file mode 100644
index 0000000..c258988
--- /dev/null
+++ b/apptrackr/ui/icons.py
@@ -0,0 +1,77 @@
+"""Tinted SVG icons. Icon artwork from Lucide (ISC license, see assets/icons/LICENSE)."""
+
+from __future__ import annotations
+
+from functools import cache, lru_cache
+
+from PySide6.QtCore import QByteArray, QRectF, Qt
+from PySide6.QtGui import QGuiApplication, QIcon, QPainter, QPixmap
+from PySide6.QtSvg import QSvgRenderer
+
+from .. import paths
+
+
+@cache
+def _source(name: str) -> str:
+ return (paths.assets_dir() / "icons" / f"{name}.svg").read_text(encoding="utf-8")
+
+
+def _dpr() -> float:
+ app = QGuiApplication.instance()
+ screen = app.primaryScreen() if app else None
+ return screen.devicePixelRatio() if screen else 1.0
+
+
+def _render(svg: str, size: int, height: int | None = None) -> QPixmap:
+ dpr = _dpr()
+ pm = QPixmap(int(size * dpr), int((height or size) * dpr))
+ pm.fill(Qt.GlobalColor.transparent)
+ renderer = QSvgRenderer(QByteArray(svg.encode("utf-8")))
+ painter = QPainter(pm)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ renderer.render(painter, QRectF(0, 0, pm.width(), pm.height()))
+ painter.end()
+ pm.setDevicePixelRatio(dpr)
+ return pm
+
+
+def stroke_for(size: int) -> float:
+ """Hairline strokes: thinner relative to the 24-unit grid as icons get larger."""
+ return 1.75 if size <= 16 else (1.6 if size <= 22 else 1.4)
+
+
+@lru_cache(maxsize=512)
+def pixmap(name: str, color: str, size: int = 16, filled: bool = False) -> QPixmap:
+ svg = _source(name).replace("currentColor", color).replace('stroke-width="2"', f'stroke-width="{stroke_for(size)}"')
+ if filled:
+ svg = svg.replace('fill="none"', f'fill="{color}"', 1)
+ return _render(svg, size)
+
+
+@lru_cache(maxsize=64)
+def illustration(name: str, ink: str, accent: str, faint: str, size: int = 120) -> QPixmap:
+ """Hairline line-art from assets/illustrations, tinted with ink, accent and faint colours."""
+ svg = (paths.assets_dir() / "illustrations" / f"{name}.svg").read_text(encoding="utf-8")
+ svg = svg.replace("INK", ink).replace("ACCENT", accent).replace("FAINT", faint)
+ return _render(svg, size, height=int(size * 0.8))
+
+
+def icon(name: str, color: str, size: int = 16, checked_color: str | None = None) -> QIcon:
+ """QIcon with an optional different tint for the checked state."""
+ ic = QIcon()
+ ic.addPixmap(pixmap(name, color, size), QIcon.Mode.Normal, QIcon.State.Off)
+ ic.addPixmap(pixmap(name, checked_color or color, size), QIcon.Mode.Normal, QIcon.State.On)
+ return ic
+
+
+@lru_cache(maxsize=16)
+def logo_pixmap(size: int = 32) -> QPixmap:
+ name = "logo-small.svg" if size <= 32 else "logo.svg" # the small mark drops minor ticks
+ return _render((paths.assets_dir() / name).read_text(encoding="utf-8"), size)
+
+
+def logo_icon() -> QIcon:
+ ic = QIcon()
+ for size in (16, 20, 24, 32, 48, 64, 128, 256):
+ ic.addPixmap(logo_pixmap(size))
+ return ic
diff --git a/apptrackr/ui/main.py b/apptrackr/ui/main.py
index 5b263c4..e7e3346 100644
--- a/apptrackr/ui/main.py
+++ b/apptrackr/ui/main.py
@@ -1,266 +1,689 @@
-"""Main application window with sidebar navigation and tray icon."""
+"""Main window: sidebar navigation, page stack, tray icon, shortcuts and background timers."""
from __future__ import annotations
+import logging
+import math
import sys
-import threading
+import tempfile
+import time
+from pathlib import Path
+from typing import Callable
-from PySide6.QtCore import Qt, QTimer
-from PySide6.QtGui import QIcon, QAction, QPixmap, QPainter, QColor, QFont
+from PySide6.QtCore import QPoint, QRectF, Qt, QTimer
+from PySide6.QtGui import QAction, QGuiApplication, QKeySequence, QShortcut
from PySide6.QtWidgets import (
- QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QStackedWidget,
- QSystemTrayIcon, QMenu, QApplication, QLabel, QButtonGroup,
+ QApplication,
+ QButtonGroup,
+ QFrame,
+ QHBoxLayout,
+ QLabel,
+ QMainWindow,
+ QMenu,
+ QPushButton,
+ QStackedWidget,
+ QSystemTrayIcon,
+ QVBoxLayout,
+ QWidget,
)
-from . import theme
-from .widgets.components import SidebarButton
-from .views.dashboard import DashboardView
-from .views.calendar_view import CalendarView
-from .views.apps_view import AppsView
-from .views.app_detail import AppDetailView
-from .views.rewards_view import RewardsView
-from .views.village_view import VillageView
-from .views.settings_view import SettingsView
-from ..data import db
-from ..updater import check as updater_check
-
-
-def _make_icon() -> QIcon:
- """Create a simple neon 'A' icon programmatically."""
- pix = QPixmap(64, 64)
- pix.fill(QColor(0, 0, 0, 0))
- p = QPainter(pix)
- p.setRenderHint(QPainter.RenderHint.Antialiasing)
- # Background circle
- p.setPen(Qt.PenStyle.NoPen)
- p.setBrush(QColor(theme.BG_DARK))
- p.drawRoundedRect(0, 0, 64, 64, 16, 16)
- # Letter
- p.setPen(QColor(theme.get_accent()))
- p.setFont(QFont("Segoe UI", 32, QFont.Weight.Bold))
- p.drawText(pix.rect(), Qt.AlignmentFlag.AlignCenter, "A")
- p.end()
- return QIcon(pix)
+from .. import APP_NAME, __version__, paths
+from ..core import tracker as trk
+from ..core.limits import LimitMonitor
+from ..data import db, queries
+from ..rewards import engine as rewards
+from ..updater import check as updater
+from . import fmt, fonts, icons, motion, theme
+from .signals import bus, run_async
+from .widgets.components import Badge, IconBinding, StatusModule, Toast, label
+
+log = logging.getLogger(__name__)
+
+PAGES = ("dashboard", "calendar", "apps", "rewards", "village", "settings", "app")
+NAV = (
+ ("dashboard", "Dashboard", "layout-dashboard"),
+ ("calendar", "Calendar", "calendar-days"),
+ ("apps", "Apps", "layout-grid"),
+ ("rewards", "Rewards", "gift"),
+ ("village", "Village", "castle"),
+)
-class MainWindow(QMainWindow):
- """Main AppTrackr window with sidebar and stacked views."""
+class AppContext:
+ """Services and navigation shared with every view."""
- PAGE_DASHBOARD = 0
- PAGE_CALENDAR = 1
- PAGE_APPS = 2
- PAGE_APP_DETAIL = 3
- PAGE_REWARDS = 4
- PAGE_VILLAGE = 5
- PAGE_SETTINGS = 6
+ def __init__(self, window: MainWindow, tracker, clicks, demo: bool):
+ self.window = window
+ self.tracker = tracker
+ self.clicks = clicks
+ self.demo = demo
+ self.update_info: updater.UpdateInfo | None = None
- def __init__(self, tracker):
- super().__init__()
- self._tracker = tracker
- self.setWindowTitle("AppTrackr")
- self.setMinimumSize(1080, 720)
- self.setWindowIcon(_make_icon())
+ def navigate(self, page: str) -> None:
+ self.window.show_page(page)
- self._build_ui()
- self._setup_tray()
+ def open_app(self, app_id: int) -> None:
+ self.window.open_app(app_id)
- # Optional startup update check (non-blocking)
- QTimer.singleShot(8000, self._startup_update_check)
+ def toast(self, text: str, tone: str = "success", action: str = "", callback: Callable | None = None) -> None:
+ self.window.toast.show_message(text, tone, action, callback)
- def _build_ui(self):
- central = QWidget()
- self.setCentralWidget(central)
- main_layout = QHBoxLayout(central)
- main_layout.setContentsMargins(0, 0, 0, 0)
- main_layout.setSpacing(0)
-
- # -- Sidebar --
- sidebar = QWidget()
- sidebar.setFixedWidth(220)
- sidebar.setStyleSheet(f"background-color: {theme.BG_DARKEST};")
- sb_layout = QVBoxLayout(sidebar)
- sb_layout.setContentsMargins(12, 20, 12, 20)
- sb_layout.setSpacing(4)
-
- # Logo
- logo = QLabel("⚡ AppTrackr")
- logo.setStyleSheet(
- f"font-size: 20px; font-weight: 800; color: {theme.get_accent()}; "
- f"padding: 8px 8px 20px 8px; background: transparent;"
- )
- sb_layout.addWidget(logo)
-
- # Nav buttons
- self._nav_group = QButtonGroup(self)
- self._nav_group.setExclusive(True)
+ def snapshot(self) -> trk.Snapshot:
+ return self.tracker.snapshot()
- nav_items = [
- ("📊", "Dashboard", self.PAGE_DASHBOARD),
- ("📅", "Calendar", self.PAGE_CALENDAR),
- ("📱", "Apps", self.PAGE_APPS),
- ("🎁", "Rewards", self.PAGE_REWARDS),
- ("🎮", "Game", self.PAGE_VILLAGE),
- ("⚙️", "Settings", self.PAGE_SETTINGS),
- ]
+ def app_menu(self, app_id: int, pos: QPoint) -> None:
+ self.window.show_app_menu(app_id, pos)
- for icon, text, page_idx in nav_items:
- btn = SidebarButton(icon, text)
- btn.clicked.connect(lambda checked, idx=page_idx: self._show_page(idx))
- self._nav_group.addButton(btn, page_idx)
- sb_layout.addWidget(btn)
+ def open_day(self, day: str) -> None:
+ self.window.open_day(day)
- sb_layout.addStretch()
- # Version label
- ver = QLabel("v1.0.0")
- ver.setStyleSheet(f"color: {theme.TEXT_MUTED}; font-size: 10px; padding: 8px; background: transparent;")
- sb_layout.addWidget(ver)
-
- main_layout.addWidget(sidebar)
+class MainWindow(QMainWindow):
+ def __init__(self, tracker, clicks=None, demo: bool = False):
+ super().__init__()
+ self.ctx = AppContext(self, tracker, clicks, demo)
+ self._tracker = tracker
+ self._history: list[str] = []
+ self._current = "dashboard"
+ self._limits = LimitMonitor()
+ self._quitting = False
- # -- Content stack --
- self._stack = QStackedWidget()
- self._stack.setStyleSheet(f"background-color: {theme.BG_DARK};")
+ self.setWindowTitle(APP_NAME + (" (demo)" if demo else ""))
+ self.setWindowIcon(icons.logo_icon())
+ self.setMinimumSize(980, 640)
+ self.resize(1240, 800)
- self._dashboard = DashboardView(self._tracker)
- self._dashboard.app_selected.connect(self._show_app_detail)
- self._stack.addWidget(self._dashboard)
+ self._build()
+ self._setup_tray()
+ self._setup_shortcuts()
+ self.toast = Toast(self.centralWidget())
+ bus.toast.connect(lambda text, tone: self.toast.show_message(text, tone))
+ bus.rewards_changed.connect(self._update_badges)
+ bus.theme_changed.connect(self._refresh_status)
+
+ self._tick_timer = QTimer(self)
+ self._tick_timer.timeout.connect(self._tick)
+ self._tick_timer.start(1000)
+ self._slow_timer = QTimer(self)
+ self._slow_timer.timeout.connect(self._slow_tick)
+ self._slow_timer.start(30_000)
+
+ self.apply_rewards_visibility()
+ self.show_page("dashboard")
+ self._refresh_status()
+ QTimer.singleShot(1500, self._slow_tick)
+ QTimer.singleShot(10_000, self._startup_update_check)
- self._calendar = CalendarView()
- self._calendar.app_selected.connect(self._show_app_detail)
- self._stack.addWidget(self._calendar)
+ # ------------------------------------------------------------------
+ # Layout
+ # ------------------------------------------------------------------
- self._apps = AppsView()
- self._apps.app_selected.connect(self._show_app_detail)
- self._stack.addWidget(self._apps)
+ def _build(self) -> None:
+ from .views.app_detail import AppDetailView
+ from .views.apps_view import AppsView
+ from .views.calendar_view import CalendarView
+ from .views.dashboard import DashboardView
+ from .views.rewards_view import RewardsView
+ from .views.settings_view import SettingsView
+ from .views.village_view import VillageView
- self._app_detail = AppDetailView()
- self._app_detail.back_clicked.connect(lambda: self._show_page(self.PAGE_APPS))
- self._stack.addWidget(self._app_detail)
+ central = QWidget()
+ self.setCentralWidget(central)
+ root = QHBoxLayout(central)
+ root.setContentsMargins(0, 0, 0, 0)
+ root.setSpacing(0)
+ root.addWidget(self._build_sidebar())
- self._rewards = RewardsView()
- self._stack.addWidget(self._rewards)
+ self._stack = QStackedWidget()
+ self._stack.setFocusPolicy(Qt.FocusPolicy.ClickFocus)
+ self._views = {
+ "dashboard": DashboardView(self.ctx),
+ "calendar": CalendarView(self.ctx),
+ "apps": AppsView(self.ctx),
+ "rewards": RewardsView(self.ctx),
+ "village": VillageView(self.ctx),
+ "settings": SettingsView(self.ctx),
+ "app": AppDetailView(self.ctx),
+ }
+ for view in self._views.values():
+ self._stack.addWidget(view)
+ root.addWidget(self._stack, 1)
+
+ def _build_sidebar(self) -> QWidget:
+ side = QWidget()
+ side.setObjectName("sidebar")
+ side.setFixedWidth(220)
+ lay = QVBoxLayout(side)
+ lay.setContentsMargins(14, 18, 14, 14)
+ lay.setSpacing(2)
+
+ brand = QHBoxLayout()
+ brand.setContentsMargins(4, 0, 0, 0)
+ brand.setSpacing(10)
+ logo = QLabel()
+ logo.setPixmap(icons.logo_pixmap(28))
+ brand.addWidget(logo)
+ words = QVBoxLayout()
+ words.setSpacing(0)
+ name = QLabel(APP_NAME)
+ name.setFont(fonts.sans(15, 600))
+ words.addWidget(name)
+ words.addWidget(label("Attention instrument", "tick"))
+ brand.addLayout(words, 1)
+ lay.addLayout(brand)
+ lay.addSpacing(22)
+
+ self._indicator = QFrame(side)
+ self._indicator.setObjectName("navIndicator")
+ self._indicator.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self._indicator.hide()
+ self._nav_group = QButtonGroup(self)
+ self._nav_group.setExclusive(True)
+ self._nav_group.buttonToggled.connect(lambda btn, on: on and self._move_indicator(btn))
+ self._nav_buttons: dict[str, QPushButton] = {}
+ self._badges: dict[str, Badge] = {}
+ self._keys: dict[str, QLabel] = {}
+
+ overview = label("Overview", "eyebrow")
+ overview.setContentsMargins(10, 0, 0, 6)
+ lay.addWidget(overview)
+ for i, (key, text, icon) in enumerate(NAV, start=1):
+ if key == "rewards":
+ lay.addSpacing(14)
+ self._progress_label = label("Progress", "eyebrow")
+ self._progress_label.setContentsMargins(10, 0, 0, 6)
+ lay.addWidget(self._progress_label)
+ lay.addWidget(self._nav_button(key, text, icon, str(i)))
+ lay.addStretch(1)
+ lay.addWidget(self._nav_button("settings", "Settings", "settings", ","))
+ lay.addSpacing(10)
+
+ self._status = StatusModule()
+ self._status.setToolTip("Pause or resume tracking (Ctrl+Shift+P)")
+ self._status.clicked.connect(self.toggle_pause)
+ self._pulse = self._status.pulse
+ lay.addWidget(self._status)
+
+ self._version = label(f"v{__version__}", "tick")
+ self._version.setContentsMargins(4, 10, 0, 0)
+ self._version.setTextFormat(Qt.TextFormat.RichText)
+ self._version.linkActivated.connect(lambda *_: self.show_page("settings"))
+ lay.addWidget(self._version)
+ return side
+
+ def _nav_button(self, key: str, text: str, icon: str, shortcut: str) -> QPushButton:
+ btn = QPushButton(text)
+ btn.setProperty("nav", True)
+ btn.setCheckable(True)
+ btn.setFixedHeight(34)
+ btn.setCursor(Qt.CursorShape.PointingHandCursor)
+ btn.setFocusPolicy(Qt.FocusPolicy.TabFocus)
+ btn.setToolTip(f"{text} (Ctrl+{shortcut})")
+ IconBinding.attach(btn, icon, "text_muted", 16, checked_tone="accent_text")
+ btn.clicked.connect(lambda *_: self.show_page(key))
+ hint = label(shortcut, "tick", align=Qt.AlignmentFlag.AlignCenter) # keycap; Ctrl is in the tooltip
+ hint.setParent(btn)
+ hint.setObjectName("navKey")
+ hint.setFixedSize(17, 16)
+ hint.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self._keys[key] = hint
+ badge = Badge(btn)
+ self._badges[key] = badge
+ btn.installEventFilter(self)
+ self._nav_group.addButton(btn)
+ self._nav_buttons[key] = btn
+ return btn
+
+ def _place_nav_extras(self, key: str, btn: QPushButton) -> None:
+ badge, hint = self._badges[key], self._keys[key]
+ badge.adjustSize()
+ badge.move(btn.width() - badge.width() - 8, (btn.height() - badge.height()) // 2)
+ hint.adjustSize()
+ hint.move(btn.width() - hint.width() - 10, (btn.height() - hint.height()) // 2)
+ hint.setVisible(not badge.isVisible())
+
+ def eventFilter(self, obj, event):
+ if event.type() in (event.Type.Resize, event.Type.Move, event.Type.Show, event.Type.Hide):
+ for key, btn in self._nav_buttons.items():
+ if btn is obj:
+ self._place_nav_extras(key, btn)
+ if btn.isChecked() and not self._indicator_moving():
+ self._move_indicator(btn, animate=False)
+ return super().eventFilter(obj, event)
+
+ # Selection indicator ---------------------------------------------------------
+
+ INDICATOR_H = 16
+
+ def _indicator_rect(self, btn: QPushButton) -> QRectF:
+ return QRectF(btn.x() + 2, btn.y() + (btn.height() - self.INDICATOR_H) / 2, 3, self.INDICATOR_H)
+
+ def _indicator_moving(self) -> bool:
+ return motion.running(self, "indicator") is not None
+
+ def _move_indicator(self, btn: QPushButton, animate: bool = True) -> None:
+ """Glide the accent bar to the selected item, stretching mid-flight like Fluent's NavigationView."""
+ if not btn.isVisible():
+ self._indicator.hide()
+ return
+ end = self._indicator_rect(btn)
+ start = QRectF(self._indicator.geometry()) if self._indicator.isVisible() else end
+ self._indicator.show()
+ self._indicator.raise_()
+
+ def step(t: float) -> None:
+ eased = motion.EASY_EASE.valueForProgress(t)
+ stretch = math.sin(math.pi * t) * abs(end.y() - start.y()) * 0.35
+ y = motion.lerp(start.y(), end.y(), eased)
+ self._indicator.setGeometry(QRectF(end.x(), y - stretch / 2, 3, self.INDICATOR_H + stretch).toRect())
+
+ if not animate or start == end:
+ step(1.0)
+ return
+ motion.tween(self, 0.0, 1.0, motion.GENTLE, step, motion.LINEAR, key="indicator")
- self._village = VillageView()
- self._stack.addWidget(self._village)
+ # ------------------------------------------------------------------
+ # Navigation
+ # ------------------------------------------------------------------
- self._settings = SettingsView(tracker=self._tracker)
- self._stack.addWidget(self._settings)
+ def show_page(self, key: str, remember: bool = True) -> None:
+ if key not in self._views:
+ return
+ if remember and key != self._current and self._current != "app":
+ self._history = [self._current]
+ changed = key != self._current
+ self._current = key
+ view = self._views[key]
+ self._stack.setCurrentWidget(view)
+ btn = self._nav_buttons.get(key)
+ if btn:
+ btn.setChecked(True)
+ if hasattr(view, "refresh"):
+ view.refresh()
+ if changed:
+ self._enter(view)
+
+ def _enter(self, view: QWidget) -> None:
+ """Fade-through page transition: the incoming page fades up from the window background."""
+ motion.fade(view, 0.0, 1.0, motion.NORMAL, motion.DECELERATE)
+
+ def open_app(self, app_id: int) -> None:
+ if self._current != "app":
+ self._history = [self._current]
+ self._views["app"].load_app(app_id)
+ self._current = "app"
+ self._stack.setCurrentWidget(self._views["app"])
+ self._enter(self._views["app"])
+ for btn in self._nav_buttons.values():
+ if btn.isChecked():
+ self._nav_group.setExclusive(False)
+ btn.setChecked(False)
+ self._nav_group.setExclusive(True)
+ origin = self._history[-1] if self._history else "apps"
+ if origin in self._nav_buttons:
+ self._nav_buttons[origin].setChecked(True)
+
+ def open_day(self, day: str) -> None:
+ self._views["calendar"].select_day(day)
+ self.show_page("calendar")
+
+ def go_back(self) -> None:
+ if self._current == "app":
+ self.show_page(self._history[-1] if self._history else "apps", remember=False)
+
+ def back_label(self) -> str:
+ origin = self._history[-1] if self._history else "apps"
+ return dict((k, t) for k, t, _ in NAV).get(origin, "Settings" if origin == "settings" else "Apps")
+
+ def refresh_current(self) -> None:
+ view = self._views[self._current]
+ if self._current == "app":
+ view.reload()
+ elif hasattr(view, "refresh"):
+ view.refresh()
+
+ def apply_rewards_visibility(self) -> None:
+ on = rewards.enabled()
+ for key in ("rewards", "village"):
+ self._nav_buttons[key].setVisible(on)
+ self._progress_label.setVisible(on)
+ if not on and self._current in ("rewards", "village"):
+ self.show_page("dashboard")
+ self._update_badges()
+
+ def _update_badges(self) -> None:
+ self._badges["rewards"].set_count(rewards.unclaimed_count() if rewards.enabled() else 0)
+ self._place_nav_extras("rewards", self._nav_buttons["rewards"])
- main_layout.addWidget(self._stack, stretch=1)
+ # ------------------------------------------------------------------
+ # App context menu (shared by every list)
+ # ------------------------------------------------------------------
- # Default page
- self._show_page(self.PAGE_DASHBOARD)
+ def show_app_menu(self, app_id: int, pos: QPoint) -> None:
+ app = queries.get_app(app_id)
+ if not app:
+ return
+ menu = QMenu(self)
+ menu.addAction("Open details", lambda: self.open_app(app_id))
+ fav = bool(app.get("is_favorite"))
+ menu.addAction(
+ "Remove from favorites" if fav else "Add to favorites", lambda: self._set_favorite(app_id, not fav)
+ )
+ menu.addSeparator()
+ menu.addAction("Exclude from tracking", lambda: self.exclude_app(app_id))
+ menu.exec(pos)
- # Periodic reward eval
- self._reward_timer = QTimer(self)
- self._reward_timer.timeout.connect(self._periodic_eval)
- self._reward_timer.start(60_000) # every 60s
+ def _set_favorite(self, app_id: int, fav: bool) -> None:
+ queries.set_favorite(app_id, fav)
+ bus.data_changed.emit()
+ self.refresh_current()
- def _show_page(self, idx: int):
- self._stack.setCurrentIndex(idx)
- btn = self._nav_group.button(idx)
- if btn:
- btn.setChecked(True)
- # Refresh view on show
- widget = self._stack.currentWidget()
- if hasattr(widget, "refresh"):
- widget.refresh()
+ def exclude_app(self, app_id: int) -> None:
+ app = queries.get_app(app_id)
+ if not app:
+ return
+ queries.set_hidden(app_id, True)
+ self._tracker.reload_settings()
+ bus.data_changed.emit()
+ if self._current == "app":
+ self.go_back()
+ else:
+ self.refresh_current()
- def _show_app_detail(self, app_id: int):
- self._app_detail.load_app(app_id)
- self._stack.setCurrentIndex(self.PAGE_APP_DETAIL)
+ def undo():
+ queries.set_hidden(app_id, False)
+ self._tracker.reload_settings()
+ bus.data_changed.emit()
+ self.refresh_current()
- def _periodic_eval(self):
- from ..rewards import engine
- engine.evaluate()
- engine.update_streak()
+ self.toast.show_message(f"{app['name']} is no longer tracked", "info", "Undo", undo)
# ------------------------------------------------------------------
- # System tray
+ # Tracking state
# ------------------------------------------------------------------
- def _setup_tray(self):
- self._tray = QSystemTrayIcon(_make_icon(), self)
+ def toggle_pause(self) -> None:
+ if not self._tracker.supported:
+ self.toast.show_message("Tracking is only available on Windows", "info")
+ return
+ if self._tracker.paused:
+ self._tracker.resume()
+ self.toast.show_message("Tracking resumed", "success")
+ else:
+ self._tracker.pause()
+ self.toast.show_message("Tracking paused", "info")
+ self._tick()
+
+ def pause_for(self, minutes: float | None) -> None:
+ self._tracker.pause(minutes)
+ until = f" for {fmt.duration(minutes * 60_000)}" if minutes else ""
+ self.toast.show_message(f"Tracking paused{until}", "info")
+ self._tick()
+
+ def _status_text(self, snap: trk.Snapshot) -> tuple[str, str, str, str]:
+ """(headline, subject, clock, tone) for the sidebar module and tray tooltip."""
+ if snap.status == trk.STATUS_TRACKING and snap.exe_name:
+ app = queries.get_app(snap.app_id) if snap.app_id else None
+ return "Tracking", app["name"] if app else snap.exe_name, fmt.clock(snap.session_ms), "accent"
+ if snap.status == trk.STATUS_PAUSED:
+ if snap.paused_until:
+ left = max(0, snap.paused_until - time.time())
+ return "Paused", "Resumes automatically", fmt.clock(left * 1000), "warning"
+ return "Paused", "Click to resume", "", "warning"
+ if snap.status == trk.STATUS_IDLE:
+ return "Idle", "Waiting for input", "", "text_muted"
+ if snap.status == trk.STATUS_LOCKED:
+ return "Locked", "Screen is locked", "", "text_muted"
+ if snap.status == trk.STATUS_UNSUPPORTED:
+ return "Off", "Tracking needs Windows", "", "text_muted"
+ return "Ready", "Waiting for an app", "", "text_muted"
+
+ def _refresh_status(self) -> None:
+ snap = self._tracker.snapshot()
+ head, subject, clock, tone = self._status_text(snap)
+ live = snap.status == trk.STATUS_TRACKING and snap.app_id is not None
+ self._status.set_status(head, subject, clock, tone, live)
+ if getattr(self, "_tray", None):
+ today = queries.total_ms(queries.today_str(), queries.today_str()) + snap.uncommitted_ms
+ detail = f"{subject} {clock}".strip()
+ self._tray.setToolTip(f"{APP_NAME}: {head.lower()}\n{detail}\nToday: {fmt.duration(today, short=True)}")
+ self._pause_action.setText("Resume tracking" if self._tracker.paused else "Pause tracking")
+
+ def _tick(self) -> None:
+ self._refresh_status()
+ if self.isVisible() and not self.isMinimized():
+ view = self._views[self._current]
+ if hasattr(view, "tick"):
+ view.tick()
+
+ def _slow_tick(self) -> None:
+ snap = self._tracker.snapshot()
+ try:
+ if rewards.enabled() and rewards.evaluate_recent():
+ bus.rewards_changed.emit()
+ fav_live = 0
+ if snap.app_id:
+ app = queries.get_app(snap.app_id)
+ fav_live = snap.uncommitted_ms if app and app.get("is_favorite") else 0
+ streak = rewards.update_streak(extra_ms=fav_live)
+ if streak:
+ msg = f"Streak extended to {streak['streak']} days"
+ if streak.get("reward"):
+ msg += f" ({fmt.reward(streak['reward'], ', ')})"
+ self.notify("Streak", msg)
+ bus.rewards_changed.emit()
+ for app in self._limits.check(snap.app_id, snap.uncommitted_ms):
+ self.notify(
+ "Daily limit reached",
+ f"{app['name']}: {fmt.duration(app['used_ms'], short=True)} today "
+ f"(limit {fmt.duration(app['daily_limit_ms'], short=True)})",
+ tone="warning",
+ )
+ 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."""
+ 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):
+ self._tray.showMessage(title, message, QSystemTrayIcon.MessageIcon.Information, 6000)
- menu = QMenu()
- show_action = QAction("Show AppTrackr", self)
- show_action.triggered.connect(self._tray_show)
- menu.addAction(show_action)
+ # ------------------------------------------------------------------
+ # Tray
+ # ------------------------------------------------------------------
- self._pause_action = QAction("Pause Tracking", self)
- self._pause_action.triggered.connect(self._tray_toggle_pause)
+ def _setup_tray(self) -> None:
+ self._tray = None
+ if not QSystemTrayIcon.isSystemTrayAvailable():
+ return
+ self._tray = QSystemTrayIcon(icons.logo_icon(), self)
+ menu = QMenu(self)
+ menu.addAction(f"Open {APP_NAME}", self.bring_to_front)
+ menu.addSeparator()
+ self._pause_action = QAction("Pause tracking", self)
+ self._pause_action.triggered.connect(self.toggle_pause)
menu.addAction(self._pause_action)
-
+ pause_menu = menu.addMenu("Pause for")
+ for text, minutes in (("15 minutes", 15), ("30 minutes", 30), ("1 hour", 60), ("2 hours", 120)):
+ pause_menu.addAction(text, lambda m=minutes: self.pause_for(m))
menu.addSeparator()
-
- quit_action = QAction("Quit", self)
- quit_action.triggered.connect(self._tray_quit)
- menu.addAction(quit_action)
-
+ menu.addAction("Quit", self.quit)
+ self._tray_menu = menu
self._tray.setContextMenu(menu)
self._tray.activated.connect(self._on_tray_activated)
+ self._tray.messageClicked.connect(self.bring_to_front)
self._tray.show()
- def _tray_show(self):
- self.showNormal()
+ def _on_tray_activated(self, reason) -> None:
+ if reason in (QSystemTrayIcon.ActivationReason.Trigger, QSystemTrayIcon.ActivationReason.DoubleClick):
+ if self.isVisible() and self.isActiveWindow():
+ self.hide()
+ else:
+ self.bring_to_front()
+
+ def has_tray(self) -> bool:
+ return self._tray is not None
+
+ def bring_to_front(self) -> None:
+ self.show()
+ if self.isMinimized():
+ self.showNormal()
+ self.raise_()
self.activateWindow()
+ self.refresh_current()
- def _tray_toggle_pause(self):
- if self._tracker.paused:
- self._tracker.resume()
- self._pause_action.setText("Pause Tracking")
- else:
- self._tracker.pause()
- self._pause_action.setText("Resume Tracking")
-
- def _tray_quit(self):
- self._tracker.stop()
+ def quit(self) -> None:
+ self._quitting = True
+ if self._tray:
+ self._tray.hide()
QApplication.quit()
- def _on_tray_activated(self, reason):
- if reason == QSystemTrayIcon.ActivationReason.DoubleClick:
- self._tray_show()
-
- def closeEvent(self, event):
- minimize_to_tray = db.get_setting("minimize_to_tray", "1") == "1"
- if minimize_to_tray:
+ def closeEvent(self, event) -> None:
+ if not self._quitting and self._tray and db.get_bool("minimize_to_tray", True):
event.ignore()
self.hide()
- self._tray.showMessage("AppTrackr", "Running in background", QSystemTrayIcon.MessageIcon.Information, 2000)
- else:
- self._tracker.stop()
- event.accept()
-
- def _startup_update_check(self):
- if db.get_setting("auto_update_check", "1") != "1":
+ if not db.get_bool("tray_hint_shown"):
+ db.set_setting("tray_hint_shown", True)
+ self._tray.showMessage(
+ APP_NAME,
+ "Still tracking in the background. Right-click the tray icon to quit.",
+ QSystemTrayIcon.MessageIcon.Information,
+ 5000,
+ )
return
+ event.accept()
+ self.quit()
- update_url = db.get_setting("update_url", "").strip()
- if not update_url:
- return
+ def resizeEvent(self, event) -> None:
+ super().resizeEvent(event)
+ if hasattr(self, "toast") and self.toast.isVisible():
+ self.toast.reposition()
+
+ # ------------------------------------------------------------------
+ # Shortcuts
+ # ------------------------------------------------------------------
+
+ def _setup_shortcuts(self) -> None:
+ def add(seq, fn):
+ QShortcut(QKeySequence(seq), self, activated=fn)
+
+ for i, (key, _text, _icon) in enumerate(NAV, start=1):
+ add(f"Ctrl+{i}", lambda k=key: self._nav_buttons[k].isVisible() and self.show_page(k))
+ add("Ctrl+,", lambda: self.show_page("settings"))
+ add("Ctrl+F", self._focus_search)
+ add("Ctrl+Shift+P", self.toggle_pause)
+ add("F5", self.refresh_current)
+ add("Alt+Left", self.go_back)
+ add("Escape", self.go_back)
+ add("Ctrl+Q", self.quit)
+
+ def _focus_search(self) -> None:
+ self.show_page("apps")
+ self._views["apps"].focus_search()
- last_check_day = db.get_setting("last_update_check_day", "")
- from datetime import date
- today = date.today().isoformat()
- if last_check_day == today:
+ # ------------------------------------------------------------------
+ # Theme and updates
+ # ------------------------------------------------------------------
+
+ def apply_theme(self) -> None:
+ if motion.enabled() and self.isVisible():
+ # Crossfade: freeze the old look in an overlay and fade it out over the new one.
+ overlay = QLabel(self.centralWidget())
+ overlay.setPixmap(self.centralWidget().grab())
+ overlay.setGeometry(self.centralWidget().rect())
+ overlay.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ overlay.show()
+ overlay.raise_()
+ motion.fade(overlay, 1.0, 0.0, motion.GENTLE, motion.EASY_EASE, on_done=overlay.deleteLater)
+ apply_app_theme(QApplication.instance())
+ set_dark_titlebar(self, theme.current().dark)
+ for view in self._views.values():
+ view.update()
+ self.refresh_current()
+
+ def showEvent(self, event) -> None:
+ super().showEvent(event)
+ set_dark_titlebar(self, theme.current().dark)
+ if sys.platform.startswith("win") and motion.enabled():
+ self.setWindowOpacity(0.0)
+ motion.tween(self, 0.0, 1.0, motion.FAST, self.setWindowOpacity, motion.DECELERATE, key="window")
+ self._stack.setFocus()
+
+ def _startup_update_check(self) -> None:
+ if self.ctx.demo or not db.get_bool("auto_update_check", True):
+ return
+ today = queries.today_str()
+ if db.get_setting("last_update_check_day") == today:
return
db.set_setting("last_update_check_day", today)
+ url = db.get_setting("update_url", "")
+ run_async(lambda: updater.check_for_update(url), self._on_update_checked, lambda exc: None)
- def worker():
- info = updater_check.check_for_update(update_url)
- if not info:
- return
- version = info.get("version", "?")
-
- def notify():
- self._tray.showMessage(
- "AppTrackr Update",
- f"Version {version} is available. Open Settings > Updates to install.",
- QSystemTrayIcon.MessageIcon.Information,
- 7000,
- )
+ 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")
+
+ def set_update_available(self, info) -> None:
+ self.ctx.update_info = info
+ accent = theme.current().accent_text
+ self._version.setText(
+ f'v{__version__} · Update to {info.version}'
+ )
- QTimer.singleShot(0, notify)
- threading.Thread(target=worker, daemon=True, name="update-check").start()
+def prepare_app(app: QApplication) -> None:
+ """Style, fonts, icon and theme shared by the app and the screenshot scripts."""
+ app.setStyle("Fusion")
+ app.setFont(fonts.sans(13))
+ app.setWindowIcon(icons.logo_icon())
+ apply_app_theme(app)
+
+
+def system_prefers_dark() -> bool:
+ hints = QGuiApplication.styleHints()
+ try:
+ return hints.colorScheme() != Qt.ColorScheme.Light
+ except AttributeError:
+ return True
+
+
+def apply_app_theme(app: QApplication) -> None:
+ theme.configure(
+ db.get_setting("ui_mode", "dark"),
+ db.get_setting("ui_theme", theme.DEFAULT_ACCENT),
+ system_dark=system_prefers_dark(),
+ )
+ app.setPalette(theme.palette())
+ app.setStyleSheet(theme.stylesheet(arrow_icon=_combo_arrow(theme.current().text_dim)))
+ bus.theme_changed.emit()
+
+
+def _combo_arrow(color: str) -> str:
+ """Write a tinted chevron for QComboBox (QSS needs a file path) and return it."""
+ folder = Path(tempfile.gettempdir()) / "apptrackr-ui"
+ folder.mkdir(exist_ok=True)
+ target = folder / f"chevron-{color.lstrip('#')}.svg"
+ if not target.exists():
+ svg = (paths.assets_dir() / "icons" / "chevron-down.svg").read_text(encoding="utf-8")
+ target.write_text(svg.replace("currentColor", color), encoding="utf-8")
+ return target.as_posix()
+
+
+def set_dark_titlebar(window: QWidget, dark: bool) -> None:
+ """Match the Windows title bar to the app theme (Windows 10 20H1+ / 11)."""
+ if not sys.platform.startswith("win"):
+ return
+ try:
+ import ctypes
+
+ value = ctypes.c_int(1 if dark else 0)
+ hwnd = int(window.winId())
+ for attribute in (20, 19): # DWMWA_USE_IMMERSIVE_DARK_MODE (and pre-20H1 value)
+ if ctypes.windll.dwmapi.DwmSetWindowAttribute(hwnd, attribute, ctypes.byref(value), 4) == 0:
+ break
+ except Exception:
+ log.debug("Could not set title bar theme", exc_info=True)
diff --git a/apptrackr/ui/motion.py b/apptrackr/ui/motion.py
new file mode 100644
index 0000000..145b279
--- /dev/null
+++ b/apptrackr/ui/motion.py
@@ -0,0 +1,331 @@
+"""Motion system: duration and easing tokens plus small animation helpers.
+
+Tokens follow Fluent 2 (durations in ms, cubic-bezier curves). Every helper
+respects reduced motion: when animations are off the end state is applied
+immediately, so callers never need a separate code path.
+
+Usage guide:
+- enter / appear DECELERATE, FAST-NORMAL
+- exit / dismiss ACCELERATE, FASTER-FAST
+- move / resize EASY_EASE, NORMAL-GENTLE
+- data change EASY_EASE, SLOW (staggered for series)
+"""
+
+from __future__ import annotations
+
+import sys
+from typing import Callable
+
+from PySide6.QtCore import (
+ QAbstractAnimation,
+ QEasingCurve,
+ QPointF,
+ QRectF,
+ Qt,
+ QTimer,
+ QVariantAnimation,
+)
+from PySide6.QtGui import QColor, QPainter, QPen
+from PySide6.QtWidgets import QGraphicsOpacityEffect, QWidget
+
+# Durations (ms)
+ULTRA_FAST = 50
+FASTER = 100
+FAST = 150
+NORMAL = 200
+GENTLE = 250
+SLOW = 300
+SLOWER = 400
+ULTRA_SLOW = 500
+
+
+def _bezier(x1: float, y1: float, x2: float, y2: float) -> QEasingCurve:
+ curve = QEasingCurve(QEasingCurve.Type.BezierSpline)
+ curve.addCubicBezierSegment(QPointF(x1, y1), QPointF(x2, y2), QPointF(1, 1))
+ return curve
+
+
+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)
+LINEAR = QEasingCurve(QEasingCurve.Type.Linear)
+
+_override: bool | None = None
+_cached: bool | None = None
+# Multiplies every duration and delay. Only the demo recorder changes it, to slow
+# motion down so frame capture can keep up; the GIF is then played back faster.
+time_scale = 1.0
+
+
+# ---------------------------------------------------------------------------
+# Reduced motion
+# ---------------------------------------------------------------------------
+
+
+def system_allows_animation() -> bool:
+ """Windows 'Animation effects' (SPI_GETCLIENTAREAANIMATION); True elsewhere."""
+ if not sys.platform.startswith("win"):
+ return True
+ try:
+ import ctypes
+
+ value = ctypes.c_int(1)
+ if ctypes.windll.user32.SystemParametersInfoW(0x1042, 0, ctypes.byref(value), 0):
+ return bool(value.value)
+ except Exception:
+ pass
+ return True
+
+
+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()
+ return _cached
+
+
+def set_enabled(value: bool | None) -> None:
+ """Persist the user's choice (None returns to following the OS)."""
+ global _cached
+ from ..data import db
+
+ db.set_setting("animations", "" if value is None else value)
+ _cached = None
+
+
+def force(value: bool | None) -> None:
+ """Override for tests and the screenshot script; None clears the override."""
+ global _override
+ _override = value
+
+
+# ---------------------------------------------------------------------------
+# Tweens
+# ---------------------------------------------------------------------------
+
+
+def tween(
+ owner: QWidget,
+ start,
+ end,
+ duration: int,
+ on_value: Callable,
+ easing: QEasingCurve = EASY_EASE,
+ on_done: Callable | None = None,
+ delay: int = 0,
+ key: str | None = None,
+) -> QVariantAnimation | None:
+ """Animate a value from *start* to *end*, calling *on_value* each frame.
+
+ With *key*, a running tween with the same key on *owner* is stopped first,
+ so repeated calls retarget instead of stacking.
+ """
+ if key:
+ current = running(owner, key)
+ if current is not None:
+ current.stop()
+ if not enabled() or duration <= 0 or start == end:
+ on_value(end)
+ if on_done:
+ on_done()
+ return None
+
+ duration = int(duration * time_scale)
+ delay = int(delay * time_scale)
+ anim = QVariantAnimation(owner)
+ anim.setStartValue(start)
+ anim.setEndValue(end)
+ anim.setDuration(duration)
+ anim.setEasingCurve(easing)
+ anim.valueChanged.connect(on_value)
+ if on_done:
+ anim.finished.connect(on_done)
+ if key:
+ setattr(owner, f"_tween_{key}", anim)
+ on_value(start) # apply the first frame now; QVariantAnimation emits on the next tick
+ if delay > 0:
+ QTimer.singleShot(delay, owner, lambda: anim.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped))
+ else:
+ anim.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
+ return anim
+
+
+def running(owner: QWidget, key: str) -> QVariantAnimation | None:
+ """The keyed tween on *owner* if it is still running, else None."""
+ anim = getattr(owner, f"_tween_{key}", None)
+ if anim is None:
+ return None
+ try:
+ return anim if anim.state() == QAbstractAnimation.State.Running else None
+ except RuntimeError: # already deleted after finishing
+ setattr(owner, f"_tween_{key}", None)
+ return None
+
+
+def fade(
+ widget: QWidget,
+ start: float,
+ end: float,
+ duration: int = FAST,
+ easing: QEasingCurve = DECELERATE,
+ on_done: Callable | None = None,
+ delay: int = 0,
+) -> None:
+ """Fade a widget's opacity. The effect is removed when it ends fully opaque."""
+ if not enabled():
+ if on_done:
+ on_done()
+ return
+ effect = widget.graphicsEffect()
+ if not isinstance(effect, QGraphicsOpacityEffect):
+ effect = QGraphicsOpacityEffect(widget)
+ widget.setGraphicsEffect(effect)
+ effect.setOpacity(start)
+
+ def finish():
+ try:
+ if end >= 1.0 and widget.graphicsEffect() is effect:
+ widget.setGraphicsEffect(None)
+ except RuntimeError:
+ return
+ if on_done:
+ on_done()
+
+ tween(widget, start, end, duration, lambda v: _set_opacity(effect, v), easing, finish, delay, key="fade")
+
+
+def _set_opacity(effect: QGraphicsOpacityEffect, value: float) -> None:
+ try:
+ effect.setOpacity(value)
+ except RuntimeError:
+ pass
+
+
+def stagger_in(widgets: list[QWidget], step: int = 22, duration: int = FAST, limit: int = 12) -> None:
+ """Fade a list of freshly added widgets in one after another."""
+ if not enabled():
+ return
+ for i, widget in enumerate(widgets[:limit]):
+ fade(widget, 0.0, 1.0, duration, DECELERATE, delay=i * step)
+
+
+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*."""
+ if not enabled():
+ on_done()
+ return
+ 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")
+
+
+def _set_max_height(widget: QWidget, value: float) -> None:
+ try:
+ widget.setMaximumHeight(int(value))
+ except RuntimeError:
+ pass
+
+
+class _Flash(QWidget):
+ """Transparent overlay that glows the parent's outline and fades away."""
+
+ def __init__(self, parent: QWidget, color: QColor, radius: float):
+ super().__init__(parent)
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self._color = color
+ self._radius = radius
+ self._strength = 1.0
+ self.setGeometry(parent.rect())
+ self.show()
+ self.raise_()
+
+ def set_strength(self, value: float) -> None:
+ self._strength = value
+ self.update()
+
+ def paintEvent(self, _event):
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ fill = QColor(self._color)
+ fill.setAlphaF(0.14 * self._strength)
+ edge = QColor(self._color)
+ edge.setAlphaF(0.9 * self._strength)
+ p.setPen(QPen(edge, 2))
+ p.setBrush(fill)
+ p.drawRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1), self._radius, self._radius)
+
+
+def flash(widget: QWidget, color: str | None = None, radius: float = 12, duration: int = ULTRA_SLOW * 2) -> None:
+ """Briefly highlight a widget to confirm an action (a build, a claim)."""
+ if not enabled():
+ return
+ from . import theme
+
+ overlay = _Flash(widget, QColor(color or theme.current().accent), radius)
+ tween(overlay, 1.0, 0.0, duration, overlay.set_strength, DECELERATE, overlay.deleteLater)
+
+
+# ---------------------------------------------------------------------------
+# Widgets
+# ---------------------------------------------------------------------------
+
+
+class PulseDot(QWidget):
+ """Small dot with a breathing halo, used to signal live tracking."""
+
+ def __init__(self, size: int = 10, parent=None):
+ super().__init__(parent)
+ self._phase = 0.0
+ self._active = False
+ self._color = QColor("#10d9a3")
+ self.setFixedSize(size * 2, size * 2)
+ self._anim = QVariantAnimation(self)
+ self._anim.setStartValue(0.0)
+ self._anim.setEndValue(1.0)
+ self._anim.setDuration(int(1600 * time_scale))
+ self._anim.setLoopCount(-1)
+ self._anim.valueChanged.connect(self._set_phase)
+
+ def set_state(self, active: bool, color: str) -> None:
+ """Called on every UI tick; also picks up changes to the animation setting."""
+ self._color = QColor(color)
+ self._active = active
+ should_run = active and enabled()
+ is_running = self._anim.state() == QAbstractAnimation.State.Running
+ if should_run and not is_running:
+ self._anim.start()
+ elif not should_run and is_running:
+ self._anim.stop()
+ self._phase = 0.0
+ self.update()
+
+ def _set_phase(self, value: float) -> None:
+ self._phase = value
+ self.update()
+
+ def paintEvent(self, _event):
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ c = self.rect().center()
+ r = self.width() / 4
+ if self._active and self._anim.state() == QAbstractAnimation.State.Running:
+ halo = QColor(self._color)
+ halo.setAlphaF(0.45 * (1 - self._phase))
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(halo)
+ hr = r * (1 + self._phase)
+ p.drawEllipse(QPointF(c), hr, hr)
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(self._color)
+ p.drawEllipse(QPointF(c), r, r)
+
+
+def lerp(a: float, b: float, t: float) -> float:
+ return a + (b - a) * t
diff --git a/apptrackr/ui/signals.py b/apptrackr/ui/signals.py
new file mode 100644
index 0000000..8e82801
--- /dev/null
+++ b/apptrackr/ui/signals.py
@@ -0,0 +1,62 @@
+"""Application-wide Qt signals and a helper for running work off the GUI thread."""
+
+from __future__ import annotations
+
+import logging
+import threading
+from typing import Any, Callable
+
+from PySide6.QtCore import QObject, Signal
+
+log = logging.getLogger(__name__)
+
+
+class Bus(QObject):
+ theme_changed = Signal()
+ data_changed = Signal() # app metadata, history or restore
+ rewards_changed = Signal()
+ toast = Signal(str, str) # message, tone
+
+
+bus = Bus()
+
+
+class _Relay(QObject):
+ done = Signal(object)
+ failed = Signal(object)
+
+
+_active: set[_Relay] = set()
+
+
+def run_async(
+ fn: Callable[[], Any],
+ on_done: Callable[[Any], None] | None = None,
+ on_error: Callable[[BaseException], None] | None = None,
+) -> None:
+ """Run *fn* on a worker thread and deliver the result on the GUI thread."""
+ relay = _Relay()
+ _active.add(relay)
+
+ def finish(callback, value):
+ _active.discard(relay)
+ if callback:
+ callback(value)
+
+ relay.done.connect(lambda v: finish(on_done, v))
+ relay.failed.connect(lambda e: finish(on_error, e))
+
+ def worker():
+ try:
+ result = fn()
+ except BaseException as exc: # delivered to the caller
+ log.debug("Background task failed", exc_info=True)
+ relay.failed.emit(exc)
+ else:
+ relay.done.emit(result)
+ finally:
+ from ..data import db
+
+ db.close()
+
+ threading.Thread(target=worker, daemon=True, name="ui-task").start()
diff --git a/apptrackr/ui/theme.py b/apptrackr/ui/theme.py
index d111821..dac8931 100644
--- a/apptrackr/ui/theme.py
+++ b/apptrackr/ui/theme.py
@@ -1,334 +1,374 @@
-"""Neon theme system for the AppTrackr PySide6 UI."""
+"""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.
+"""
from __future__ import annotations
-# -- Palette --
-BG_DARKEST = "#000000"
-BG_DARK = "#0b0f1a"
-BG_CARD = "#111827"
-BG_CARD_ALT = "#1a2332"
-BG_HOVER = "#1e293b"
-BG_INPUT = "#0f172a"
-TEXT_COLOR = "#ffffff"
-
-# Default accent colors
-CYAN = "#06d6a0"
-CYAN_DIM = "#0a9e78"
-PURPLE = "#a855f7"
-PURPLE_DIM = "#7c3aed"
-PINK = "#ec4899"
-BLUE = "#3b82f6"
-YELLOW = "#fbbf24"
-RED = "#ef4444"
-GREEN = "#22c55e"
-
-# Active theme accent (can be changed)
-_ACTIVE_ACCENT = CYAN
-_ACTIVE_ACCENT_DIM = CYAN_DIM
-
-# Theme presets
-THEME_PRESETS = {
- "Cyan": ("#06d6a0", "#0a9e78"),
- "Purple": ("#a855f7", "#7c3aed"),
- "Pink": ("#ec4899", "#be185d"),
- "Blue": ("#3b82f6", "#2563eb"),
- "Green": ("#22c55e", "#16a34a"),
- "Red": ("#ef4444", "#dc2626"),
- "Orange": ("#f97316", "#ea580c"),
- "Amber": ("#fbbf24", "#f59e0b"),
+from dataclasses import dataclass, replace
+
+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.
+ACCENTS = {
+ "Orange": "#ff6b1a",
+ "Amber": "#f2b01e",
+ "Red": "#f04e4e",
+ "Pink": "#ec5f9c",
+ "Purple": "#9d7bff",
+ "Blue": "#4c8dff",
+ "Cyan": "#22c3a6",
+ "Green": "#47c46b",
+}
+DEFAULT_ACCENT = "Orange"
+MODES = ("dark", "light", "system")
+
+RADIUS_PANEL = 6
+RADIUS_CONTROL = 4
+
+
+def _mix(a: str, b: str, t: float) -> str:
+ """Blend colour *a* toward *b* by *t* (0..1)."""
+ ca, cb = QColor(a), QColor(b)
+ return QColor(
+ round(ca.red() + (cb.red() - ca.red()) * t),
+ round(ca.green() + (cb.green() - ca.green()) * t),
+ round(ca.blue() + (cb.blue() - ca.blue()) * t),
+ ).name()
+
+
+def _luminance(c: QColor) -> float:
+ def lin(v: float) -> float:
+ return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4
+
+ return 0.2126 * lin(c.redF()) + 0.7152 * lin(c.greenF()) + 0.0722 * lin(c.blueF())
+
+
+def contrast(a: str, b: str) -> float:
+ la, lb = sorted((_luminance(QColor(a)), _luminance(QColor(b))), reverse=True)
+ return (la + 0.05) / (lb + 0.05)
+
+
+@dataclass(frozen=True)
+class Theme:
+ dark: bool
+ window: str
+ sidebar: str
+ surface: str
+ surface_alt: str
+ hover: str
+ input: str
+ border: str
+ border_strong: str
+ text: str
+ text_dim: str
+ text_muted: str
+ track: str
+ ink: str # neutral data marks
+ grid: str # graph-paper dots
+ accent: str = ACCENTS[DEFAULT_ACCENT]
+ gold: str = "#e9a923"
+ danger: str = "#f04e4e"
+ warning: str = "#f2a516"
+ success: str = "#47c46b"
+
+ def accent_soft(self, alpha: float = 0.16) -> str:
+ c = QColor(self.accent)
+ return f"rgba({c.red()}, {c.green()}, {c.blue()}, {alpha})"
+
+ @property
+ def accent_hover(self) -> str:
+ c = QColor(self.accent)
+ return (c.lighter(110) if self.dark else c.darker(108)).name()
+
+ @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
+
+ @property
+ def on_accent(self) -> str:
+ """Ink or white, whichever reads better on an accent fill."""
+ ink, white = "#14120f", "#ffffff"
+ return ink if contrast(self.accent, ink) >= contrast(self.accent, white) else white
+
+ def heat(self, level: int, today: bool = False) -> str:
+ """Quantized calendar ramp: 0 = empty, 1..4 = ink steps. Today uses the signal hue."""
+ if level <= 0:
+ return self.track
+ top = self.accent if today else self.text_dim
+ return _mix(self.surface, top, (0.22, 0.42, 0.66, 0.9 if not today else 1.0)[min(level, 4) - 1])
+
+ def color(self, name: str) -> QColor:
+ return QColor(getattr(self, name))
+
+
+GRAPHITE = Theme(
+ dark=True,
+ window="#121210",
+ sidebar="#0e0e0c",
+ surface="#191917",
+ surface_alt="#21201d",
+ hover="#292825",
+ input="#151513",
+ border="#2b2a26",
+ border_strong="#3b3a35",
+ text="#edebe4",
+ text_dim="#aaa79d",
+ text_muted="#77746b",
+ track="#25241f",
+ ink="#6b6860",
+ grid="#23221f",
+)
+
+PAPER = Theme(
+ dark=False,
+ window="#f2f0ea",
+ sidebar="#ebe8e0",
+ surface="#faf9f5",
+ surface_alt="#f1eee7",
+ hover="#e9e5dc",
+ input="#fdfcf9",
+ border="#ddd8cd",
+ border_strong="#c8c2b5",
+ text="#191814",
+ text_dim="#4f4c44",
+ text_muted="#7f7b71",
+ track="#e7e3d9",
+ ink="#aca595",
+ grid="#e0dcd2",
+ gold="#b9800a",
+ danger="#d23b30",
+ warning="#b86e00",
+ success="#2a8a47",
+)
+
+# 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.
+CATEGORY_COLORS = {
+ "Work": ("#2a78d6", "#3987e5"),
+ "Development": ("#1baf7a", "#199e70"),
+ "Communication": ("#eda100", "#c98500"),
+ "Study": ("#4a3aa7", "#9085e9"),
+ "Social": ("#008300", "#008300"),
+ "Games": ("#e87ba4", "#d55181"),
+ "Entertainment": ("#e34948", "#e66767"),
+ "Tools": ("#8c6d1f", "#9c7a25"),
+ None: ("#a39e92", "#5e5b54"),
}
+_current = GRAPHITE
+_mode = "dark"
+_accent_name = DEFAULT_ACCENT
-def set_theme(theme_name: str) -> None:
- """Set active theme accent color."""
- global _ACTIVE_ACCENT, _ACTIVE_ACCENT_DIM
- if theme_name in THEME_PRESETS:
- _ACTIVE_ACCENT, _ACTIVE_ACCENT_DIM = THEME_PRESETS[theme_name]
-
-
-def get_accent() -> str:
- """Get current active accent color."""
- return _ACTIVE_ACCENT
+def current() -> Theme:
+ return _current
-def get_accent_dim() -> str:
- """Get current active accent dim color."""
- return _ACTIVE_ACCENT_DIM
-TEXT = "#e2e8f0"
-TEXT_DIM = "#94a3b8"
-TEXT_MUTED = "#64748b"
+def mode() -> str:
+ return _mode
-BORDER = "#1e293b"
-# -- Glow shadow CSS --
-def glow(color: str = None, radius: int = 12, spread: int = 2) -> str:
- """Return a QSS drop-shadow string for glow effects."""
- # Qt doesn't support box-shadow natively; we use border + color trick
- if color is None:
- color = get_accent()
- return f"border: 1px solid {color};"
+def accent_name() -> str:
+ return _accent_name
-# -- Global stylesheet --
-def get_stylesheet() -> str:
- """Generate stylesheet with current theme accent colors."""
- accent = get_accent()
- accent_dim = get_accent_dim()
-
- return f"""
-/* ---- Global ---- */
-QWidget {{
- color: {TEXT};
- font-family: "Segoe UI", "Inter", sans-serif;
- font-size: 13px;
-}}
+def category_color(category: str | None) -> str:
+ light, dark = CATEGORY_COLORS.get(category, CATEGORY_COLORS[None])
+ return dark if _current.dark else light
-QMainWindow {{
- background-color: {BG_DARKEST};
-}}
-QStackedWidget, QStackedWidget > QWidget {{
- background-color: {BG_DARK};
-}}
-
-/* ---- Scroll bars ---- */
-QScrollBar:vertical {{
- background: {BG_DARK};
- width: 8px;
- margin: 0;
-}}
-QScrollBar::handle:vertical {{
- background: {TEXT_MUTED};
- min-height: 30px;
- border-radius: 4px;
-}}
-QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{
- height: 0;
-}}
-QScrollBar:horizontal {{
- background: {BG_DARK};
- height: 8px;
-}}
-QScrollBar::handle:horizontal {{
- background: {TEXT_MUTED};
- min-width: 30px;
- border-radius: 4px;
-}}
+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."""
+ global _current, _mode, _accent_name
+ if mode in MODES:
+ _mode = mode
+ if accent in ACCENTS:
+ _accent_name = accent
+ dark = system_dark if _mode == "system" else _mode == "dark"
+ _current = replace(GRAPHITE if dark else PAPER, accent=ACCENTS[_accent_name])
+ return _current
-/* ---- Buttons ---- */
-QPushButton {{
- background-color: {BG_CARD};
- color: {TEXT};
- border: 1px solid {BORDER};
- border-radius: 6px;
- padding: 8px 18px;
- font-weight: 600;
-}}
-QPushButton:hover {{
- background-color: {BG_HOVER};
- border-color: {accent};
- color: {accent};
-}}
-QPushButton:pressed {{
- background-color: {BG_CARD_ALT};
-}}
-QPushButton#primary {{
- background-color: {accent_dim};
- color: {TEXT_COLOR};
- border-color: {accent};
-}}
-QPushButton#primary:hover {{
- background-color: {accent};
-}}
-/* ---- Labels ---- */
-QLabel {{
- background: transparent;
-}}
-QLabel#heading {{
- font-size: 20px;
- font-weight: 700;
- color: {TEXT};
-}}
-QLabel#subheading {{
- font-size: 14px;
- color: {TEXT_DIM};
-}}
-QLabel#accent {{
- color: {accent};
- font-weight: 600;
-}}
-QLabel#value-large {{
- font-size: 28px;
- font-weight: 700;
- color: {accent};
-}}
+def palette(t: Theme | None = None) -> QPalette:
+ """QPalette matching the theme, for widgets the stylesheet does not reach."""
+ t = t or _current
+ p = QPalette()
+ role = QPalette.ColorRole
+ p.setColor(role.Window, QColor(t.window))
+ p.setColor(role.WindowText, QColor(t.text))
+ p.setColor(role.Base, QColor(t.input))
+ p.setColor(role.AlternateBase, QColor(t.surface_alt))
+ p.setColor(role.Text, QColor(t.text))
+ p.setColor(role.Button, QColor(t.surface_alt))
+ p.setColor(role.ButtonText, QColor(t.text))
+ p.setColor(role.Highlight, QColor(t.accent))
+ p.setColor(role.HighlightedText, QColor(t.on_accent))
+ p.setColor(role.ToolTipBase, QColor(t.surface_alt))
+ p.setColor(role.ToolTipText, QColor(t.text))
+ p.setColor(role.PlaceholderText, QColor(t.text_muted))
+ p.setColor(role.Link, QColor(t.accent_text))
+ for r in (role.Text, role.ButtonText, role.WindowText):
+ p.setColor(QPalette.ColorGroup.Disabled, r, QColor(t.text_muted))
+ return p
-/* ---- Line edit ---- */
-QLineEdit {{
- background-color: {BG_INPUT};
- border: 1px solid {BORDER};
- border-radius: 6px;
- padding: 8px 12px;
- color: {TEXT};
-}}
-QLineEdit:focus {{
- border-color: {accent};
-}}
-/* ---- Combo box ---- */
-QComboBox {{
- background-color: {BG_INPUT};
- border: 1px solid {BORDER};
- border-radius: 6px;
- padding: 6px 12px;
- color: {TEXT};
-}}
-QComboBox:hover {{
- border-color: {accent};
-}}
-QComboBox::drop-down {{
- border: none;
- width: 20px;
-}}
+def stylesheet(t: Theme | None = None, arrow_icon: str = "") -> str:
+ """Global QSS. *arrow_icon* is a file path for the combo box arrow image."""
+ t = t or _current
+ rp, rc = RADIUS_PANEL, RADIUS_CONTROL
+ return f"""
+QWidget {{ color: {t.text}; }}
+QMainWindow, QDialog, QMessageBox {{ background: {t.window}; }}
+QScrollArea {{ background: transparent; border: none; }}
+
+/* Sidebar */
+QWidget#sidebar {{ background: {t.sidebar}; border-right: 1px solid {t.border}; }}
+QPushButton[nav="true"] {{
+ background: transparent; color: {t.text_dim}; border: 1px solid transparent; border-radius: {rc}px;
+ text-align: left; padding: 0 10px; font-size: 13px; font-weight: 500;
+}}
+QPushButton[nav="true"]:hover {{ background: {t.hover}; color: {t.text}; }}
+QPushButton[nav="true"]:checked {{ background: {t.surface_alt}; color: {t.text}; border-color: {t.border}; }}
+QPushButton[nav="true"]:focus {{ border-color: {t.accent}; }}
+QFrame#navIndicator {{ background: {t.accent}; border: none; border-radius: 1px; }}
+QLabel#navKey {{ color: {t.text_muted}; border: 1px solid {t.border}; border-radius: 3px; }}
+QLabel#navBadge {{
+ background: {t.accent}; color: {t.on_accent}; border-radius: 3px; padding: 0 5px;
+}}
+
+/* Typography (mono roles get their font in code; see widgets.components.label) */
+QLabel {{ background: transparent; }}
+QLabel[role="title"] {{ font-size: 24px; font-weight: 600; }}
+QLabel[role="subtitle"] {{ font-size: 13px; color: {t.text_dim}; }}
+QLabel[role="eyebrow"], QLabel[role="tick"] {{ color: {t.text_muted}; }}
+QLabel[role="eyebrowAccent"] {{ color: {t.accent_text}; }}
+QLabel[role="heading"] {{ font-size: 15px; font-weight: 600; }}
+QLabel[role="value"] {{ font-size: 28px; font-weight: 600; }}
+QLabel[role="hero"] {{ font-size: 44px; font-weight: 600; color: {t.text}; }}
+QLabel[role="dim"] {{ color: {t.text_dim}; }}
+QLabel[role="muted"] {{ color: {t.text_muted}; }}
+QLabel[role="caption"] {{ color: {t.text_muted}; font-size: 12px; }}
+QLabel[role="accent"] {{ color: {t.accent_text}; font-weight: 600; }}
+QLabel[role="danger"] {{ color: {t.danger}; font-weight: 600; }}
+QLabel[role="warning"] {{ color: {t.warning}; font-weight: 600; }}
+QLabel[role="success"] {{ color: {t.success}; font-weight: 600; }}
+QLabel[role="pill"] {{
+ background: transparent; border: 1px solid {t.border_strong}; border-radius: 3px;
+ color: {t.text_dim}; padding: 1px 6px;
+}}
+QLabel[role="pillAccent"] {{
+ background: {t.accent_soft(0.14)}; border: 1px solid {t.accent_soft(0.45)}; border-radius: 3px;
+ color: {t.accent_text}; padding: 1px 6px;
+}}
+QLabel[role="pillDanger"] {{
+ background: transparent; border: 1px solid {t.danger}; border-radius: 3px; color: {t.danger}; padding: 1px 6px;
+}}
+QLabel#kbd {{
+ background: {t.surface_alt}; border: 1px solid {t.border_strong}; border-bottom-width: 2px;
+ border-radius: 3px; padding: 1px 6px; color: {t.text_dim};
+}}
+
+/* Surfaces */
+QFrame[card="true"] {{ background: {t.surface}; border: 1px solid {t.border}; border-radius: {rp}px; }}
+QFrame[card="true"] QLabel {{ border: none; }}
+QFrame[cell="true"] {{ background: transparent; border: none; }}
+QFrame[row="true"] {{ background: transparent; border: none; border-radius: {rc}px; }}
+QFrame[row="true"]:hover {{ background: {t.hover}; }}
+QFrame[divider="true"] {{ background: {t.border}; border: none; min-height: 1px; max-height: 1px; }}
+QFrame[vdivider="true"] {{ background: {t.border}; border: none; min-width: 1px; max-width: 1px; }}
+QFrame[banner="true"] {{
+ background: {t.accent_soft(0.08)}; border: 1px solid {t.accent_soft(0.4)}; border-radius: {rp}px;
+}}
+
+/* Buttons */
+QPushButton, QToolButton {{
+ background: transparent; color: {t.text}; border: 1px solid {t.border_strong};
+ border-radius: {rc}px; padding: 6px 12px; font-weight: 500;
+}}
+QPushButton:hover, QToolButton:hover {{ background: {t.hover}; border-color: {t.text_muted}; }}
+QPushButton:pressed, QToolButton:pressed {{ background: {t.border}; }}
+QPushButton:focus, QToolButton:focus {{ border-color: {t.accent}; }}
+QPushButton:disabled, QToolButton:disabled {{ color: {t.text_muted}; border-color: {t.border}; background: transparent; }}
+QPushButton:checked {{ background: {t.accent_soft(0.12)}; border-color: {t.accent_soft(0.55)}; }}
+QPushButton[kind="primary"] {{ background: {t.accent}; color: {t.on_accent}; border: 1px solid {t.accent}; font-weight: 600; }}
+QPushButton[kind="primary"]:hover {{ background: {t.accent_hover}; border-color: {t.accent_hover}; }}
+QPushButton[kind="primary"]:focus {{ border: 1px solid {t.text}; }}
+QPushButton[kind="primary"]:disabled {{ background: transparent; color: {t.text_muted}; border-color: {t.border}; }}
+QPushButton[kind="ghost"], QToolButton[kind="ghost"] {{ background: transparent; border: 1px solid transparent; color: {t.text_dim}; }}
+QPushButton[kind="ghost"]:hover, QToolButton[kind="ghost"]:hover {{ background: {t.hover}; color: {t.text}; }}
+QPushButton[kind="ghost"]:focus, QToolButton[kind="ghost"]:focus {{ border-color: {t.accent}; }}
+QPushButton[kind="ghost"]:checked {{ background: {t.accent_soft(0.12)}; color: {t.text}; }}
+QPushButton[kind="danger"] {{ color: {t.danger}; }}
+QPushButton[kind="link"] {{ background: transparent; border: none; color: {t.accent_text}; padding: 2px 0; font-weight: 500; }}
+QPushButton[kind="link"]:hover {{ text-decoration: underline; background: transparent; }}
+QToolButton::menu-indicator {{ image: none; width: 0; }}
+
+/* Segmented control */
+QFrame[segmented="true"] {{ background: {t.input}; border: 1px solid {t.border}; border-radius: {rc + 1}px; }}
+QPushButton[segment="true"] {{
+ background: transparent; border: 1px solid transparent; border-radius: {rc - 1}px;
+ color: {t.text_dim}; padding: 4px 12px; font-weight: 500;
+}}
+QPushButton[segment="true"]:hover {{ color: {t.text}; background: transparent; }}
+QPushButton[segment="true"]:checked {{ background: transparent; color: {t.text}; border-color: transparent; }}
+QFrame#segThumb {{ background: {t.surface_alt}; border: 1px solid {t.border_strong}; border-radius: {rc - 1}px; }}
+QPushButton[segment="true"]:focus {{ border-color: {t.accent}; }}
+
+/* Inputs */
+QLineEdit, QComboBox, QSpinBox {{
+ background: {t.input}; border: 1px solid {t.border_strong}; border-radius: {rc}px;
+ padding: 6px 10px; selection-background-color: {t.accent}; selection-color: {t.on_accent};
+}}
+QLineEdit:hover, QComboBox:hover, QSpinBox:hover {{ border-color: {t.text_muted}; }}
+QLineEdit:focus, QComboBox:focus, QSpinBox:focus {{ border-color: {t.accent}; }}
+QComboBox {{ padding-right: 28px; }}
+QComboBox::drop-down {{ subcontrol-origin: padding; subcontrol-position: center right; width: 26px; border: none; background: transparent; }}
+QComboBox::down-arrow {{ image: url("{arrow_icon}"); width: 14px; height: 14px; }}
QComboBox QAbstractItemView {{
- background-color: {BG_CARD};
- border: 1px solid {BORDER};
- color: {TEXT};
- selection-background-color: {BG_HOVER};
-}}
-
-/* ---- Tab widget ---- */
-QTabWidget::pane {{
- border: none;
- background: {BG_DARK};
-}}
-QTabBar::tab {{
- background: {BG_CARD};
- color: {TEXT_DIM};
- padding: 10px 20px;
- margin-right: 2px;
- border-top-left-radius: 6px;
- border-top-right-radius: 6px;
- font-weight: 600;
-}}
-QTabBar::tab:selected {{
- background: {BG_DARK};
- color: {accent};
- border-bottom: 2px solid {accent};
-}}
-QTabBar::tab:hover {{
- color: {TEXT};
-}}
-
-/* ---- Progress bar ---- */
-QProgressBar {{
- background: {BG_CARD};
- border: 1px solid {BORDER};
- border-radius: 4px;
- text-align: center;
- color: {TEXT};
- height: 18px;
-}}
-QProgressBar::chunk {{
- background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 {accent}, stop:1 {PURPLE});
- border-radius: 3px;
-}}
-
-/* ---- Slider ---- */
-QSlider::groove:horizontal {{
- background: {BG_CARD};
- height: 6px;
- border-radius: 3px;
-}}
-QSlider::handle:horizontal {{
- background: {accent};
- width: 16px;
- height: 16px;
- margin: -5px 0;
- border-radius: 8px;
-}}
-
-/* ---- Check box ---- */
-QCheckBox {{
- spacing: 8px;
- background: transparent;
-}}
-QCheckBox::indicator {{
- width: 18px;
- height: 18px;
- border-radius: 4px;
- border: 1px solid {BORDER};
- background: {BG_INPUT};
-}}
-QCheckBox::indicator:checked {{
- background: {accent};
- border-color: {accent};
-}}
-
-/* ---- Spin box ---- */
-QSpinBox {{
- background-color: {BG_INPUT};
- border: 1px solid {BORDER};
- border-radius: 6px;
- padding: 6px 12px;
- color: {TEXT};
-}}
-QSpinBox:focus {{
- border-color: {accent};
-}}
-
-/* ---- Tool tip ---- */
+ background: {t.surface}; border: 1px solid {t.border_strong}; border-radius: {rc}px; padding: 4px;
+ selection-background-color: {t.hover}; selection-color: {t.text}; outline: none;
+}}
+
+/* Progress */
+QProgressBar {{ background: {t.track}; border: none; border-radius: 2px; max-height: 4px; min-height: 4px; }}
+QProgressBar::chunk {{ background: {t.ink}; border-radius: 2px; }}
+QProgressBar[tone="accent"]::chunk {{ background: {t.accent}; }}
+QProgressBar[tone="danger"]::chunk {{ background: {t.danger}; }}
+QProgressBar[tone="gold"]::chunk {{ background: {t.gold}; }}
+
+/* Scroll bars */
+QScrollBar:vertical {{ background: transparent; width: 8px; margin: 2px; }}
+QScrollBar::handle:vertical {{ background: {t.border_strong}; min-height: 32px; border-radius: 2px; }}
+QScrollBar::handle:vertical:hover {{ background: {t.text_muted}; }}
+QScrollBar:horizontal {{ background: transparent; height: 8px; margin: 2px; }}
+QScrollBar::handle:horizontal {{ background: {t.border_strong}; min-width: 32px; border-radius: 2px; }}
+QScrollBar::add-line, QScrollBar::sub-line {{ width: 0; height: 0; }}
+QScrollBar::add-page, QScrollBar::sub-page {{ background: transparent; }}
+
+/* Popups */
QToolTip {{
- background: {BG_CARD};
- color: {TEXT};
- border: 1px solid {accent_dim};
- padding: 6px;
- border-radius: 4px;
-}}
-
-/* ---- Separator ---- */
-QFrame[frameShape="4"], QFrame[frameShape="5"] {{
- color: {BORDER};
- max-height: 1px;
-}}
-
-/* ---- Menu ---- */
-QMenu {{
- background: {BG_CARD};
- border: 1px solid {BORDER};
- padding: 4px;
-}}
-QMenu::item {{
- padding: 6px 24px;
- border-radius: 4px;
-}}
-QMenu::item:selected {{
- background: {BG_HOVER};
- color: {accent};
-}}
+ background: {t.surface_alt}; color: {t.text}; border: 1px solid {t.border_strong};
+ border-radius: {rc}px; padding: 6px 8px;
+}}
+QMenu {{ background: {t.surface}; border: 1px solid {t.border_strong}; border-radius: {rp}px; padding: 4px; }}
+QMenu::item {{ padding: 6px 22px 6px 12px; border-radius: {rc - 1}px; }}
+QMenu::item:selected {{ background: {t.hover}; }}
+QMenu::item:disabled {{ color: {t.text_muted}; }}
+QMenu::separator {{ height: 1px; background: {t.border}; margin: 4px 6px; }}
+QProgressDialog QLabel {{ padding: 4px; }}
+
+/* Toast */
+QFrame#toast {{ background: {t.surface_alt}; border: 1px solid {t.border_strong}; border-left: 3px solid {t.accent}; border-radius: {rc}px; }}
+QFrame#toast QLabel {{ color: {t.text}; }}
"""
-
-
-# Keep backward compatibility
-GLOBAL_QSS = get_stylesheet()
-
-
-def format_ms(ms: int) -> str:
- """Format milliseconds to human-readable string like '2h 15m'."""
- if ms < 0:
- ms = 0
- seconds = ms // 1000
- if seconds < 60:
- return f"{seconds}s"
- minutes = seconds // 60
- if minutes < 60:
- return f"{minutes}m"
- hours = minutes // 60
- mins = minutes % 60
- if hours < 24:
- return f"{hours}h {mins}m" if mins else f"{hours}h"
- days = hours // 24
- hrs = hours % 24
- return f"{days}d {hrs}h" if hrs else f"{days}d"
diff --git a/apptrackr/ui/views/app_detail.py b/apptrackr/ui/views/app_detail.py
index d430cdf..3761246 100644
--- a/apptrackr/ui/views/app_detail.py
+++ b/apptrackr/ui/views/app_detail.py
@@ -1,217 +1,373 @@
-"""App detail view – trends, history histogram, goals."""
+"""App detail: totals, 30-day history, limit, rewards and recent sessions for one app."""
from __future__ import annotations
-from datetime import date, timedelta
+from datetime import date, datetime
-from PySide6.QtCore import Qt, Signal
-from PySide6.QtGui import QColor, QPainter, QPen
+from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
- QScrollArea, QFrame, QCheckBox,
+ QComboBox,
+ QGridLayout,
+ QHBoxLayout,
+ QInputDialog,
+ QMenu,
+ QPushButton,
+ QVBoxLayout,
+ QWidget,
)
-from .. import theme
-from ..widgets.components import NeonCard, StatValue, GradientBar
-from ...data import queries
+from ...data import catalog, queries
+from ...rewards import engine as rewards
+from ...rewards import rules
+from .. import fmt, motion
+from ..signals import bus
+from ..widgets.charts import Bar, BarChart
+from ..widgets.components import (
+ AppAvatar,
+ Card,
+ EmptyState,
+ IconBinding,
+ MetricGrid,
+ Page,
+ SettingRow,
+ StatTile,
+ Toggle,
+ button,
+ clear_layout,
+ divider,
+ 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),
+)
+MINUTE = 60_000
-class BarChartWidget(QWidget):
- """Simple bar chart for daily history."""
- def __init__(self, parent=None):
+class AppDetailView(Page):
+ def __init__(self, ctx, parent=None):
super().__init__(parent)
- self._data: list[tuple[str, int]] = [] # (day, ms)
- self.setMinimumHeight(160)
- self.setStyleSheet("background: transparent;")
-
- def set_data(self, data: list[tuple[str, int]]):
- self._data = data
- self.update()
-
- def paintEvent(self, event):
- if not self._data:
+ self.setObjectName("page")
+ self.ctx = ctx
+ self.app_id: int | None = None
+
+ self.back = button("Back", kind="ghost", icon="arrow-left", tooltip="Back (Esc)", on_click=ctx.window.go_back)
+ back_row = QHBoxLayout()
+ back_row.addWidget(self.back)
+ back_row.addStretch(1)
+ self.add(back_row)
+
+ head = QHBoxLayout()
+ head.setSpacing(14)
+ self.avatar = AppAvatar("", None, 48)
+ head.addWidget(self.avatar)
+ names = QVBoxLayout()
+ names.setSpacing(3)
+ self.kicker = label("", "eyebrowAccent")
+ names.addWidget(self.kicker)
+ self.title = label("", "title")
+ names.addWidget(self.title)
+ self.subtitle = label("", "subtitle")
+ self.subtitle.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
+ names.addWidget(self.subtitle)
+ head.addLayout(names, 1)
+ self.fav_btn = QPushButton("Favorite")
+ self.fav_btn.setCheckable(True)
+ self.fav_btn.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.fav_btn.setFocusPolicy(Qt.FocusPolicy.TabFocus)
+ IconBinding.attach(self.fav_btn, "star", "text_dim", checked_tone="gold")
+ self.fav_btn.clicked.connect(self._toggle_favorite)
+ head.addWidget(self.fav_btn)
+ self.more_btn = button("", icon="ellipsis", tooltip="More actions")
+ self.more_btn.clicked.connect(self._more_menu)
+ head.addWidget(self.more_btn)
+ self.add(head)
+
+ self.t_today = StatTile("Today", framed=False)
+ self.t_week = StatTile("Last 7 days", framed=False)
+ self.t_month = StatTile("Last 30 days", framed=False)
+ self.t_avg = StatTile("Daily average", framed=False)
+ self.add(MetricGrid([self.t_today, self.t_week, self.t_month, self.t_avg], columns=4))
+
+ self.chart_card = Card("Last 30 days", "Focused time per day", index=1)
+ self.chart = BarChart(180)
+ self.chart_card.body.addWidget(self.chart)
+ self.add(self.chart_card)
+
+ cols = self.stack_when_narrow(QHBoxLayout())
+ cols.setSpacing(16)
+ left = QVBoxLayout()
+ left.setSpacing(16)
+
+ self.settings_card = Card("Settings", index=2)
+ self.category = QComboBox()
+ self.category.addItem("Uncategorized", None)
+ for cat in queries.CATEGORIES:
+ self.category.addItem(cat, cat)
+ self.category.currentIndexChanged.connect(self._on_category)
+ self.settings_card.body.addWidget(
+ 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.rewards_divider = divider()
+ self.settings_card.body.addWidget(self.rewards_divider)
+ self.rewards_toggle = Toggle()
+ self.rewards_toggle.toggled.connect(self._on_rewards)
+ self.rewards_row = SettingRow(
+ "Earn rewards", "Time in this app earns XP and village resources.", self.rewards_toggle
+ )
+ self.settings_card.body.addWidget(self.rewards_row)
+ self.reward_hint = label("", "caption", wrap=True)
+ self.settings_card.body.addWidget(self.reward_hint)
+ left.addWidget(self.settings_card)
+
+ self.facts = Card("Details", index=4)
+ self.facts_grid = QGridLayout()
+ self.facts_grid.setHorizontalSpacing(16)
+ self.facts_grid.setVerticalSpacing(8)
+ self.facts.body.addLayout(self.facts_grid)
+ left.addWidget(self.facts)
+ left.addStretch(1)
+ cols.addLayout(left, 1)
+
+ self.sessions_card = Card("Recent sessions", "Each continuous stretch of focus", index=3)
+ self.sessions = QVBoxLayout()
+ self.sessions.setSpacing(0)
+ self.sessions_card.body.addLayout(self.sessions)
+ self.sessions_card.body.addStretch(1)
+ cols.addWidget(self.sessions_card, 1)
+ self.add(cols)
+ self.layout_.addStretch(1)
+
+ # ------------------------------------------------------------------
+
+ def load_app(self, app_id: int) -> None:
+ if app_id != self.app_id:
+ for tile in (self.t_today, self.t_week, self.t_month, self.t_avg):
+ tile.reset()
+ self.app_id = app_id
+ self.verticalScrollBar().setValue(0)
+ self.reload(animate=True)
+
+ def reload(self, animate: bool = False) -> None:
+ if self.app_id is None:
return
- p = QPainter(self)
- p.setRenderHint(QPainter.RenderHint.Antialiasing)
-
- w = self.width()
- h = self.height()
- margin_bottom = 24
- chart_h = h - margin_bottom
- n = len(self._data)
- bar_w = max(min((w - 20) // max(n, 1), 24), 4)
- gap = max(bar_w // 4, 1)
- max_val = max(v for _, v in self._data) if self._data else 1
-
- x = 10
- for day_str, ms in self._data:
- bar_h = max(int((ms / max(max_val, 1)) * (chart_h - 10)), 0)
- # Gradient bar
- c = QColor(theme.get_accent())
- c.setAlphaF(0.3 + 0.7 * min(ms / max(max_val, 1), 1.0))
- p.setPen(Qt.PenStyle.NoPen)
- p.setBrush(c)
- p.drawRoundedRect(x, chart_h - bar_h, bar_w, bar_h, 2, 2)
-
- # Day label (show every few)
- if n <= 14 or self._data.index((day_str, ms)) % (n // 7 or 1) == 0:
- p.setPen(QColor(theme.TEXT_MUTED))
- from PySide6.QtGui import QFont
- p.setFont(QFont("Segoe UI", 7))
- day_short = day_str[5:] # MM-DD
- p.drawText(x, h - 4, day_short)
-
- x += bar_w + gap
- p.end()
-
-
-class AppDetailView(QWidget):
- """Detailed view for a single app."""
-
- back_clicked = Signal()
-
- def __init__(self, parent=None):
- super().__init__(parent)
- self._app_id: int | None = None
- self._build_ui()
-
- def _build_ui(self):
- layout = QVBoxLayout(self)
- layout.setContentsMargins(24, 24, 24, 24)
- layout.setSpacing(16)
-
- # Back button + title
- top_row = QHBoxLayout()
- back_btn = QPushButton("← Back")
- back_btn.clicked.connect(self.back_clicked.emit)
- top_row.addWidget(back_btn)
-
- self._title = QLabel("App Details")
- self._title.setObjectName("heading")
- top_row.addWidget(self._title, stretch=1)
-
- self._fav_btn = QPushButton("☆ Favorite")
- self._fav_btn.clicked.connect(self._toggle_fav)
- top_row.addWidget(self._fav_btn)
- layout.addLayout(top_row)
-
- # Stats cards
- stats_row = QHBoxLayout()
- self._total_7d = StatValue("0m", "7-Day Total", theme.get_accent())
- self._total_30d = StatValue("0m", "30-Day Total", theme.PURPLE)
- self._opens_stat = StatValue("0", "Opens (7d)", theme.BLUE)
- self._clicks_stat = StatValue("0", "Clicks (7d)", theme.PINK)
-
- for w in (self._total_7d, self._total_30d, self._opens_stat, self._clicks_stat):
- card = NeonCard(glow_color=theme.BG_CARD)
- card.content_layout().addWidget(w)
- stats_row.addWidget(card)
- layout.addLayout(stats_row)
-
- # Chart
- chart_card = NeonCard(glow_color=theme.BG_CARD, title="DAILY USAGE (30 DAYS)")
- self._chart = BarChartWidget()
- chart_card.content_layout().addWidget(self._chart)
- layout.addWidget(chart_card)
-
- # Category
- cat_row = QHBoxLayout()
- cat_label = QLabel("Category:")
- cat_label.setStyleSheet(f"color: {theme.TEXT_DIM}; background: transparent;")
- cat_row.addWidget(cat_label)
- from PySide6.QtWidgets import QComboBox
- self._category = QComboBox()
- self._category.addItems(["None", "Work", "Study", "Games", "Social", "Entertainment", "Tools"])
- self._category.currentTextChanged.connect(self._on_category_change)
- cat_row.addWidget(self._category)
- cat_row.addStretch()
- layout.addLayout(cat_row)
-
- # Rewards toggle
- rewards_card = NeonCard(glow_color=theme.BG_CARD, title="REWARDS")
- rewards_layout = rewards_card.content_layout()
-
- self._rewards_check = QCheckBox("Enable rewards for this app")
- self._rewards_check.setStyleSheet(f"color: {theme.TEXT}; font-size: 13px;")
- self._rewards_check.stateChanged.connect(self._on_rewards_toggle)
- rewards_layout.addWidget(self._rewards_check)
-
- rewards_info = QLabel("When enabled, time spent in this app will generate XP and resources.")
- rewards_info.setWordWrap(True)
- rewards_info.setStyleSheet(f"color: {theme.TEXT_MUTED}; font-size: 11px; background: transparent;")
- rewards_layout.addWidget(rewards_info)
-
- layout.addWidget(rewards_card)
-
- layout.addStretch()
-
- def load_app(self, app_id: int):
- self._app_id = app_id
- app = queries.get_app(app_id)
+ app = queries.get_app(self.app_id)
if not app:
+ self.ctx.window.go_back()
return
-
- self._title.setText(app.get("display_name") or app["exe_name"])
-
- # Favorite button
- is_fav = bool(app.get("is_favorite"))
- self._fav_btn.setText("★ Favorited" if is_fav else "☆ Favorite")
- self._fav_btn.setStyleSheet(
- f"color: {theme.YELLOW};" if is_fav else ""
+ self.back.setText(f"Back to {self.ctx.window.back_label()}")
+ self.avatar.set_app(app["name"], app.get("icon_path"))
+ self.title.setText(app["name"])
+ self.kicker.setText(app.get("category") or "Uncategorized")
+ self.subtitle.setText(app["exe_name"] + (f" · {app['icon_path']}" if app.get("icon_path") else ""))
+ self.fav_btn.setChecked(bool(app.get("is_favorite")))
+ self.fav_btn.setText("Favorite" if app.get("is_favorite") else "Add to favorites")
+
+ 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)
+
+ on = rewards.enabled()
+ for w in (self.rewards_divider, self.rewards_row, self.reward_hint):
+ w.setVisible(on)
+ self.rewards_toggle.set_silently(rules.app_rewards_enabled(self.app_id))
+ self._update_reward_hint()
+
+ history = queries.app_daily_history(self.app_id, 30)
+ snap = self.ctx.snapshot()
+ live = snap.uncommitted_ms if snap.app_id == self.app_id else 0
+ history[-1]["focused_ms"] += live
+ week = history[-7:]
+ total_30 = sum(h["focused_ms"] for h in history)
+ active = [h for h in history if h["focused_ms"] > 0]
+ limit_ms = app.get("daily_limit_ms")
+ today_ms = history[-1]["focused_ms"]
+
+ self.t_today.set_number(
+ today_ms,
+ _short,
+ (
+ f"of {fmt.duration(limit_ms, short=True)} limit"
+ if limit_ms
+ else f"{history[-1]['opens_count']} launches"
+ ),
+ "danger" if limit_ms and today_ms >= limit_ms else "caption",
+ )
+ self.t_week.set_number(
+ sum(h["focused_ms"] for h in week), _short, f"{sum(h['opens_count'] for h in week)} launches"
+ )
+ self.t_month.set_number(total_30, _short, f"{len(active)} active days")
+ self.t_avg.set_number(total_30 / len(active) if active else 0, _short, "per active day, last 30 days")
+
+ self.chart.set_data(
+ [
+ Bar(
+ str(date.fromisoformat(h["day"]).day) if i % 3 == 2 or i == 29 else "",
+ h["focused_ms"],
+ f"{fmt.long_date(h['day'])}\n{fmt.duration(h['focused_ms'])}"
+ + (f" · {h['opens_count']} launches" if h["opens_count"] else ""),
+ )
+ for i, h in enumerate(history)
+ ],
+ highlight=29,
+ limit=limit_ms,
+ empty_text="No activity in the last 30 days",
+ )
+ 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 "")
)
- # Category
- cat = app.get("category") or "None"
- idx = self._category.findText(cat)
- if idx >= 0:
- self._category.blockSignals(True)
- self._category.setCurrentIndex(idx)
- self._category.blockSignals(False)
-
- # Rewards enabled
- from ...rewards import rules as reward_rules
- reward_rules.ensure_app_rules(app_id)
- enabled = reward_rules.app_rewards_enabled(app_id)
- self._rewards_check.blockSignals(True)
- self._rewards_check.setChecked(enabled)
- self._rewards_check.blockSignals(False)
-
- # Stats
- hist_30 = queries.app_daily_history(app_id, days=30)
- hist_7 = [h for h in hist_30 if h["day"] >= (date.today() - timedelta(days=7)).isoformat()]
-
- total_7 = sum(h.get("focused_ms", 0) for h in hist_7)
- total_30 = sum(h.get("focused_ms", 0) for h in hist_30)
- opens_7 = sum(h.get("opens_count", 0) for h in hist_7)
- clicks_7 = sum(h.get("clicks_count", 0) for h in hist_7)
-
- self._total_7d.set_value(theme.format_ms(total_7))
- self._total_30d.set_value(theme.format_ms(total_30))
- self._opens_stat.set_value(str(opens_7))
- self._clicks_stat.set_value(str(clicks_7))
-
- # Chart
- chart_data = [(h["day"], h.get("focused_ms", 0)) for h in hist_30]
- self._chart.set_data(chart_data)
-
- def _toggle_fav(self):
- if self._app_id is None:
+ self._fill_facts(app)
+ self._fill_sessions(animate)
+
+ def _fill_facts(self, app: dict) -> None:
+ clear_layout(self.facts_grid)
+ summary = queries.app_summary(self.app_id)
+ facts = [
+ ("First seen", fmt.relative_day(summary["first_day"])),
+ ("Last used", fmt.relative_day(summary["last_day"])),
+ ("All-time total", fmt.duration(summary["total_ms"], short=True)),
+ ("Active days", str(summary["active_days"])),
+ ("Longest session", fmt.duration(summary["longest_session_ms"], short=True)),
+ ("Executable", app["exe_name"]),
+ ]
+ for row, (name, value) in enumerate(facts):
+ self.facts_grid.addWidget(eyebrow(name), row, 0)
+ val = label(value)
+ val.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
+ self.facts_grid.addWidget(val, row, 1)
+ self.facts_grid.setColumnStretch(1, 1)
+
+ def _fill_sessions(self, animate: bool = False) -> None:
+ clear_layout(self.sessions)
+ added: list[QWidget] = []
+ sessions = queries.recent_sessions(self.app_id, limit=12)
+ if not sessions:
+ self.sessions.addWidget(EmptyState("clock", "No sessions yet"))
return
- app = queries.get_app(self._app_id)
- if not app:
+ last_day = None
+ for s in sessions:
+ day = datetime.fromtimestamp(s["start_ts"]).date()
+ if day != last_day:
+ heading = label(
+ fmt.relative_day(day).upper() if (date.today() - day).days < 2 else fmt.long_date(day).upper(),
+ "eyebrow",
+ )
+ heading.setContentsMargins(0, 10 if last_day else 0, 0, 4)
+ self.sessions.addWidget(heading)
+ added.append(heading)
+ last_day = day
+ row = QWidget()
+ lay = QHBoxLayout(row)
+ lay.setContentsMargins(0, 5, 0, 5)
+ lay.addWidget(label(f"{fmt.time_of_day(s['start_ts'])} – {fmt.time_of_day(s['end_ts'])}", "dim"))
+ if s["was_idle"]:
+ tag = label("then idle", "pill")
+ tag.setToolTip("This session ended because there was no input for the idle timeout.")
+ lay.addWidget(tag)
+ lay.addStretch(1)
+ dur = label(fmt.duration(s["duration_ms"], short=True))
+ dur.setStyleSheet("font-weight: 600;")
+ lay.addWidget(dur)
+ self.sessions.addWidget(row)
+ added.append(row)
+ if animate:
+ motion.stagger_in(added, step=16, limit=16)
+
+ def _update_reward_hint(self) -> None:
+ if not self.rewards_toggle.isChecked():
+ self.reward_hint.setText("")
+ self.reward_hint.hide()
return
- new_fav = not bool(app.get("is_favorite"))
- queries.set_favorite(self._app_id, new_fav)
- self.load_app(self._app_id)
-
- def _on_category_change(self, text):
- if self._app_id is None:
+ item = next((m for m in rewards.next_milestones() if m["app_id"] == self.app_id), None)
+ if item and item["next"]:
+ nxt = item["next"]
+ self.reward_hint.setText(
+ f"Next milestone at {fmt.duration(nxt['target_ms'], short=True)} today "
+ f"({fmt.duration(item['focused_ms'], short=True)} so far): {fmt.reward(nxt['reward'], ', ')}"
+ )
+ else:
+ self.reward_hint.setText("All of today's milestones are done.")
+ self.reward_hint.setVisible(rewards.enabled())
+
+ # ------------------------------------------------------------------
+ # Actions
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _set_combo(combo: QComboBox, data) -> None:
+ idx = combo.findData(data)
+ combo.blockSignals(True)
+ combo.setCurrentIndex(max(0, idx))
+ combo.blockSignals(False)
+
+ def _toggle_favorite(self) -> None:
+ queries.set_favorite(self.app_id, self.fav_btn.isChecked())
+ bus.data_changed.emit()
+ self.reload()
+
+ def _on_category(self) -> None:
+ if self.app_id is not None:
+ queries.set_category(self.app_id, self.category.currentData())
+ bus.data_changed.emit()
+
+ def _on_limit(self) -> None:
+ if self.app_id is None:
return
- queries.set_category(self._app_id, text if text != "None" else None)
-
- def _on_rewards_toggle(self, state):
- if self._app_id is None:
+ minutes = self.limit.currentData() 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")
+ self.reload()
+
+ def _on_rewards(self, on: bool) -> None:
+ if self.app_id is None:
return
- from ...rewards import rules as reward_rules
- reward_rules.enable_app_rewards(self._app_id, bool(state))
+ rules.enable_app_rewards(self.app_id, on)
+ bus.rewards_changed.emit()
+ self._update_reward_hint()
+
+ def _more_menu(self) -> None:
+ menu = QMenu(self)
+ menu.addAction("Rename…", self._rename)
+ menu.addAction("Reset name", lambda: self._apply_name(None))
+ menu.addSeparator()
+ menu.addAction("Exclude from tracking", lambda: self.ctx.window.exclude_app(self.app_id))
+ menu.exec(self.more_btn.mapToGlobal(self.more_btn.rect().bottomLeft()))
+
+ def _rename(self) -> None:
+ app = queries.get_app(self.app_id)
+ name, ok = QInputDialog.getText(self, "Rename app", f"Display name for {app['exe_name']}:", text=app["name"])
+ if ok:
+ self._apply_name(name)
+
+ def _apply_name(self, name: str | None) -> None:
+ app = queries.get_app(self.app_id)
+ queries.set_display_name(self.app_id, name or catalog.friendly_name(app["exe_name"]))
+ bus.data_changed.emit()
+ self.reload()
+
+
+def _short(ms: float) -> str:
+ return fmt.duration(ms, short=True)
diff --git a/apptrackr/ui/views/apps_view.py b/apptrackr/ui/views/apps_view.py
index 5235b6d..902ccc0 100644
--- a/apptrackr/ui/views/apps_view.py
+++ b/apptrackr/ui/views/apps_view.py
@@ -1,133 +1,233 @@
-"""Apps list view – sort by most/least used, most opened, most clicked."""
+"""Apps: every tracked app for a period, sortable, searchable and filterable."""
from __future__ import annotations
-from PySide6.QtCore import Qt, Signal
-from PySide6.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QComboBox,
- QScrollArea, QTabBar, QPushButton,
+from PySide6.QtCore import QTimer
+from PySide6.QtWidgets import QComboBox, QHBoxLayout, QLineEdit, QPushButton, QVBoxLayout
+
+from ...data import db, queries
+from .. import fmt, icons, motion, theme
+from ..signals import bus
+from ..widgets.components import (
+ AppRow,
+ Card,
+ EmptyState,
+ IconBinding,
+ Page,
+ PageHeader,
+ SegmentedControl,
+ button,
+ clear_layout,
+ label,
+ tone_color,
)
-from .. import theme
-from ..widgets.components import AppRow
-from ...data import queries
-
-
-class AppsView(QWidget):
- """Apps list with sort tabs, search, and filter."""
+PERIODS = (("Today", 0), ("Last 7 days", 6), ("Last 30 days", 29), ("Last 90 days", 89), ("All time", None))
+SORTS = (
+ ("Most used", queries.SORT_FOCUSED),
+ ("Least used", queries.SORT_LEAST),
+ ("Most launched", queries.SORT_OPENS),
+ ("Most clicked", queries.SORT_CLICKS),
+)
- app_selected = Signal(int)
- def __init__(self, parent=None):
+class AppsView(Page):
+ def __init__(self, ctx, parent=None):
super().__init__(parent)
- self._current_tab = 0
- self._search_text = ""
- self._build_ui()
- self.refresh()
-
- def _build_ui(self):
- layout = QVBoxLayout(self)
- layout.setContentsMargins(24, 24, 24, 24)
- layout.setSpacing(16)
-
- header = QLabel("Apps")
- header.setObjectName("heading")
- layout.addWidget(header)
-
- # Tabs
- tab_row = QHBoxLayout()
- self._tabs = QTabBar()
- self._tabs.addTab("Most Used")
- self._tabs.addTab("Least Used")
- self._tabs.addTab("Most Opened")
- self._tabs.addTab("Most Clicked")
- self._tabs.addTab("Favorites")
- self._tabs.currentChanged.connect(self._on_tab_change)
- tab_row.addWidget(self._tabs)
- tab_row.addStretch()
- layout.addLayout(tab_row)
-
- # Search + period
- filter_row = QHBoxLayout()
- self._search = QLineEdit()
- self._search.setPlaceholderText("Search apps...")
- self._search.textChanged.connect(self._on_search)
- filter_row.addWidget(self._search, stretch=1)
-
- self._period = QComboBox()
- self._period.addItems(["7 Days", "30 Days", "90 Days", "All Time"])
- self._period.currentIndexChanged.connect(lambda _: self.refresh())
- filter_row.addWidget(self._period)
- layout.addLayout(filter_row)
-
- # Apps list
- scroll = QScrollArea()
- scroll.setWidgetResizable(True)
- scroll.setStyleSheet("QScrollArea { border: none; background: transparent; }")
- self._list_container = QWidget()
- self._list_container.setStyleSheet("background: transparent;")
- self._list_layout = QVBoxLayout(self._list_container)
- self._list_layout.setContentsMargins(0, 0, 0, 0)
- self._list_layout.setSpacing(6)
- self._list_layout.addStretch()
- scroll.setWidget(self._list_container)
- layout.addWidget(scroll, stretch=1)
-
- def refresh(self):
- days_map = {0: 7, 1: 30, 2: 90, 3: 3650}
- days = days_map.get(self._period.currentIndex(), 7)
-
- tab = self._tabs.currentIndex()
- if tab == 0:
- apps = queries.most_used(days=days)
- elif tab == 1:
- apps = queries.least_used(days=days)
- elif tab == 2:
- apps = queries.most_opened(days=days)
- elif tab == 3:
- apps = queries.most_clicked(days=days)
- elif tab == 4:
- all_apps = queries.most_used(days=days, limit=200)
- apps = [a for a in all_apps if a.get("is_favorite")]
- else:
- apps = []
-
- # Filter by search
- if self._search_text:
- q = self._search_text.lower()
- apps = [a for a in apps if q in (a.get("display_name") or a["exe_name"]).lower()]
-
- self._rebuild_list(apps)
-
- def _rebuild_list(self, apps: list[dict]):
- while self._list_layout.count() > 1:
- item = self._list_layout.takeAt(0)
- if item.widget():
- item.widget().deleteLater()
-
+ self.setObjectName("page")
+ self.ctx = ctx
+ self._fractions: dict[int, float] = {}
+
+ self.header = PageHeader("Apps", kicker="Library")
+ self.add(self.header)
+
+ bar = QHBoxLayout()
+ bar.setSpacing(8)
+ self.search = QLineEdit()
+ self.search.setPlaceholderText("Search apps (Ctrl+F)")
+ self.search.setClearButtonEnabled(True)
+ self.search.setAccessibleName("Search apps")
+ self._search_action = self.search.addAction(
+ icons.icon("search", tone_color("text_muted")), QLineEdit.ActionPosition.LeadingPosition
+ )
+ bus.theme_changed.connect(lambda: self._search_action.setIcon(icons.icon("search", tone_color("text_muted"))))
+ self._debounce = QTimer(self)
+ self._debounce.setSingleShot(True)
+ self._debounce.setInterval(150)
+ self._debounce.timeout.connect(self._user_refresh)
+ self.search.textChanged.connect(lambda *_: self._debounce.start())
+ bar.addWidget(self.search, 1)
+
+ self.period = QComboBox()
+ self.period.setAccessibleName("Period")
+ for text, _ in PERIODS:
+ self.period.addItem(text)
+ self.period.setCurrentIndex(1)
+ self.period.currentIndexChanged.connect(self._user_refresh)
+ bar.addWidget(self.period)
+
+ self.category = QComboBox()
+ self.category.setAccessibleName("Category")
+ self.category.addItem("All categories", None)
+ for cat in queries.CATEGORIES:
+ self.category.addItem(cat, cat)
+ self.category.currentIndexChanged.connect(self._user_refresh)
+ bar.addWidget(self.category)
+
+ self.favorites = QPushButton("Favorites")
+ self.favorites.setCheckable(True)
+ self.favorites.setProperty("kind", "ghost")
+ self.favorites.setToolTip("Show only favorite apps")
+ IconBinding.attach(self.favorites, "star", "text_dim", checked_tone="gold")
+ self.favorites.toggled.connect(self._user_refresh)
+ bar.addWidget(self.favorites)
+ self.add(bar)
+
+ self.sort = SegmentedControl([s[0] for s in SORTS])
+ self.sort.changed.connect(self._user_refresh)
+ sort_row = QHBoxLayout()
+ sort_row.addWidget(self.sort)
+ sort_row.addStretch(1)
+ self.summary = label("", "caption")
+ sort_row.addWidget(self.summary)
+ self.add(sort_row)
+
+ self.card = Card(padding=8, spacing=2)
+ self.list = QVBoxLayout()
+ self.list.setSpacing(2)
+ self.card.body.addLayout(self.list)
+ self.add(self.card)
+
+ self.hidden_note = button("", kind="link", on_click=lambda: ctx.navigate("settings"))
+ self.add(self.hidden_note)
+ self.layout_.addStretch(1)
+
+ bus.data_changed.connect(lambda: self.isVisible() and self.refresh())
+
+ def focus_search(self) -> None:
+ self.search.setFocus()
+ self.search.selectAll()
+
+ def set_period(self, index: int) -> None:
+ self.period.setCurrentIndex(index)
+
+ def _user_refresh(self, *_args) -> None:
+ self.refresh(animate=True)
+
+ def refresh(self, animate: bool = False) -> None:
+ """Rebuild the list. *animate* staggers rows in after a user-driven change."""
+ _label, days = PERIODS[self.period.currentIndex()]
+ end = queries.today_str()
+ start = queries.days_ago(days) if days is not None else "0000-01-01"
+ sort = SORTS[self.sort.current()][1]
+ apps = queries.top_apps(
+ start,
+ end,
+ sort=sort,
+ limit=None,
+ category=self.category.currentData(),
+ favorites_only=self.favorites.isChecked(),
+ search=self.search.text(),
+ )
+
+ total_ms = sum(a["focused_ms"] for a in apps)
+ count = len(apps)
+ self.header.set_subtitle(
+ f"{count} app{'s' if count != 1 else ''} · {fmt.duration(total_ms, short=True)} "
+ f"focused · {PERIODS[self.period.currentIndex()][0].lower()}"
+ )
+ self.summary.setText("Right-click an app for quick actions")
+
+ clear_layout(self.list)
if not apps:
- lbl = QLabel("No apps found")
- lbl.setStyleSheet(f"color: {theme.TEXT_MUTED}; padding: 20px; background: transparent;")
- lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
- self._list_layout.insertWidget(0, lbl)
- return
-
- max_ms = max(a.get("focused_ms", 1) for a in apps) or 1
- for i, app in enumerate(apps):
- row = AppRow(
- app_id=app["app_id"],
- name=app.get("display_name") or app["exe_name"],
- value_ms=app.get("focused_ms", 0),
- max_ms=max_ms,
- is_favorite=bool(app.get("is_favorite")),
+ self.list.addWidget(self._empty_state(sort))
+ else:
+ metric = {queries.SORT_OPENS: "opens_count", queries.SORT_CLICKS: "clicks_count"}.get(sort, "focused_ms")
+ peak = max(a[metric] for a in apps) or 1
+ rows = [self._row(app, sort, metric, peak, total_ms, rank) for rank, app in enumerate(apps, start=1)]
+ for row in rows:
+ self.list.addWidget(row)
+ self._fractions = {row.app_id: row.fraction for row in rows}
+ if animate:
+ motion.stagger_in(rows)
+
+ hidden = len(queries.hidden_apps())
+ self.hidden_note.setText(f"{hidden} excluded app{'s are' if hidden != 1 else ' is'} hidden. Manage in Settings")
+ self.hidden_note.setVisible(hidden > 0)
+
+ def _row(self, app: dict, sort: str, metric: str, peak: int, total_ms: int, rank: int) -> AppRow:
+ opens = app["opens_count"]
+ launches = f"{opens} launch{'es' if opens != 1 else ''}"
+ if sort == queries.SORT_OPENS:
+ value = launches
+ sub = fmt.duration(app["focused_ms"], short=True) + " focused"
+ elif sort == queries.SORT_CLICKS:
+ value = f"{fmt.count(app['clicks_count'])} clicks"
+ sub = fmt.duration(app["focused_ms"], short=True) + " focused"
+ else:
+ value = fmt.duration(app["focused_ms"], short=True)
+ days = app.get("active_days") or 0
+ sub = " · ".join(
+ filter(
+ None,
+ [
+ app.get("category"),
+ launches if opens else "",
+ f"{days} active day{'s' if days != 1 else ''}" if days > 1 else "",
+ ],
+ )
)
- row.clicked.connect(self.app_selected.emit)
- self._list_layout.insertWidget(i, row)
-
- def _on_tab_change(self, idx):
- self._current_tab = idx
- self.refresh()
-
- def _on_search(self, text):
- self._search_text = text
- self.refresh()
+ extra = f"{app['focused_ms'] / total_ms:.0%}" if total_ms and metric == "focused_ms" else ""
+ row = AppRow(
+ app,
+ value,
+ app[metric] / peak,
+ sub=sub,
+ extra=extra,
+ rank=rank,
+ dot=theme.category_color(app.get("category")) if app.get("category") else None,
+ animate_from=self._fractions.get(app["app_id"], 0.0),
+ )
+ row.clicked.connect(self.ctx.open_app)
+ row.context_requested.connect(self.ctx.app_menu)
+ return row
+
+ def _empty_state(self, sort: str) -> EmptyState:
+ if self.search.text().strip():
+ return EmptyState(
+ "search",
+ f"No apps match “{self.search.text().strip()}”",
+ "Try a different name or clear the filters.",
+ "Clear search",
+ lambda: self.search.clear(),
+ )
+ if sort == queries.SORT_CLICKS and not db.get_bool("track_clicks"):
+ return EmptyState(
+ "mouse-pointer-click",
+ "Click counting is off",
+ "Turn it on in Settings to see which apps you click the most.",
+ "Open Settings",
+ lambda: self.ctx.navigate("settings"),
+ )
+ if self.favorites.isChecked():
+ return EmptyState(
+ "star",
+ "No favorites in this period",
+ "Mark apps as favorites from their detail page or the right-click menu. "
+ "Favorites also drive your daily streak.",
+ )
+ if self.category.currentData():
+ return EmptyState(
+ "layout-grid",
+ f"No {self.category.currentText()} apps in this period",
+ "Assign categories from an app's detail page.",
+ )
+ if not self.ctx.tracker.supported and not queries.first_tracked_day():
+ return EmptyState(
+ "power",
+ "Nothing tracked on this platform",
+ "Foreground tracking runs on Windows. Start with --demo to explore sample data.",
+ )
+ return EmptyState(
+ "layout-grid", "No apps tracked in this period", "Use your computer as usual and apps will appear here."
+ )
diff --git a/apptrackr/ui/views/calendar_view.py b/apptrackr/ui/views/calendar_view.py
index a371d94..ca5de7a 100644
--- a/apptrackr/ui/views/calendar_view.py
+++ b/apptrackr/ui/views/calendar_view.py
@@ -1,202 +1,238 @@
-"""Calendar heatmap view."""
+"""Calendar: month heatmap with a breakdown of the selected day."""
from __future__ import annotations
import calendar
-from datetime import date, timedelta
+from datetime import date, datetime
-from PySide6.QtCore import Qt, Signal
-from PySide6.QtGui import QColor, QPainter, QFont
-from PySide6.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QGridLayout,
- QScrollArea, QPushButton, QFrame, QSizePolicy,
-)
+from PySide6.QtCore import Qt
+from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout
-from .. import theme
from ...data import queries
-from ..widgets.components import NeonCard, AppRow
-
-
-class HeatmapCell(QWidget):
- """Single day cell in the calendar heatmap."""
+from .. import fmt, fonts, motion, theme
+from ..signals import bus
+from ..widgets.charts import Bar, BarChart, HeatLegend, MonthHeatmap
+from ..widgets.components import (
+ AppRow,
+ Card,
+ EmptyState,
+ Page,
+ PageHeader,
+ button,
+ clear_layout,
+ count_to,
+ divider,
+ eyebrow,
+ label,
+)
- clicked = Signal(str) # emits day string YYYY-MM-DD
- def __init__(self, day_str: str, total_ms: int, max_ms: int, parent=None):
+class CalendarView(Page):
+ def __init__(self, ctx, parent=None):
super().__init__(parent)
- self._day = day_str
- self._total_ms = total_ms
- self._max_ms = max_ms
- self.setFixedSize(28, 28)
- self.setCursor(Qt.CursorShape.PointingHandCursor)
- self.setToolTip(f"{day_str}\n{theme.format_ms(total_ms)}")
-
- def paintEvent(self, event):
- p = QPainter(self)
- p.setRenderHint(QPainter.RenderHint.Antialiasing)
- if self._total_ms == 0:
- color = QColor(theme.BG_CARD)
+ self.setObjectName("page")
+ self.ctx = ctx
+ self._month = date.today().replace(day=1)
+ self._selected = date.today()
+ self._day_total = 0
+ self._fractions: dict[int, float] = {}
+
+ self.header = PageHeader("Calendar", kicker="History")
+ self.prev_btn = button(
+ "", icon="chevron-left", tooltip="Previous month (PgUp)", on_click=lambda: self._shift(-1)
+ )
+ self.next_btn = button("", icon="chevron-right", tooltip="Next month (PgDown)", on_click=lambda: self._shift(1))
+ self.today_btn = button("Today", on_click=self._go_today)
+ for b in (self.prev_btn, self.today_btn, self.next_btn):
+ self.header.actions.addWidget(b)
+ self.add(self.header)
+
+ cols = self.stack_when_narrow(QHBoxLayout())
+ cols.setSpacing(16)
+
+ self.month_card = Card("Month", index=1)
+ self.month_title = label("", "heading")
+ self.month_title.setFont(fonts.sans(20, 600))
+ self.month_card.body.addWidget(self.month_title)
+ self.heatmap = MonthHeatmap()
+ self.heatmap.day_selected.connect(self._on_day)
+ self.month_card.body.addWidget(self.heatmap)
+ stats = QHBoxLayout()
+ stats.setSpacing(18)
+ self.stat_labels = {}
+ for key, caption in (
+ ("total", "Total"),
+ ("avg", "Daily average"),
+ ("active", "Active days"),
+ ("best", "Busiest day"),
+ ):
+ box = QVBoxLayout()
+ box.setSpacing(3)
+ box.addWidget(eyebrow(caption))
+ value = label("–")
+ value.setFont(fonts.sans(15, 600, tabular=True))
+ box.addWidget(value)
+ self.stat_labels[key] = value
+ stats.addLayout(box)
+ stats.addStretch(1)
+ legend_row = QHBoxLayout()
+ legend_row.addStretch(1)
+ legend_row.addWidget(HeatLegend())
+ self.month_card.body.addLayout(legend_row)
+ self.month_card.body.addWidget(divider())
+ self.month_card.body.addLayout(stats)
+ self.month_card.body.addStretch(1)
+ cols.addWidget(self.month_card, 11)
+
+ self.day_card = Card("Day", index=2)
+ head = QHBoxLayout()
+ names = QVBoxLayout()
+ names.setSpacing(2)
+ self.day_title = label("", "heading")
+ self.day_title.setFont(fonts.sans(20, 600))
+ names.addWidget(self.day_title)
+ self.day_sub = label("", "caption")
+ names.addWidget(self.day_sub)
+ head.addLayout(names, 1)
+ self.day_total = label("", "value")
+ head.addWidget(self.day_total, 0, Qt.AlignmentFlag.AlignTop)
+ self.day_card.body.addLayout(head)
+ self.day_hours = BarChart(110)
+ self.day_card.body.addWidget(self.day_hours)
+ self.day_list = QVBoxLayout()
+ self.day_list.setSpacing(2)
+ self.day_card.body.addLayout(self.day_list)
+ self.day_card.body.addStretch(1)
+ cols.addWidget(self.day_card, 10)
+ self.add(cols)
+ self.layout_.addStretch(1)
+
+ bus.data_changed.connect(lambda: self.isVisible() and self.refresh())
+
+ def select_day(self, day: str) -> None:
+ self._selected = date.fromisoformat(day)
+ self._month = self._selected.replace(day=1)
+
+ def refresh(self, animate: bool = False) -> None:
+ first = self._month
+ last = first.replace(day=calendar.monthrange(first.year, first.month)[1])
+ totals = queries.daily_totals(first.isoformat(), last.isoformat())
+ snap = self.ctx.snapshot()
+ today = date.today()
+ if first <= today <= last and snap.app_id:
+ totals[today.isoformat()] = totals.get(today.isoformat(), 0) + snap.uncommitted_ms
+
+ self.month_title.setText(f"{first:%B %Y}")
+ self.heatmap.set_month(first, totals)
+ self.heatmap.set_selected(self._selected)
+ self.next_btn.setEnabled(first < today.replace(day=1))
+ self.today_btn.setEnabled(self._selected != today or first != today.replace(day=1))
+
+ 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)))
+ 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)}")
else:
- intensity = min(self._total_ms / max(self._max_ms, 1), 1.0)
- c = QColor(theme.get_accent())
- c.setAlphaF(0.15 + intensity * 0.85)
- color = c
- p.setPen(Qt.PenStyle.NoPen)
- p.setBrush(color)
- p.drawRoundedRect(1, 1, 26, 26, 4, 4)
-
- # Day number
- if self._day:
- day_num = int(self._day.split("-")[2])
- p.setPen(QColor(theme.TEXT if self._total_ms > 0 else theme.TEXT_MUTED))
- p.setFont(QFont("Segoe UI", 8))
- p.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, str(day_num))
- p.end()
-
- def mousePressEvent(self, event):
- self.clicked.emit(self._day)
-
-
-class CalendarView(QWidget):
- """Calendar heatmap + day drilldown."""
-
- app_selected = Signal(int)
-
- def __init__(self, parent=None):
- super().__init__(parent)
- self._current_month = date.today().replace(day=1)
- self._build_ui()
- self.refresh()
-
- def _build_ui(self):
- layout = QVBoxLayout(self)
- layout.setContentsMargins(24, 24, 24, 24)
- layout.setSpacing(16)
-
- # Header
- header = QLabel("Calendar")
- header.setObjectName("heading")
- layout.addWidget(header)
-
- # Month nav
- nav_row = QHBoxLayout()
- self._prev_btn = QPushButton("◀")
- self._prev_btn.setFixedSize(36, 36)
- self._prev_btn.clicked.connect(self._prev_month)
- nav_row.addWidget(self._prev_btn)
-
- self._month_label = QLabel()
- self._month_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
- self._month_label.setStyleSheet(f"font-size: 18px; font-weight: 700; color: {theme.TEXT}; background: transparent;")
- nav_row.addWidget(self._month_label, stretch=1)
-
- self._next_btn = QPushButton("▶")
- self._next_btn.setFixedSize(36, 36)
- self._next_btn.clicked.connect(self._next_month)
- nav_row.addWidget(self._next_btn)
- layout.addLayout(nav_row)
-
- # Heatmap grid
- self._grid_container = NeonCard(glow_color=theme.BG_CARD)
- self._grid_layout = QGridLayout()
- self._grid_layout.setSpacing(4)
- self._grid_container.content_layout().addLayout(self._grid_layout)
- layout.addWidget(self._grid_container)
-
- # Day drilldown
- self._drill_label = QLabel("Click a day to see details")
- self._drill_label.setObjectName("subheading")
- layout.addWidget(self._drill_label)
-
- scroll = QScrollArea()
- scroll.setWidgetResizable(True)
- scroll.setStyleSheet("QScrollArea { border: none; background: transparent; }")
- self._drill_container = QWidget()
- self._drill_container.setStyleSheet("background: transparent;")
- self._drill_layout = QVBoxLayout(self._drill_container)
- self._drill_layout.setContentsMargins(0, 0, 0, 0)
- self._drill_layout.setSpacing(6)
- self._drill_layout.addStretch()
- scroll.setWidget(self._drill_container)
- layout.addWidget(scroll, stretch=1)
-
- def refresh(self):
- self._month_label.setText(self._current_month.strftime("%B %Y"))
-
- # Clear grid
- while self._grid_layout.count():
- item = self._grid_layout.takeAt(0)
- if item.widget():
- item.widget().deleteLater()
-
- # Day-of-week headers
- for i, name in enumerate(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]):
- lbl = QLabel(name)
- lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
- lbl.setStyleSheet(f"color: {theme.TEXT_MUTED}; font-size: 10px; background: transparent;")
- self._grid_layout.addWidget(lbl, 0, i)
-
- # Get month range
- year = self._current_month.year
- month = self._current_month.month
- _, days_in_month = calendar.monthrange(year, month)
- start_day = self._current_month.isoformat()
- end_day = date(year, month, days_in_month).isoformat()
-
- # Fetch data
- daily = {d["day"]: d["total_ms"] for d in queries.daily_totals_range(start_day, end_day)}
- max_ms = max(daily.values()) if daily else 1
-
- # Build cells
- first_weekday = self._current_month.weekday() # 0=Monday
- for day_num in range(1, days_in_month + 1):
- d = date(year, month, day_num)
- day_str = d.isoformat()
- total_ms = daily.get(day_str, 0)
- cell = HeatmapCell(day_str, total_ms, max_ms)
- cell.clicked.connect(self._show_day)
- row = 1 + (first_weekday + day_num - 1) // 7
- col = (first_weekday + day_num - 1) % 7
- self._grid_layout.addWidget(cell, row, col)
-
- def _show_day(self, day_str: str):
- self._drill_label.setText(f"Apps on {day_str}")
-
- # Clear
- while self._drill_layout.count() > 1:
- item = self._drill_layout.takeAt(0)
- if item.widget():
- item.widget().deleteLater()
-
- apps = queries.day_breakdown(day_str)
+ self.stat_labels["best"].setText("–")
+ self.header.set_subtitle(
+ f"{fmt.duration(total, short=True)} tracked in {first:%B}" if total else f"Nothing tracked in {first:%B}"
+ )
+ self._show_day(animate)
+
+ def _show_day(self, animate: bool = False) -> None:
+ day = self._selected
+ key = day.isoformat()
+ apps = queries.top_apps(key, key, limit=None)
+ snap = self.ctx.snapshot()
+ if day == date.today() and snap.app_id:
+ for app in apps:
+ if app["app_id"] == snap.app_id:
+ app["focused_ms"] += snap.uncommitted_ms
+ total = sum(a["focused_ms"] for a in apps)
+ self.day_title.setText(fmt.long_date(day))
+ self.day_sub.setText(fmt.relative_day(day) if (date.today() - day).days < 7 else f"{day:%Y}")
+ if animate and total and self._day_total:
+ count_to(self.day_total, self._day_total, total, _short)
+ else:
+ self.day_total.setText(fmt.duration(total, short=True) if total else "")
+ self._day_total = total
+
+ hours = queries.hourly_totals(key)
+ self.day_hours.set_data(
+ [
+ Bar(f"{h:02d}" if h % 6 == 0 else "", ms, f"{h:02d}:00 · {fmt.duration(ms)}")
+ for h, ms in enumerate(hours)
+ ],
+ highlight=datetime.now().hour if day == date.today() else None,
+ empty_text="No activity on this day",
+ )
+ self.day_hours.setVisible(bool(total))
+
+ clear_layout(self.day_list)
if not apps:
- lbl = QLabel("No data for this day")
- lbl.setStyleSheet(f"color: {theme.TEXT_MUTED}; background: transparent;")
- self._drill_layout.insertWidget(0, lbl)
+ self.day_list.addWidget(EmptyState("calendar-days", "No activity", "Nothing was tracked on this day."))
return
-
- max_ms = max(a.get("focused_ms", 1) for a in apps)
- for i, app in enumerate(apps):
+ peak = apps[0]["focused_ms"] or 1
+ rows = []
+ for rank, app in enumerate(apps[:12], start=1):
row = AppRow(
- app_id=app["app_id"],
- name=app.get("display_name") or app["exe_name"],
- value_ms=app.get("focused_ms", 0),
- max_ms=max_ms,
- is_favorite=False,
+ app,
+ fmt.duration(app["focused_ms"], short=True),
+ app["focused_ms"] / peak,
+ rank=rank,
+ tone="accent" if day == date.today() and app["app_id"] == snap.app_id else "ink",
+ dot=theme.category_color(app.get("category")),
+ sub=app.get("category") or "Uncategorized",
+ extra=f"{app['focused_ms'] / (total or 1):.0%}",
+ animate_from=self._fractions.get(app["app_id"], 0.0),
)
- row.clicked.connect(self.app_selected.emit)
- self._drill_layout.insertWidget(i, row)
-
- def _prev_month(self):
- if self._current_month.month == 1:
- self._current_month = self._current_month.replace(year=self._current_month.year - 1, month=12)
+ row.clicked.connect(self.ctx.open_app)
+ row.context_requested.connect(self.ctx.app_menu)
+ self.day_list.addWidget(row)
+ rows.append(row)
+ self._fractions = {row.app_id: row.fraction for row in rows}
+ if animate:
+ motion.stagger_in(rows)
+ if len(apps) > 12:
+ self.day_list.addWidget(label(f"and {len(apps) - 12} more", "caption"))
+
+ def _on_day(self, day: str) -> None:
+ self._selected = date.fromisoformat(day)
+ if self._selected.replace(day=1) != self._month:
+ self._month = self._selected.replace(day=1)
+ self.refresh(animate=True)
else:
- self._current_month = self._current_month.replace(month=self._current_month.month - 1)
- self.refresh()
-
- def _next_month(self):
- if self._current_month.month == 12:
- self._current_month = self._current_month.replace(year=self._current_month.year + 1, month=1)
+ self.today_btn.setEnabled(self._selected != date.today())
+ self._show_day(animate=True)
+
+ def _shift(self, months: int) -> None:
+ y, m = self._month.year, self._month.month + months
+ y, m = y + (m - 1) // 12, (m - 1) % 12 + 1
+ target = date(y, m, 1)
+ if target > date.today().replace(day=1):
+ return
+ self._month = target
+ last = calendar.monthrange(y, m)[1]
+ self._selected = min(date.today(), target.replace(day=min(self._selected.day, last)))
+ self.refresh(animate=True)
+
+ def _go_today(self) -> None:
+ self._selected = date.today()
+ self._month = self._selected.replace(day=1)
+ self.refresh(animate=True)
+
+ def keyPressEvent(self, event):
+ if event.key() == Qt.Key.Key_PageUp:
+ self._shift(-1)
+ elif event.key() == Qt.Key.Key_PageDown:
+ self._shift(1)
else:
- self._current_month = self._current_month.replace(month=self._current_month.month + 1)
- self.refresh()
+ super().keyPressEvent(event)
+
+
+def _short(ms: float) -> str:
+ return fmt.duration(ms, short=True)
diff --git a/apptrackr/ui/views/dashboard.py b/apptrackr/ui/views/dashboard.py
index ddef2d1..7de62a4 100644
--- a/apptrackr/ui/views/dashboard.py
+++ b/apptrackr/ui/views/dashboard.py
@@ -1,180 +1,410 @@
-"""Dashboard view – Now Tracking + today stats + top apps."""
+"""Dashboard: what is being tracked right now and how today is going."""
from __future__ import annotations
-from PySide6.QtCore import Qt, QTimer, Signal
-from PySide6.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QScrollArea, QPushButton, QFrame,
+from datetime import date, datetime, timedelta
+
+from PySide6.QtCore import QSize
+from PySide6.QtWidgets import QHBoxLayout, QMenu, QVBoxLayout, QWidget
+
+from ...core import tracker as trk
+from ...data import db, queries
+from ...game import economy
+from ...rewards import engine as rewards
+from .. import fmt, fonts, icons, motion, theme
+from ..signals import bus
+from ..widgets.charts import Bar, BarChart, SessionDial, ShareBar
+from ..widgets.components import (
+ AppAvatar,
+ AppRow,
+ Card,
+ EmptyState,
+ FlowLayout,
+ MetricGrid,
+ Page,
+ PageHeader,
+ StatTile,
+ button,
+ clear_layout,
+ divider,
+ eyebrow,
+ icon_label,
+ label,
+ legend_item,
+ set_role,
+ tone_color,
)
-from .. import theme
-from ..widgets.components import NeonCard, StatValue, AppRow
-from ...data import queries
+TOP_APPS = 7
-class DashboardView(QWidget):
- """Main dashboard with live tracking info and today's stats."""
+class NowCard(Card):
+ """Live session: chronograph dial, current app and pause controls."""
- app_selected = Signal(int)
+ def __init__(self, ctx, parent=None):
+ super().__init__(parent=parent, padding=18, spacing=12)
+ self.ctx = ctx
+ head = QHBoxLayout()
+ head.addWidget(eyebrow("Now", 1))
+ head.addStretch(1)
+ self.pulse = motion.PulseDot(5)
+ head.addWidget(self.pulse)
+ self.state = label("", "pillAccent")
+ head.addWidget(self.state)
+ self.body.addLayout(head)
- def __init__(self, tracker, parent=None):
- super().__init__(parent)
- self._tracker = tracker
- self._build_ui()
-
- # Auto-refresh every 1 second
- self._timer = QTimer(self)
- self._timer.timeout.connect(self.refresh)
- self._timer.start(1000)
-
- def _build_ui(self):
- layout = QVBoxLayout(self)
- layout.setContentsMargins(24, 24, 24, 24)
- layout.setSpacing(20)
-
- # -- Header --
- header = QLabel("Dashboard")
- header.setObjectName("heading")
- layout.addWidget(header)
-
- # -- Now Tracking card --
- now_card = NeonCard(glow_color=theme.get_accent(), title="NOW TRACKING")
- now_layout = now_card.content_layout()
-
- self._now_app = QLabel("—")
- self._now_app.setStyleSheet(
- f"font-size: 22px; font-weight: 700; color: {theme.TEXT}; background: transparent;"
- )
- now_layout.addWidget(self._now_app)
+ row = QHBoxLayout()
+ row.setSpacing(18)
+ self.dial = SessionDial(150)
+ row.addWidget(self.dial)
- self._now_timer = QLabel("0s")
- self._now_timer.setStyleSheet(
- f"font-size: 36px; font-weight: 700; color: {theme.get_accent()}; background: transparent;"
- )
- now_layout.addWidget(self._now_timer)
-
- # Pause button
- btn_row = QHBoxLayout()
- self._pause_btn = QPushButton("⏸ Pause Tracking")
- self._pause_btn.setObjectName("primary")
- self._pause_btn.clicked.connect(self._toggle_pause)
- btn_row.addWidget(self._pause_btn)
- btn_row.addStretch()
- now_layout.addLayout(btn_row)
-
- layout.addWidget(now_card)
-
- # -- Stats row --
- stats_row = QHBoxLayout()
- stats_row.setSpacing(16)
-
- self._today_total = StatValue("0m", "Today Total", theme.get_accent())
- self._week_total = StatValue("0m", "This Week", theme.PURPLE)
- self._apps_count = StatValue("0", "Apps Today", theme.BLUE)
- self._streak = StatValue("0", "Streak Days", theme.YELLOW)
-
- for w in (self._today_total, self._week_total, self._apps_count, self._streak):
- card = NeonCard(glow_color=theme.BG_CARD)
- card.content_layout().addWidget(w)
- stats_row.addWidget(card)
-
- layout.addLayout(stats_row)
-
- # -- Top Apps today --
- top_label = QLabel("Top Apps Today")
- top_label.setStyleSheet(
- f"font-size: 16px; font-weight: 700; color: {theme.TEXT}; background: transparent;"
+ self.identity = QWidget()
+ col = QVBoxLayout(self.identity)
+ col.setContentsMargins(0, 4, 0, 0)
+ col.setSpacing(4)
+ top = QHBoxLayout()
+ top.setSpacing(10)
+ self.avatar = AppAvatar("", None, 32)
+ top.addWidget(self.avatar)
+ self.state_icon = icon_label("pause", "warning", 22)
+ top.addWidget(self.state_icon)
+ self.name = label("", "heading")
+ self.name.setFont(fonts.sans(19, 600))
+ top.addWidget(self.name, 1)
+ col.addLayout(top)
+ self.detail = label("", "caption", wrap=True)
+ col.addWidget(self.detail)
+ col.addSpacing(6)
+ col.addWidget(divider())
+ col.addSpacing(4)
+ facts = QHBoxLayout()
+ facts.setSpacing(18)
+ self.fact_started = self._fact("Started")
+ self.fact_today = self._fact("Today in app")
+ facts.addLayout(self.fact_started[0])
+ facts.addLayout(self.fact_today[0])
+ facts.addStretch(1)
+ col.addLayout(facts)
+ col.addStretch(1)
+
+ actions = QHBoxLayout()
+ actions.setSpacing(6)
+ self.pause_btn = button("Pause", kind="primary", on_click=ctx.window.toggle_pause)
+ self.pause_btn.setIconSize(QSize(14, 14))
+ actions.addWidget(self.pause_btn)
+ self.later_btn = button("Pause for…", icon="timer", tooltip="Pause for a while")
+ menu = QMenu(self.later_btn)
+ for text, minutes in (("15 minutes", 15), ("30 minutes", 30), ("1 hour", 60), ("2 hours", 120)):
+ menu.addAction(f"Pause for {text}", lambda m=minutes: ctx.window.pause_for(m))
+ self.later_btn.clicked.connect(
+ lambda: menu.exec(self.later_btn.mapToGlobal(self.later_btn.rect().bottomLeft()))
)
- layout.addWidget(top_label)
-
- scroll = QScrollArea()
- scroll.setWidgetResizable(True)
- scroll.setStyleSheet("QScrollArea { border: none; background: transparent; }")
- self._apps_container = QWidget()
- self._apps_container.setStyleSheet("background: transparent;")
- self._apps_layout = QVBoxLayout(self._apps_container)
- self._apps_layout.setContentsMargins(0, 0, 0, 0)
- self._apps_layout.setSpacing(6)
- self._apps_layout.addStretch()
- scroll.setWidget(self._apps_container)
- layout.addWidget(scroll, stretch=1)
-
- def refresh(self):
- # Now tracking
- exe = self._tracker.current_exe
- if exe and not self._tracker.paused:
- app_id = self._tracker.current_app_id
- app = queries.get_app(app_id) if app_id else None
- label = (app.get("display_name") if app else "") or ""
- if label.strip().lower() == exe.lower() or not label.strip():
- label = queries.normalize_app_name(exe)
- self._now_app.setText(label)
- self._now_timer.setText(theme.format_ms(self._tracker.session_elapsed_ms))
- self._pause_btn.setText("⏸ Pause Tracking")
- elif self._tracker.paused:
- self._now_app.setText("Paused")
- self._now_timer.setText("—")
- self._pause_btn.setText("▶ Resume Tracking")
- else:
- self._now_app.setText("—")
- self._now_timer.setText("0s")
+ actions.addWidget(self.later_btn)
+ actions.addStretch(1)
+ col.addLayout(actions)
+ row.addWidget(self.identity, 1)
+ self.body.addLayout(row)
+ self._last_app: int | None = None
+ self._last_key: tuple | None = None
- # Today total
- today_ms = queries.today_total_ms()
- self._today_total.set_value(theme.format_ms(today_ms))
+ @staticmethod
+ def _fact(caption: str):
+ box = QVBoxLayout()
+ box.setSpacing(2)
+ box.addWidget(eyebrow(caption))
+ value = label("–")
+ value.setFont(fonts.sans(14, 600, tabular=True))
+ box.addWidget(value)
+ return box, value
- # Week total
- week_apps = queries.weekly_totals(limit=100)
- week_ms = sum(a.get("focused_ms", 0) for a in week_apps)
- self._week_total.set_value(theme.format_ms(week_ms))
+ def update_from(self, snap: trk.Snapshot) -> None:
+ tracking = snap.status == trk.STATUS_TRACKING and snap.app_id is not None
+ key = (snap.status, snap.app_id)
+ if self._last_key is not None and key != self._last_key and self.isVisible():
+ motion.fade(self.identity, 0.0, 1.0, motion.NORMAL, motion.DECELERATE)
+ self._last_key = key
+ self.pulse.set_state(tracking, theme.current().accent)
+ self.pulse.setVisible(tracking)
+ self.avatar.setVisible(tracking)
+ self.state_icon.setVisible(not tracking)
+ paused = snap.status == trk.STATUS_PAUSED
+ self.pause_btn.setText("Resume" if paused else "Pause")
+ self.pause_btn.setIcon(icons.icon("play" if paused else "pause", tone_color("text_on"), 14))
+ self.pause_btn.setEnabled(self.ctx.tracker.supported)
+ self.later_btn.setVisible(self.ctx.tracker.supported and not paused)
- # Apps count
- top = queries.dashboard_top_apps_today(limit=50)
- self._apps_count.set_value(str(len(top)))
+ if tracking:
+ app = queries.get_app(snap.app_id) or {"name": snap.exe_name}
+ if snap.app_id != self._last_app:
+ self.avatar.set_app(app["name"], app.get("icon_path"))
+ self._last_app = snap.app_id
+ self.name.setText(app["name"])
+ today = queries.app_usage_on(queries.today_str(), snap.app_id) + snap.uncommitted_ms
+ parts = [app.get("category") or "Uncategorized"]
+ if app.get("daily_limit_ms"):
+ 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.dial.set_state(True, snap.session_ms, "Session")
+ self._set_state("Live", "pillAccent")
+ return
- # Streak
- from ...rewards import engine as reward_engine
- profile = reward_engine.get_profile()
- self._streak.set_value(str(profile.get("streak_days", 0)))
+ self._last_app = None
+ icon, title, detail, pill = {
+ trk.STATUS_PAUSED: ("pause", "Tracking paused", "Nothing is recorded until you resume.", "Paused"),
+ trk.STATUS_IDLE: ("clock", "Away", self._idle_text(), "Idle"),
+ trk.STATUS_LOCKED: ("clock", "Screen locked", "Tracking continues when you unlock.", "Locked"),
+ trk.STATUS_UNSUPPORTED: (
+ "power",
+ "Tracking unavailable",
+ "Foreground tracking needs Windows. Run with --demo to explore with sample data.",
+ "Off",
+ ),
+ }.get(snap.status, ("activity", "Waiting for an app", "Switch to any app to start tracking.", "Ready"))
+ if paused and snap.paused_until:
+ detail = f"Resumes automatically at {fmt.time_of_day(snap.paused_until)}."
+ self.state_icon.setPixmap(icons.pixmap(icon, tone_color("warning" if paused else "text_muted"), 22))
+ self.name.setText(title)
+ self.detail.setText(detail)
+ self.fact_started[1].setText("–")
+ self.fact_today[1].setText("–")
+ self.dial.set_state(False, 0, pill)
+ self._set_state(pill, "pill")
- # Top apps list
- self._rebuild_app_list(top)
+ @staticmethod
+ def _idle_text() -> str:
+ minutes = db.get_int("idle_threshold_sec", 300) // 60
+ return f"No input for {minutes} min. Tracking resumes when you're back."
- def _rebuild_app_list(self, apps: list[dict]):
- # Clear existing
- while self._apps_layout.count() > 1:
- item = self._apps_layout.takeAt(0)
- if item.widget():
- item.widget().deleteLater()
+ def _set_state(self, text: str, role: str) -> None:
+ if self.state.property("role") != role:
+ set_role(self.state, role)
+ self.state.setText(text)
- if not apps:
- empty = QLabel("No apps tracked yet today")
- empty.setStyleSheet(f"color: {theme.TEXT_MUTED}; padding: 20px; background: transparent;")
- empty.setAlignment(Qt.AlignmentFlag.AlignCenter)
- self._apps_layout.insertWidget(0, empty)
- return
- max_ms = max(a.get("focused_ms", 1) for a in apps)
- for i, app in enumerate(apps[:10]):
- raw_name = (app.get("display_name") or "").strip()
- if not raw_name or raw_name.lower() == (app.get("exe_name") or "").lower():
- shown_name = queries.normalize_app_name(app.get("exe_name", ""))
- else:
- shown_name = raw_name
+class DashboardView(Page):
+ def __init__(self, ctx, parent=None):
+ super().__init__(parent)
+ self.setObjectName("page")
+ self.ctx = ctx
+ self._ticks = 0
+ self._yesterday_hours: list[int] | None = None
+ self._day_keys: list[str] = []
+ self._fractions: dict[int, float] = {}
+
+ self.header = PageHeader("Dashboard", "", kicker=_kicker_date())
+ self.add(self.header)
+
+ top = self.stack_when_narrow(QHBoxLayout())
+ top.setSpacing(16)
+ self.now = NowCard(ctx)
+ self.now.setMinimumWidth(380)
+ top.addWidget(self.now, 6)
+ self.t_today = StatTile("Today", framed=False)
+ self.t_week = StatTile("This week", framed=False)
+ self.t_apps = StatTile("Apps used today", framed=False)
+ self.t_streak = StatTile("Streak", framed=False)
+ self.metrics = MetricGrid([self.t_today, self.t_week, self.t_apps, self.t_streak])
+ top.addWidget(self.metrics, 5)
+ self.add(top)
+
+ cols = self.stack_when_narrow(QHBoxLayout())
+ cols.setSpacing(16)
+ charts = QVBoxLayout()
+ charts.setSpacing(16)
+ self.hourly_card = Card("Today by hour", "Focused time in each hour", index=2)
+ self.hourly = BarChart(150)
+ self.hourly_card.body.addWidget(self.hourly)
+ charts.addWidget(self.hourly_card)
+
+ self.days_card = Card("Last 14 days", "Click a day to open it in the calendar", index=3)
+ self.days = BarChart(150)
+ self.days.bar_clicked.connect(self._open_day)
+ self.days_card.body.addWidget(self.days)
+ charts.addWidget(self.days_card)
+ cols.addLayout(charts, 6)
+
+ self.top_card = Card("Top apps today", index=4)
+ self.top_card.header_actions.addWidget(button("View all", kind="link", on_click=self._view_all))
+ self.top_list = QVBoxLayout()
+ self.top_list.setSpacing(2)
+ self.top_card.body.addLayout(self.top_list)
+ self.top_card.body.addStretch(1)
+ self.category_title = eyebrow("By category")
+ self.top_card.body.addWidget(self.category_title)
+ self.share = ShareBar()
+ self.top_card.body.addWidget(self.share)
+ legend_host = QWidget()
+ self.legend = FlowLayout(legend_host)
+ self.top_card.body.addWidget(legend_host)
+ cols.addWidget(self.top_card, 5)
+ self.add(cols)
+ self.layout_.addStretch(1)
+
+ bus.data_changed.connect(lambda: self.isVisible() and self.refresh())
+
+ # ------------------------------------------------------------------
+
+ def refresh(self) -> None:
+ self.header.set_kicker(_kicker_date())
+ snap = self.ctx.snapshot()
+ self._refresh_totals(snap)
+ self._refresh_charts(snap)
+ self._refresh_top(snap)
+ self.now.update_from(snap)
+
+ def tick(self) -> None:
+ self._ticks += 1
+ snap = self.ctx.snapshot()
+ self.now.update_from(snap)
+ self._refresh_totals(snap)
+ if self._ticks % 15 == 0:
+ self._refresh_charts(snap)
+ self._refresh_top(snap)
+
+ def _refresh_totals(self, snap: trk.Snapshot) -> None:
+ today = queries.today_str()
+ live = snap.uncommitted_ms if snap.app_id else 0
+ today_ms = queries.total_ms(today, today) + live
+
+ now = datetime.now()
+ if self._ticks % 60 == 0 or self._yesterday_hours is None:
+ self._yesterday_hours = queries.hourly_totals((date.today() - timedelta(days=1)).isoformat())
+ hours = self._yesterday_hours
+ same_time = sum(hours[: now.hour]) + hours[now.hour] * now.minute / 60
+ change = fmt.percent_change(today_ms, same_time)
+ if change:
+ role = "success" if today_ms >= same_time else "caption"
+ self.t_today.set_number(today_ms, _short, f"{change} vs this time yesterday", role)
+ else:
+ total = sum(hours)
+ sub = f"Yesterday: {fmt.duration(total, short=True)}" if total else "Nothing tracked yesterday"
+ self.t_today.set_number(today_ms, _short, sub)
+
+ 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")
+
+ profile = rewards.get_profile()
+ streak = profile["streak"]
+ fav_today = rewards.favorites_ms(today)
+ current = queries.get_app(snap.app_id) if snap.app_id else None
+ if current and current.get("is_favorite"):
+ fav_today += live
+ if not db.fetchone("SELECT 1 FROM apps WHERE is_favorite = 1 AND is_hidden = 0"):
+ sub = "Star an app to start a streak"
+ elif profile.get("last_streak_day") == today or fav_today >= economy.STREAK_GOAL_MS:
+ sub = "Today's goal is done"
+ else:
+ left = economy.STREAK_GOAL_MS - fav_today
+ sub = f"{fmt.duration(left, short=True)} in favorites to go today"
+ self.t_streak.set_number(streak, _days, sub, tooltip="A streak day needs 30 minutes in your favorite apps.")
+
+ def _refresh_charts(self, snap: trk.Snapshot) -> None:
+ today = date.today()
+ hours = queries.hourly_totals(today.isoformat())
+ if snap.app_id:
+ hours[datetime.now().hour] += snap.uncommitted_ms
+ self.hourly.set_data(
+ [
+ Bar(f"{h:02d}" if h % 3 == 0 else "", ms, f"{h:02d}:00 to {(h + 1) % 24:02d}:00\n{fmt.duration(ms)}")
+ for h, ms in enumerate(hours)
+ ],
+ highlight=datetime.now().hour,
+ empty_text="Nothing tracked today yet",
+ )
+ start = today - timedelta(days=13)
+ totals = queries.daily_totals(start.isoformat(), today.isoformat())
+ self._day_keys = [(start + timedelta(days=i)).isoformat() for i in range(14)]
+ bars = []
+ for key in self._day_keys:
+ d = date.fromisoformat(key)
+ ms = totals.get(key, 0) + (snap.uncommitted_ms if key == today.isoformat() and snap.app_id else 0)
+ bars.append(Bar(str(d.day), ms, f"{fmt.long_date(d)}\n{fmt.duration(ms) if ms else 'No activity'}"))
+ self.days.set_data(bars, highlight=13, empty_text="No activity in the last two weeks")
+
+ def _refresh_top(self, snap: trk.Snapshot) -> None:
+ today = queries.today_str()
+ apps = queries.top_apps(today, today, limit=None)
+ if snap.app_id:
+ for app in apps:
+ if app["app_id"] == snap.app_id:
+ app["focused_ms"] += snap.uncommitted_ms
+ apps.sort(key=lambda a: -a["focused_ms"])
+ total = sum(a["focused_ms"] for a in apps) or 1
+ self.t_apps.set_number(len(apps), _count, f"Most used: {apps[0]['name']}" if apps else "No apps yet today")
+
+ clear_layout(self.top_list)
+ if not apps:
+ self.top_list.addWidget(
+ EmptyState("layout-grid", "No apps yet today", "Apps appear here as soon as they have been in focus.")
+ )
+ peak = apps[0]["focused_ms"] if apps else 1
+ for rank, app in enumerate(apps[:TOP_APPS], start=1):
+ limit = app.get("daily_limit_ms")
+ over = bool(limit and app["focused_ms"] >= limit)
+ fraction = app["focused_ms"] / peak
row = AppRow(
- app_id=app["app_id"],
- name=shown_name,
- value_ms=app.get("focused_ms", 0),
- max_ms=max_ms,
- is_favorite=bool(app.get("is_favorite")),
- icon_path=app.get("icon_path"),
+ app,
+ fmt.duration(app["focused_ms"], short=True),
+ fraction,
+ rank=rank,
+ dot=None if limit else theme.category_color(app.get("category")),
+ animate_from=self._fractions.get(app["app_id"], 0.0),
+ sub=f"Limit {fmt.duration(limit, short=True)}" + (" reached" if over else "")
+ if limit
+ else (app.get("category") or "Uncategorized"),
+ tone="danger" if over else ("accent" if app["app_id"] == snap.app_id else "ink"),
+ extra=f"{app['focused_ms'] / total:.0%}",
+ marker=(limit / peak) if limit and limit < peak else None,
)
- row.clicked.connect(self.app_selected.emit)
- self._apps_layout.insertWidget(i, row)
+ row.clicked.connect(self.ctx.open_app)
+ row.context_requested.connect(self.ctx.app_menu)
+ self.top_list.addWidget(row)
+ self._fractions = {a["app_id"]: a["focused_ms"] / peak for a in apps[:TOP_APPS]}
- def _toggle_pause(self):
- if self._tracker.paused:
- self._tracker.resume()
+ by_cat: dict[str | None, int] = {}
+ for app in apps:
+ by_cat[app.get("category")] = by_cat.get(app.get("category"), 0) + app["focused_ms"]
+ ranked = sorted(by_cat.items(), key=lambda kv: -kv[1])
+ self.share.set_segments([(c or "Uncategorized", ms, theme.category_color(c)) for c, ms in ranked])
+ clear_layout(self.legend)
+ for cat, ms in ranked:
+ self.legend.addWidget(legend_item(theme.category_color(cat), f"{cat or 'Uncategorized'} {ms / total:.0%}"))
+ has_cats = any(c for c in by_cat)
+ for w in (self.category_title, self.share):
+ w.setVisible(bool(apps))
+ self.legend.parentWidget().setVisible(bool(apps))
+ if apps and not has_cats:
+ self.category_title.setText("By category · set categories on an app's page")
else:
- self._tracker.pause()
- self.refresh()
+ self.category_title.setText("By category")
+
+ def _open_day(self, index: int) -> None:
+ if 0 <= index < len(self._day_keys):
+ self.ctx.open_day(self._day_keys[index])
+
+ def _view_all(self) -> None:
+ apps_view = self.ctx.window._views["apps"]
+ apps_view.set_period(0)
+ self.ctx.navigate("apps")
+
+
+def _short(ms: float) -> str:
+ return fmt.duration(ms, short=True)
+
+
+def _count(n: float) -> str:
+ return str(int(round(n)))
+
+
+def _days(n: float) -> str:
+ n = int(round(n))
+ return f"{n} day{'s' if n != 1 else ''}"
+
+
+def _kicker_date() -> str:
+ """Instrument-style date readout, e.g. SAT 03 OCT 2026."""
+ d = date.today()
+ return f"{d:%a} {d.day:02d} {d:%b} {d.year}"
diff --git a/apptrackr/ui/views/rewards_view.py b/apptrackr/ui/views/rewards_view.py
index c9e63fa..37c1d2f 100644
--- a/apptrackr/ui/views/rewards_view.py
+++ b/apptrackr/ui/views/rewards_view.py
@@ -1,161 +1,386 @@
-"""Rewards view – unclaimed rewards + rule editor."""
+"""Rewards: level progress, pending rewards, earning apps and how milestones work."""
from __future__ import annotations
-import json
+from PySide6.QtCore import Qt
+from PySide6.QtWidgets import QComboBox, QGridLayout, QHBoxLayout, QProgressBar, QVBoxLayout, QWidget
-from PySide6.QtCore import Qt, Signal
-from PySide6.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
- QScrollArea, QFrame, QComboBox, QSpinBox, QGraphicsDropShadowEffect,
+from ...data import queries
+from ...game import economy
+from ...game import state as game_state
+from ...rewards import engine as rewards
+from ...rewards import rules
+from .. import fmt, fonts, motion, theme
+from ..signals import bus
+from ..widgets.components import (
+ AppAvatar,
+ Card,
+ EmptyState,
+ Page,
+ PageHeader,
+ animate_progress,
+ button,
+ clear_layout,
+ count_to,
+ eyebrow,
+ icon_label,
+ label,
+ vdivider,
)
-from PySide6.QtGui import QColor
-from .. import theme
-from ..widgets.components import NeonCard, StatValue
-from ...rewards import engine as reward_engine
-from ...rewards import rules as reward_rules
-from ...data import queries
+METRIC_TEXT = {"focused_ms": "focused", "opens_count": "launches", "clicks_count": "clicks"}
-class RewardCard(QFrame):
- """A single unclaimed reward with glow + claim button."""
+class RewardsView(Page):
+ def __init__(self, ctx, parent=None):
+ super().__init__(parent)
+ self.setObjectName("page")
+ self.ctx = ctx
- claimed = Signal(int)
+ self.header = PageHeader(
+ "Rewards", "Time in the apps you choose earns XP and resources for your village.", kicker="Progress"
+ )
+ self.claim_all = button("Claim all", kind="primary", icon="sparkles", on_click=self._claim_all)
+ self.header.actions.addWidget(self.claim_all)
+ self.add(self.header)
- def __init__(self, event: dict, parent=None):
- super().__init__(parent)
- self._event_id = event["event_id"]
- self.setStyleSheet(f"""
- QFrame {{
- background: {theme.BG_CARD};
- border: 1px solid {theme.PURPLE_DIM};
- border-radius: 10px;
- padding: 12px;
- }}
- """)
- shadow = QGraphicsDropShadowEffect(self)
- shadow.setBlurRadius(20)
- shadow.setColor(QColor(theme.PURPLE))
- shadow.setOffset(0, 0)
- self.setGraphicsEffect(shadow)
-
- layout = QHBoxLayout(self)
- layout.setSpacing(12)
-
- # App name
- app_name = event.get("display_name") or event.get("exe_name", "?")
- name_lbl = QLabel(f"🎁 {app_name}")
- name_lbl.setStyleSheet(f"font-weight: 600; color: {theme.TEXT}; background: transparent;")
- layout.addWidget(name_lbl)
-
- # Reward details
- reward = json.loads(event["granted_json"]) if isinstance(event["granted_json"], str) else event["granted_json"]
- parts = []
- for k, v in reward.items():
- parts.append(f"+{v} {k}")
- detail = QLabel(" ".join(parts))
- detail.setStyleSheet(f"color: {theme.get_accent()}; font-weight: 600; background: transparent;")
- layout.addWidget(detail, stretch=1)
-
- # Claim button
- claim = QPushButton("✨ Claim")
- claim.setObjectName("primary")
- claim.clicked.connect(lambda: self.claimed.emit(self._event_id))
- layout.addWidget(claim)
-
-
-class RewardsView(QWidget):
- """Rewards tab – claim pending rewards, view profile, manage rules."""
-
- def __init__(self, parent=None):
- super().__init__(parent)
- self._build_ui()
- self.refresh()
-
- def _build_ui(self):
- layout = QVBoxLayout(self)
- layout.setContentsMargins(24, 24, 24, 24)
- layout.setSpacing(16)
-
- header = QLabel("Rewards")
- header.setObjectName("heading")
- layout.addWidget(header)
-
- # Profile stats
- stats_row = QHBoxLayout()
- self._xp_stat = StatValue("0", "XP", theme.get_accent())
- self._level_stat = StatValue("1", "Level", theme.PURPLE)
- self._streak_stat = StatValue("0", "Streak", theme.YELLOW)
- self._credits_stat = StatValue("0", "Credits", theme.PINK)
-
- for w in (self._xp_stat, self._level_stat, self._streak_stat, self._credits_stat):
- card = NeonCard(glow_color=theme.BG_CARD)
- card.content_layout().addWidget(w)
- stats_row.addWidget(card)
- layout.addLayout(stats_row)
-
- # Claim all
- btn_row = QHBoxLayout()
- self._claim_all_btn = QPushButton("✨ Claim All Rewards")
- self._claim_all_btn.setObjectName("primary")
- self._claim_all_btn.clicked.connect(self._claim_all)
- btn_row.addWidget(self._claim_all_btn)
- btn_row.addStretch()
- layout.addLayout(btn_row)
-
- # Unclaimed rewards
- unclaimed_label = QLabel("Pending Rewards")
- unclaimed_label.setStyleSheet(f"font-size: 16px; font-weight: 700; color: {theme.TEXT}; background: transparent;")
- layout.addWidget(unclaimed_label)
-
- scroll = QScrollArea()
- scroll.setWidgetResizable(True)
- scroll.setStyleSheet("QScrollArea { border: none; background: transparent; }")
- self._rewards_container = QWidget()
- self._rewards_container.setStyleSheet("background: transparent;")
- self._rewards_layout = QVBoxLayout(self._rewards_container)
- self._rewards_layout.setContentsMargins(0, 0, 0, 0)
- self._rewards_layout.setSpacing(8)
- self._rewards_layout.addStretch()
- scroll.setWidget(self._rewards_container)
- layout.addWidget(scroll, stretch=1)
-
- def refresh(self):
- # Profile
- profile = reward_engine.get_profile()
- self._xp_stat.set_value(str(profile.get("xp", 0)))
- self._level_stat.set_value(str(profile.get("level", 1)))
- self._streak_stat.set_value(str(profile.get("streak_days", 0)))
- self._credits_stat.set_value(str(profile.get("credits", 0)))
-
- # Evaluate new rewards first
- reward_engine.evaluate()
-
- # Unclaimed
- unclaimed = reward_engine.unclaimed_rewards()
-
- while self._rewards_layout.count() > 1:
- item = self._rewards_layout.takeAt(0)
- if item.widget():
- item.widget().deleteLater()
-
- if not unclaimed:
- lbl = QLabel("No pending rewards — keep tracking!")
- lbl.setStyleSheet(f"color: {theme.TEXT_MUTED}; padding: 20px; background: transparent;")
- lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
- self._rewards_layout.insertWidget(0, lbl)
+ self.profile = Card(padding=20)
+ top = QHBoxLayout()
+ top.setSpacing(28)
+ level_col = QVBoxLayout()
+ level_col.setSpacing(2)
+ cap = QHBoxLayout()
+ cap.setSpacing(6)
+ cap.addWidget(eyebrow("Level"))
+ self.crown = icon_label("crown", "gold", 14)
+ cap.addWidget(self.crown)
+ cap.addStretch(1)
+ level_col.addLayout(cap)
+ self.level = label("", "hero")
+ level_col.addWidget(self.level)
+ top.addLayout(level_col)
+ progress_col = QVBoxLayout()
+ progress_col.setSpacing(8)
+ progress_col.addStretch(1)
+ self.progress_text = label("", "caption")
+ progress_col.addWidget(self.progress_text)
+ self.progress = QProgressBar()
+ self.progress.setTextVisible(False)
+ self.progress.setProperty("tone", "accent")
+ progress_col.addWidget(self.progress)
+ progress_col.addSpacing(10)
+ top.addLayout(progress_col, 1)
+ self.stat_values = {}
+ for key, caption in (("xp", "Total XP"), ("credits", "Credits"), ("streak", "Streak")):
+ top.addWidget(vdivider())
+ col = QVBoxLayout()
+ col.setSpacing(4)
+ col.addWidget(eyebrow(caption))
+ value = label("–")
+ value.setFont(fonts.sans(20, 600, tabular=True))
+ col.addWidget(value)
+ col.addStretch(1)
+ top.addLayout(col)
+ self.stat_values[key] = value
+ self.profile.body.addLayout(top)
+ self.add(self.profile)
+
+ cols = self.stack_when_narrow(QHBoxLayout())
+ cols.setSpacing(16)
+ left = QVBoxLayout()
+ left.setSpacing(16)
+ self.pending = Card("Pending rewards", index=1)
+ self.pending_list = QVBoxLayout()
+ self.pending_list.setSpacing(2)
+ self.pending.body.addLayout(self.pending_list)
+ left.addWidget(self.pending)
+
+ self.earning = Card("Earning apps", "Progress toward each app's next milestone today", index=2)
+ self.earning_list = QVBoxLayout()
+ self.earning_list.setSpacing(4)
+ self.earning.body.addLayout(self.earning_list)
+ add_row = QHBoxLayout()
+ self.add_combo = QComboBox()
+ self.add_combo.setAccessibleName("App to add")
+ self.add_combo.setMinimumWidth(200)
+ add_row.addWidget(self.add_combo, 1)
+ self.add_btn = button("Add app", icon="plus", on_click=self._add_app)
+ add_row.addWidget(self.add_btn)
+ self.earning.body.addLayout(add_row)
+ left.addWidget(self.earning)
+ left.addStretch(1)
+ cols.addLayout(left, 3)
+
+ self.rules_card = Card("How it works", index=3)
+ self._build_rules(self.rules_card)
+ cols.addWidget(self.rules_card, 2, Qt.AlignmentFlag.AlignTop)
+ self.add(cols)
+ self.layout_.addStretch(1)
+
+ self._shown: dict = {}
+ self._progress: dict[int, int] = {}
+ self._pending_rows: list[QWidget] = []
+ self._added_app: int | None = None
+ bus.rewards_changed.connect(lambda: self.isVisible() and self.refresh())
+ bus.data_changed.connect(lambda: self.isVisible() and self.refresh())
+
+ def _build_rules(self, card: Card) -> None:
+ card.body.addWidget(
+ label(
+ "Each earning app pays out when today's focused time crosses a milestone. "
+ "Repeating milestones pay again every time the amount is reached.",
+ "dim",
+ wrap=True,
+ )
+ )
+ grid = QGridLayout()
+ grid.setHorizontalSpacing(12)
+ grid.setVerticalSpacing(6)
+ row = 0
+ for metric, threshold, reward, repeat in rules.DEFAULT_RULES:
+ if metric != "focused_ms":
+ continue
+ grid.addWidget(
+ label(
+ f"Every {fmt.duration(threshold, short=True)}" if repeat else fmt.duration(threshold, short=True),
+ "muted",
+ ),
+ row,
+ 0,
+ )
+ grid.addWidget(label(fmt.reward(reward, ", ")), row, 1)
+ row += 1
+ card.body.addLayout(grid)
+ card.body.addWidget(label("STREAKS", "eyebrow"))
+ card.body.addWidget(
+ label(
+ "Spend 30 minutes in favorite apps each day to grow a streak. Milestone days pay a bonus.",
+ "dim",
+ wrap=True,
+ )
+ )
+ streaks = QGridLayout()
+ streaks.setHorizontalSpacing(12)
+ streaks.setVerticalSpacing(6)
+ for i, (days, reward) in enumerate(economy.STREAK_REWARDS.items()):
+ streaks.addWidget(label(f"{days} days", "muted"), i, 0)
+ streaks.addWidget(label(fmt.reward(reward, ", ")), i, 1)
+ card.body.addLayout(streaks)
+ card.body.addWidget(
+ label(
+ f"Every {economy.XP_PER_LEVEL} XP is a level. Each new level pays "
+ f"{economy.CREDITS_PER_LEVEL} credits per level number, spendable at the "
+ "village market.",
+ "caption",
+ wrap=True,
+ )
+ )
+
+ # ------------------------------------------------------------------
+
+ def refresh(self) -> None:
+ rewards.evaluate_recent()
+ profile = rewards.get_profile()
+ bonuses = game_state.get_bonuses()
+ self.crown.setVisible(bonuses["has_monument"])
+ self.crown.setToolTip("Monument built")
+ self.level.setText(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 ''}")
+
+ groups = rewards.unclaimed_by_app()
+ self.claim_all.setEnabled(bool(groups))
+ total = sum(len(g["event_ids"]) for g in groups)
+ self.pending.set_title(f"Pending rewards · {total}" if total else "Pending rewards")
+ clear_layout(self.pending_list)
+ self._pending_rows = []
+ if not groups:
+ self.pending_list.addWidget(
+ EmptyState("gift", "Nothing to claim", "New rewards show up here as earning apps reach milestones.")
+ )
+ for g in groups:
+ row = self._pending_row(g)
+ self._pending_rows.append(row)
+ self.pending_list.addWidget(row)
+
+ clear_layout(self.earning_list)
+ milestones = rewards.next_milestones()
+ if not milestones:
+ self.earning_list.addWidget(
+ EmptyState(
+ "zap", "No apps are earning yet", "Pick an app below, or turn on Earn rewards from any app's page."
+ )
+ )
+ progress = {}
+ for item in milestones:
+ row = self._earning_row(item)
+ self.earning_list.addWidget(row)
+ progress[item["app_id"]] = row.bar_value
+ if item["app_id"] == self._added_app:
+ motion.fade(row, 0.0, 1.0, motion.NORMAL)
+ self._progress = progress
+ self._added_app = None
+
+ earning = rules.earning_app_ids()
+ self.add_combo.clear()
+ for app in queries.top_apps(queries.days_ago(29), queries.today_str(), limit=None):
+ if app["app_id"] not in earning:
+ self.add_combo.addItem(app["name"], app["app_id"])
+ self.add_combo.setEnabled(self.add_combo.count() > 0)
+ self.add_btn.setEnabled(self.add_combo.count() > 0)
+ if not self.add_combo.count():
+ self.add_combo.addItem("All recent apps are earning")
+
+ def _pending_row(self, group: dict) -> QWidget:
+ row = QWidget()
+ row.setProperty("row", True)
+ lay = QHBoxLayout(row)
+ lay.setContentsMargins(6, 6, 4, 6)
+ lay.setSpacing(12)
+ lay.addWidget(AppAvatar(group["name"], None, 30))
+ text = QVBoxLayout()
+ text.setSpacing(0)
+ name = label(group["name"])
+ name.setStyleSheet("font-weight: 600;")
+ text.addWidget(name)
+ 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")
+ amounts.setFont(fonts.mono(10, 500, 2))
+ lay.addWidget(amounts)
+ lay.addWidget(button("Claim", on_click=lambda ids=group["event_ids"]: self._claim(ids, row)))
+ return row
+
+ def _earning_row(self, item: dict) -> QWidget:
+ row = QWidget()
+ lay = QHBoxLayout(row)
+ lay.setContentsMargins(0, 4, 0, 4)
+ lay.setSpacing(12)
+ lay.addWidget(AppAvatar(item["name"], item.get("icon_path"), 28))
+ col = QVBoxLayout()
+ col.setSpacing(4)
+ top = QHBoxLayout()
+ name = label(item["name"])
+ name.setStyleSheet("font-weight: 600;")
+ top.addWidget(name)
+ top.addStretch(1)
+ nxt = item["next"]
+ if nxt:
+ top.addWidget(
+ label(
+ f"{fmt.duration(item['focused_ms'], short=True)} / {fmt.duration(nxt['target_ms'], short=True)}",
+ "caption",
+ )
+ )
+ col.addLayout(top)
+ bar = QProgressBar()
+ bar.setTextVisible(False)
+ bar.setMaximum(1000)
+ value = int(1000 * item["focused_ms"] / max(1, nxt["target_ms"])) if nxt else 1000
+ col.addWidget(bar)
+ 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"))
+ else:
+ col.addWidget(label("All milestones reached today", "caption"))
+ lay.addLayout(col, 1)
+ remove = button(
+ "",
+ kind="ghost",
+ icon="x",
+ tooltip=f"Stop earning rewards for {item['name']}",
+ on_click=lambda: self._remove_app(item["app_id"], item["name"], row),
+ )
+ lay.addWidget(remove, 0, Qt.AlignmentFlag.AlignTop)
+ return row
+
+ # ------------------------------------------------------------------
+
+ def _animate_profile(self, profile: dict, into: int) -> None:
+ """Count XP and credits, and fill the level bar (wrapping on a level-up)."""
+ shown = self._shown
+ self._shown = {"xp": profile["xp"], "credits": profile["credits"], "level": profile["level"], "into": into}
+ if not shown:
+ self.progress.setValue(into)
+ self.stat_values["xp"].setText(fmt.count(profile["xp"]))
+ self.stat_values["credits"].setText(fmt.count(profile["credits"]))
+ return
+ for key in ("xp", "credits"):
+ if shown[key] != profile[key]:
+ count_to(self.stat_values[key], shown[key], profile[key], lambda v: fmt.count(int(round(v))))
+ if profile["level"] > shown["level"]:
+ bar = self.progress
+
+ def restart():
+ bar.setValue(0)
+ animate_progress(bar, 0, into)
+
+ motion.tween(
+ bar,
+ float(shown["into"]),
+ float(bar.maximum()),
+ motion.SLOW,
+ lambda v: bar.setValue(int(v)),
+ motion.EASY_EASE,
+ restart,
+ key="progress",
+ )
+ motion.flash(self.level, theme.current().gold, radius=6)
+ elif shown["into"] != into:
+ 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)))
+
+ 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)
+ for row in rows[1:]:
+ motion.collapse(row, lambda: None)
+ motion.collapse(rows[0], lambda: self._report(rewards.claim_many()))
+
+ def _report(self, applied: dict) -> None:
+ bus.rewards_changed.emit() # refreshes this page while it is visible
+ if not self.isVisible():
+ self.refresh()
+ if applied:
+ motion.flash(self.profile)
+ 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!"
+ self.ctx.toast(msg)
+
+ def _changed(self) -> None:
+ bus.rewards_changed.emit()
+ if not self.isVisible():
+ self.refresh()
+
+ def _add_app(self) -> None:
+ app_id = self.add_combo.currentData()
+ if app_id is None:
return
+ rules.enable_app_rewards(app_id, True)
+ self._added_app = app_id
+ self.ctx.toast(f"{self.add_combo.currentText()} now earns rewards")
+ self._changed()
- for i, evt in enumerate(unclaimed):
- card = RewardCard(evt)
- card.claimed.connect(self._on_claim)
- self._rewards_layout.insertWidget(i, card)
+ def _remove_app(self, app_id: int, name: str, row: QWidget) -> None:
+ def remove():
+ rules.enable_app_rewards(app_id, False)
+ self._changed()
- def _on_claim(self, event_id: int):
- reward_engine.claim_reward(event_id)
- self.refresh()
+ def undo():
+ rules.enable_app_rewards(app_id, True)
+ self._added_app = app_id
+ self._changed()
- def _claim_all(self):
- reward_engine.claim_all()
- self.refresh()
+ motion.collapse(row, remove)
+ 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 d2018b6..f10b81c 100644
--- a/apptrackr/ui/views/settings_view.py
+++ b/apptrackr/ui/views/settings_view.py
@@ -1,337 +1,551 @@
-"""Settings view – idle, privacy, autostart, export."""
+"""Settings. Every control applies immediately."""
from __future__ import annotations
-import os
import sys
+import threading
+import time
+from pathlib import Path
-from PySide6.QtCore import Qt
+from PySide6.QtCore import QObject, QRectF, QSize, Qt, QUrl, Signal
+from PySide6.QtGui import QColor, QDesktopServices, QPainter, QPen
from PySide6.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
- QSpinBox, QCheckBox, QFrame, QFileDialog, QMessageBox, QLineEdit,
- QComboBox, QScrollArea,
+ QAbstractButton,
+ QButtonGroup,
+ QComboBox,
+ QFileDialog,
+ QGridLayout,
+ QHBoxLayout,
+ QLineEdit,
+ QMessageBox,
+ QProgressDialog,
+ QVBoxLayout,
+ QWidget,
)
-from .. import theme
-from ..widgets.components import NeonCard
-from ...data import db, export
-from ...updater import check as updater_check
+from ... import APP_NAME, REPO_URL, __version__
+from ...core import autostart
+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 ..signals import bus, run_async
+from ..widgets.components import (
+ Card,
+ ElidedLabel,
+ Page,
+ PageHeader,
+ SegmentedControl,
+ SettingRow,
+ Toggle,
+ button,
+ clear_layout,
+ divider,
+ label,
+)
+
+IDLE_CHOICES = (
+ ("Never", 0),
+ ("1 minute", 60),
+ ("2 minutes", 120),
+ ("3 minutes", 180),
+ ("5 minutes", 300),
+ ("10 minutes", 600),
+ ("15 minutes", 900),
+ ("30 minutes", 1800),
+)
+SHORTCUTS = (
+ ("Ctrl+1 … Ctrl+5", "Switch page"),
+ ("Ctrl+,", "Settings"),
+ ("Ctrl+F", "Search apps"),
+ ("Ctrl+Shift+P", "Pause or resume tracking"),
+ ("Esc / Alt+Left", "Back from an app"),
+ ("F5", "Refresh"),
+ ("Ctrl+Q", "Quit"),
+)
+
+
+class _ProgressRelay(QObject):
+ progress = Signal(int, int)
-class SettingsView(QWidget):
- """Application settings panel."""
+class Swatch(QAbstractButton):
+ """Round accent color picker button."""
- def __init__(self, tracker=None, parent=None):
+ def __init__(self, name: str, color: str, parent=None):
super().__init__(parent)
- self._tracker = tracker
- self._build_ui()
- self._load()
-
- def _build_ui(self):
- root_layout = QVBoxLayout(self)
- root_layout.setContentsMargins(0, 0, 0, 0)
- root_layout.setSpacing(0)
-
- scroll = QScrollArea()
- scroll.setWidgetResizable(True)
- scroll.setFrameShape(QFrame.Shape.NoFrame)
- root_layout.addWidget(scroll)
-
- content = QWidget()
- scroll.setWidget(content)
-
- layout = QVBoxLayout(content)
- layout.setContentsMargins(24, 24, 24, 24)
- layout.setSpacing(16)
-
- header = QLabel("Settings")
- header.setObjectName("heading")
- layout.addWidget(header)
-
- # -- Tracking --
- track_card = NeonCard(glow_color=theme.BG_CARD, title="TRACKING")
- tl = track_card.content_layout()
-
- # Idle threshold
- idle_row = QHBoxLayout()
- idle_row.setSpacing(16)
- idle_lbl = QLabel("Idle threshold (seconds):")
- idle_lbl.setStyleSheet("background: transparent;")
- idle_row.addWidget(idle_lbl)
- self._idle_spin = QSpinBox()
- self._idle_spin.setRange(0, 3600)
- self._idle_spin.setSingleStep(30)
- self._idle_spin.setFixedWidth(100)
- self._idle_spin.setToolTip("0 = disabled")
- idle_row.addWidget(self._idle_spin)
- idle_row.addStretch()
- tl.addLayout(idle_row)
-
- # Polling rate
- poll_row = QHBoxLayout()
- poll_row.setSpacing(16)
- poll_lbl = QLabel("Polling rate (Hz):")
- poll_lbl.setStyleSheet("background: transparent;")
- poll_row.addWidget(poll_lbl)
- self._poll_spin = QSpinBox()
- self._poll_spin.setRange(1, 10)
- self._poll_spin.setFixedWidth(100)
- poll_row.addWidget(self._poll_spin)
- poll_row.addStretch()
- tl.addLayout(poll_row)
-
- layout.addWidget(track_card)
-
- # -- Privacy --
- privacy_card = NeonCard(glow_color=theme.BG_CARD, title="PRIVACY")
- pl = privacy_card.content_layout()
-
- self._title_check = QCheckBox("Track window titles (hashed)")
- pl.addWidget(self._title_check)
-
- self._click_check = QCheckBox("Track mouse clicks (count only)")
- pl.addWidget(self._click_check)
-
- layout.addWidget(privacy_card)
-
- # -- System --
- sys_card = NeonCard(glow_color=theme.BG_CARD, title="SYSTEM")
- sl = sys_card.content_layout()
-
- self._autostart_check = QCheckBox("Launch on system startup")
- sl.addWidget(self._autostart_check)
-
- self._tray_check = QCheckBox("Minimize to system tray")
- sl.addWidget(self._tray_check)
-
- self._rewards_check = QCheckBox("Enable rewards system")
- sl.addWidget(self._rewards_check)
-
- layout.addWidget(sys_card)
-
- # -- Data --
- data_card = NeonCard(glow_color=theme.BG_CARD, title="DATA")
- dl = data_card.content_layout()
-
- btn_row = QHBoxLayout()
- export_csv_btn = QPushButton("Export CSV")
- export_csv_btn.clicked.connect(self._export_csv)
- btn_row.addWidget(export_csv_btn)
-
- export_json_btn = QPushButton("Export JSON")
- export_json_btn.clicked.connect(self._export_json)
- btn_row.addWidget(export_json_btn)
-
- backup_btn = QPushButton("Backup Database")
- backup_btn.clicked.connect(self._backup)
- btn_row.addWidget(backup_btn)
-
- restore_btn = QPushButton("Restore Backup")
- restore_btn.clicked.connect(self._restore)
- btn_row.addWidget(restore_btn)
-
- btn_row.addStretch()
- dl.addLayout(btn_row)
-
- # DB location
- db_path = QLabel(f"DB: {db._db_path()}")
- db_path.setStyleSheet(f"color: {theme.TEXT_MUTED}; font-size: 11px; background: transparent;")
- dl.addWidget(db_path)
-
- layout.addWidget(data_card)
-
- # -- Appearance --
- appearance_card = NeonCard(glow_color=theme.BG_CARD, title="APPEARANCE")
- al = appearance_card.content_layout()
-
- theme_row = QHBoxLayout()
- theme_row.setSpacing(16)
- theme_lbl = QLabel("Theme Color:")
- theme_lbl.setStyleSheet("background: transparent;")
- theme_row.addWidget(theme_lbl)
- self._theme_combo = QComboBox()
- self._theme_combo.addItems(list(theme.THEME_PRESETS.keys()))
- self._theme_combo.setFixedWidth(150)
- theme_row.addWidget(self._theme_combo)
- theme_row.addStretch()
- al.addLayout(theme_row)
-
- theme_note = QLabel("Changes apply after restart")
- theme_note.setStyleSheet(f"color: {theme.TEXT_MUTED}; font-size: 11px; background: transparent;")
- al.addWidget(theme_note)
-
- layout.addWidget(appearance_card)
-
- # -- Updates --
- updates_card = NeonCard(glow_color=theme.BG_CARD, title="UPDATES")
- ul = updates_card.content_layout()
-
- self._auto_update_check = QCheckBox("Automatically check for updates on startup")
- ul.addWidget(self._auto_update_check)
-
- url_row = QHBoxLayout()
- url_row.setSpacing(16)
- url_lbl = QLabel("Update feed URL:")
- url_lbl.setStyleSheet("background: transparent;")
- url_row.addWidget(url_lbl)
- self._update_url_edit = QLineEdit()
- self._update_url_edit.setPlaceholderText("https://api.github.com/repos///releases/latest")
- url_row.addWidget(self._update_url_edit, stretch=1)
- ul.addLayout(url_row)
-
- update_actions = QHBoxLayout()
- check_btn = QPushButton("Check for Updates")
- check_btn.clicked.connect(self._check_for_updates)
- update_actions.addWidget(check_btn)
- update_actions.addStretch()
- ul.addLayout(update_actions)
-
- update_note = QLabel("If an update is found, AppTrackr can download and launch the new installer.")
- update_note.setWordWrap(True)
- update_note.setStyleSheet(f"color: {theme.TEXT_MUTED}; font-size: 11px; background: transparent;")
- ul.addWidget(update_note)
-
- layout.addWidget(updates_card)
-
- # Save button
- save_row = QHBoxLayout()
- save_btn = QPushButton("Save Settings")
- save_btn.setObjectName("primary")
- save_btn.clicked.connect(self._save)
- save_row.addWidget(save_btn)
- save_row.addStretch()
- layout.addLayout(save_row)
-
- layout.addStretch()
-
- def _load(self):
- self._idle_spin.setValue(int(db.get_setting("idle_threshold_sec", "300")))
- self._poll_spin.setValue(int(db.get_setting("polling_hz", "4")))
- self._title_check.setChecked(db.get_setting("track_window_titles", "0") == "1")
- self._click_check.setChecked(db.get_setting("track_clicks", "0") == "1")
- self._autostart_check.setChecked(db.get_setting("autostart", "0") == "1")
- self._tray_check.setChecked(db.get_setting("minimize_to_tray", "1") == "1")
- self._rewards_check.setChecked(db.get_setting("rewards_enabled", "1") == "1")
- self._auto_update_check.setChecked(db.get_setting("auto_update_check", "1") == "1")
- self._update_url_edit.setText(db.get_setting("update_url", ""))
-
- # Theme
- current_theme = db.get_setting("ui_theme", "Cyan")
- idx = self._theme_combo.findText(current_theme)
- if idx >= 0:
- self._theme_combo.setCurrentIndex(idx)
-
- def _save(self):
- db.set_setting("idle_threshold_sec", str(self._idle_spin.value()))
- db.set_setting("polling_hz", str(self._poll_spin.value()))
- db.set_setting("track_window_titles", "1" if self._title_check.isChecked() else "0")
- db.set_setting("track_clicks", "1" if self._click_check.isChecked() else "0")
- db.set_setting("autostart", "1" if self._autostart_check.isChecked() else "0")
- db.set_setting("minimize_to_tray", "1" if self._tray_check.isChecked() else "0")
- db.set_setting("rewards_enabled", "1" if self._rewards_check.isChecked() else "0")
- db.set_setting("ui_theme", self._theme_combo.currentText())
- db.set_setting("auto_update_check", "1" if self._auto_update_check.isChecked() else "0")
- db.set_setting("update_url", self._update_url_edit.text().strip())
-
- # Apply autostart
- self._apply_autostart(self._autostart_check.isChecked())
-
- if self._tracker:
- self._tracker.reload_settings()
-
- QMessageBox.information(self, "Settings", "Settings saved.")
-
- def _apply_autostart(self, enable: bool):
- """Set or remove autostart via Windows registry."""
- try:
- import winreg
- key = winreg.OpenKey(
- winreg.HKEY_CURRENT_USER,
- r"Software\Microsoft\Windows\CurrentVersion\Run",
- 0, winreg.KEY_SET_VALUE,
+ 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)
+
+ 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))
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.drawRoundedRect(QRectF(1.5, 1.5, 25, 25), 5, 5)
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(self.color))
+ p.drawRoundedRect(QRectF(6, 6, 16, 16), 3, 3)
+
+
+class SettingsView(Page):
+ def __init__(self, ctx, parent=None):
+ super().__init__(parent)
+ self.setObjectName("page")
+ self.ctx = ctx
+ self.add(PageHeader("Settings", "Changes are saved automatically.", kicker="Preferences"))
+
+ self.update_banner = Card(padding=14)
+ self.update_banner.setProperty("card", False)
+ self.update_banner.setProperty("banner", True)
+ banner_row = QHBoxLayout()
+ self.update_text = label("", wrap=True)
+ banner_row.addWidget(self.update_text, 1)
+ self.update_btn = button("Download and install", kind="primary", on_click=self._install_update)
+ banner_row.addWidget(self.update_btn)
+ self.update_banner.body.addLayout(banner_row)
+ self.update_banner.hide()
+ self.add(self.update_banner)
+
+ self._build_general()
+ self._build_tracking()
+ self._build_appearance()
+ self._build_data()
+ self._build_updates()
+ self._build_about()
+ self.layout_.addStretch(1)
+
+ # ------------------------------------------------------------------
+ # Sections
+ # ------------------------------------------------------------------
+
+ def _build_general(self) -> None:
+ card = Card("General", index=1)
+ self.autostart = Toggle()
+ self.autostart.toggled.connect(self._set_autostart)
+ desc = "Starts in the tray when you sign in to Windows."
+ if not autostart.supported():
+ desc = "Available on Windows."
+ self.autostart.setEnabled(False)
+ card.body.addWidget(SettingRow("Launch at startup", desc, self.autostart))
+ card.body.addWidget(divider())
+ self.tray = Toggle()
+ self.tray.toggled.connect(lambda on: self._save("minimize_to_tray", on, "Close behavior updated"))
+ card.body.addWidget(
+ SettingRow(
+ "Keep running when closed",
+ "Closing the window hides it to the system tray so tracking continues.",
+ self.tray,
)
- if enable:
- exe = sys.executable
- if getattr(sys, "frozen", False):
- cmd = f'"{exe}"'
- else:
- cmd = f'"{exe}" -m apptrackr'
- winreg.SetValueEx(key, "AppTrackr", 0, winreg.REG_SZ, cmd)
- else:
- try:
- winreg.DeleteValue(key, "AppTrackr")
- except FileNotFoundError:
- pass
- winreg.CloseKey(key)
- except Exception:
- pass
-
- def _export_csv(self):
- path, _ = QFileDialog.getSaveFileName(self, "Export CSV", "apptrackr_export.csv", "CSV (*.csv)")
- if path:
- export.export_csv(path)
- QMessageBox.information(self, "Export", f"Exported to {path}")
-
- def _export_json(self):
- path, _ = QFileDialog.getSaveFileName(self, "Export JSON", "apptrackr_export.json", "JSON (*.json)")
- if path:
- export.export_json(path)
- QMessageBox.information(self, "Export", f"Exported to {path}")
-
- def _backup(self):
- path, _ = QFileDialog.getSaveFileName(self, "Backup Database", "apptrackr_backup.sqlite", "SQLite (*.sqlite)")
- if path:
- export.backup_db(path)
- QMessageBox.information(self, "Backup", f"Backed up to {path}")
-
- def _restore(self):
- path, _ = QFileDialog.getOpenFileName(self, "Restore Backup", "", "SQLite (*.sqlite)")
- if path:
- reply = QMessageBox.warning(
- self, "Restore",
- "This will replace your current data. The app will restart. Continue?",
- QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
+ )
+ card.body.addWidget(divider())
+ self.notifications = Toggle()
+ self.notifications.toggled.connect(lambda on: self._save("notifications_enabled", on))
+ card.body.addWidget(
+ SettingRow(
+ "Notifications", "Daily limits, streaks and updates while the window is hidden.", self.notifications
+ )
+ )
+ card.body.addWidget(divider())
+ self.rewards = Toggle()
+ self.rewards.toggled.connect(self._set_rewards)
+ card.body.addWidget(
+ SettingRow(
+ "Rewards and village",
+ "XP, levels and the village game. Turning this off hides both pages; nothing is deleted.",
+ self.rewards,
+ )
+ )
+ self.add(card)
+
+ 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)
+ card.body.addWidget(
+ SettingRow(
+ "Idle timeout",
+ "Stop counting after this long without keyboard or mouse "
+ "input. Time up to your last input still counts.",
+ self.idle,
)
- if reply == QMessageBox.StandardButton.Yes:
- export.restore_db(path)
- QMessageBox.information(self, "Restore", "Restored. Please restart the app.")
-
- def _check_for_updates(self):
- update_url = self._update_url_edit.text().strip() or db.get_setting("update_url", "")
- if not update_url:
- QMessageBox.information(
- self,
- "Updates",
- "Set an Update feed URL first.\n\n"
- "Example:\nhttps://api.github.com/repos///releases/latest",
+ )
+ card.body.addWidget(divider())
+ self.clicks = Toggle()
+ self.clicks.toggled.connect(self._set_clicks)
+ card.body.addWidget(
+ SettingRow(
+ "Count mouse clicks",
+ "Stores a click count per app per day. Positions, buttons and keystrokes are never recorded.",
+ self.clicks,
+ )
+ )
+ card.body.addWidget(divider())
+ card.body.addWidget(
+ SettingRow(
+ "Excluded apps",
+ "Excluded apps are not tracked and are hidden everywhere. Right-click any app to exclude it.",
)
+ )
+ self.excluded = QVBoxLayout()
+ self.excluded.setSpacing(4)
+ card.body.addLayout(self.excluded)
+ self.add(card)
+
+ 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(divider())
+ swatches = QWidget()
+ lay = QHBoxLayout(swatches)
+ lay.setContentsMargins(0, 0, 0, 0)
+ lay.setSpacing(2)
+ self.swatch_group = QButtonGroup(self)
+ self.swatches: dict[str, Swatch] = {}
+ for name, color in theme.ACCENTS.items():
+ sw = Swatch(name, color)
+ self.swatch_group.addButton(sw)
+ 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(divider())
+ self.animations = Toggle()
+ self.animations.toggled.connect(self._set_animations)
+ card.body.addWidget(
+ SettingRow(
+ "Animations",
+ "Transitions, counters and chart motion. Follows Windows' Animation effects setting until changed.",
+ self.animations,
+ )
+ )
+ self.add(card)
+
+ def _build_data(self) -> None:
+ card = Card("Data", "Usage is stored only on this computer.", index=4)
+ row = QHBoxLayout()
+ row.setSpacing(8)
+ row.addWidget(button("Export CSV", icon="download", on_click=lambda: self._export("csv")))
+ row.addWidget(button("Export JSON", icon="download", on_click=lambda: self._export("json")))
+ row.addWidget(button("Back up…", icon="database", on_click=self._backup))
+ row.addWidget(button("Restore…", icon="archive-restore", on_click=self._restore))
+ row.addStretch(1)
+ row.addWidget(button("Open data folder", kind="ghost", icon="folder-open", on_click=self._open_folder))
+ card.body.addLayout(row)
+ self.db_path = ElidedLabel("", "caption") # long data paths must not widen the page
+ card.body.addWidget(self.db_path)
+ self.add(card)
+
+ def _build_updates(self) -> None:
+ card = Card("Updates", index=5)
+ self.auto_update = Toggle()
+ self.auto_update.toggled.connect(lambda on: self._save("auto_update_check", on))
+ card.body.addWidget(
+ SettingRow(
+ "Check for updates automatically",
+ "Asks GitHub for the latest release once a day. Nothing else is sent.",
+ self.auto_update,
+ )
+ )
+ card.body.addWidget(divider())
+ check_row = QHBoxLayout()
+ self.version_label = label(f"{APP_NAME} {__version__}")
+ self.version_label.setStyleSheet("font-weight: 600;")
+ check_row.addWidget(self.version_label)
+ self.update_status = label("", "caption")
+ check_row.addWidget(self.update_status, 1)
+ self.check_btn = button("Check now", icon="refresh-cw", on_click=self._check_updates)
+ check_row.addWidget(self.check_btn)
+ card.body.addLayout(check_row)
+ self.feed = QLineEdit()
+ self.feed.setPlaceholderText(updater.DEFAULT_UPDATE_URL)
+ self.feed.setAccessibleName("Update feed URL")
+ self.feed.editingFinished.connect(lambda: self._save("update_url", self.feed.text().strip()))
+ card.body.addWidget(
+ SettingRow("Release feed", "GitHub releases API URL. Leave empty for the official releases.", None)
+ )
+ card.body.addWidget(self.feed)
+ self.add(card)
+
+ def _build_about(self) -> None:
+ card = Card("About", index=6)
+ links = QHBoxLayout()
+ links.setSpacing(16)
+ for text, url in (
+ ("Source code", REPO_URL),
+ ("Report an issue", REPO_URL + "/issues"),
+ ("Releases", REPO_URL + "/releases"),
+ ("License (MIT)", REPO_URL + "/blob/main/LICENSE"),
+ ):
+ links.addWidget(button(text, kind="link", on_click=lambda u=url: QDesktopServices.openUrl(QUrl(u))))
+ links.addStretch(1)
+ card.body.addLayout(links)
+ card.body.addWidget(label("KEYBOARD SHORTCUTS", "eyebrow"))
+ grid = QGridLayout()
+ grid.setHorizontalSpacing(14)
+ grid.setVerticalSpacing(6)
+ for i, (keys, action) in enumerate(SHORTCUTS):
+ k = label(keys)
+ k.setObjectName("kbd")
+ grid.addWidget(k, i // 2, (i % 2) * 2, Qt.AlignmentFlag.AlignLeft)
+ grid.addWidget(label(action, "dim"), i // 2, (i % 2) * 2 + 1)
+ grid.setColumnStretch(1, 1)
+ grid.setColumnStretch(3, 1)
+ card.body.addLayout(grid)
+ self.add(card)
+
+ # ------------------------------------------------------------------
+ # Load
+ # ------------------------------------------------------------------
+
+ def refresh(self) -> None:
+ self.autostart.set_silently(autostart.is_enabled())
+ self.tray.set_silently(db.get_bool("minimize_to_tray", True))
+ self.notifications.set_silently(db.get_bool("notifications_enabled", True))
+ self.rewards.set_silently(db.get_bool("rewards_enabled", True))
+ self.clicks.set_silently(db.get_bool("track_clicks"))
+ self.auto_update.set_silently(db.get_bool("auto_update_check", True))
+ 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())
+ self.mode.set_current(theme.MODES.index(theme.mode()))
+ self.swatches[theme.accent_name()].setChecked(True)
+ self.db_path.setText(f"Database: {db.db_path()}")
+ self._fill_excluded()
+
+ info = self.ctx.update_info
+ self.update_banner.setVisible(info is not None)
+ if info:
+ self.update_text.setText(f"{APP_NAME} {info.version} is available. You have {__version__}.")
+ self.update_btn.setVisible(bool(info.download_url) and sys.platform.startswith("win"))
+
+ def _fill_excluded(self) -> None:
+ clear_layout(self.excluded)
+ hidden = queries.hidden_apps()
+ if not hidden:
+ self.excluded.addWidget(label("No excluded apps.", "muted"))
return
-
- info = updater_check.check_for_update(update_url)
- if not info:
- QMessageBox.information(self, "Updates", "You're up to date.")
+ for app in hidden:
+ row = QWidget()
+ lay = QHBoxLayout(row)
+ lay.setContentsMargins(0, 0, 0, 0)
+ lay.setSpacing(10)
+ lay.addWidget(label(app["name"]))
+ lay.addWidget(label(app["exe_name"], "caption"), 1)
+ lay.addWidget(button("Track again", kind="ghost", on_click=lambda a=app, r=row: self._include(a, r)))
+ self.excluded.addWidget(row)
+
+ # ------------------------------------------------------------------
+ # Handlers
+ # ------------------------------------------------------------------
+
+ def _save(self, key: str, value, message: str = "Saved") -> None:
+ db.set_setting(key, value)
+ self.ctx.toast(message)
+
+ def _set_autostart(self, on: bool) -> None:
+ if autostart.set_enabled(on):
+ self.ctx.toast("AppTrackr will start when you sign in" if on else "Launch at startup turned off")
+ else:
+ self.autostart.set_silently(autostart.is_enabled())
+ self.ctx.toast("Could not change the startup setting", "danger")
+
+ def _set_rewards(self, on: bool) -> None:
+ db.set_setting("rewards_enabled", on)
+ 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()
+ 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()}")
+
+ def _set_clicks(self, on: bool) -> None:
+ db.set_setting("track_clicks", on)
+ if self.ctx.clicks is not None:
+ self.ctx.clicks.set_enabled(on)
+ self.ctx.toast("Click counting on" if on else "Click counting off")
+
+ def _set_animations(self, on: bool) -> None:
+ motion.set_enabled(on)
+ self.ctx.toast("Animations on" if on else "Animations off")
+
+ def _set_mode(self, index: int) -> None:
+ db.set_setting("ui_mode", theme.MODES[index])
+ self.ctx.window.apply_theme()
+
+ def _set_accent(self, name: str) -> None:
+ db.set_setting("ui_theme", name)
+ self.ctx.window.apply_theme()
+
+ def _include(self, app: dict, row: QWidget) -> None:
+ queries.set_hidden(app["app_id"], False)
+ self.ctx.tracker.reload_settings()
+ bus.data_changed.emit()
+ motion.collapse(row, self._fill_excluded)
+ self.ctx.toast(f"{app['name']} is tracked again")
+
+ # Data ----------------------------------------------------------------
+
+ def _export(self, kind: str) -> None:
+ default = f"apptrackr-{queries.today_str()}.{kind}"
+ path, _ = QFileDialog.getSaveFileName(
+ self, f"Export {kind.upper()}", default, "CSV (*.csv)" if kind == "csv" else "JSON (*.json)"
+ )
+ if not path:
+ return
+ try:
+ n = export.export_csv(path) if kind == "csv" else export.export_json(path)
+ except OSError as exc:
+ QMessageBox.warning(self, "Export failed", str(exc))
return
+ self.ctx.toast(
+ f"Exported {n:,} rows",
+ action="Show",
+ callback=lambda: QDesktopServices.openUrl(QUrl.fromLocalFile(str(Path(path).parent))),
+ )
- version = info.get("version", "unknown")
- url = info.get("url", "")
- if not url:
- QMessageBox.information(self, "Updates", f"Update v{version} found, but no installer asset was published.")
+ def _backup(self) -> None:
+ path, _ = QFileDialog.getSaveFileName(
+ self,
+ "Back up database",
+ f"apptrackr-backup-{queries.today_str()}.sqlite",
+ "SQLite database (*.sqlite *.db)",
+ )
+ if not path:
+ return
+ try:
+ export.backup_db(path)
+ except Exception as exc:
+ QMessageBox.warning(self, "Backup failed", str(exc))
return
+ self.ctx.toast("Backup saved")
- reply = QMessageBox.question(
+ def _restore(self) -> None:
+ path, _ = QFileDialog.getOpenFileName(
+ self, "Restore backup", "", "SQLite database (*.sqlite *.db);;All files (*)"
+ )
+ if not path:
+ return
+ try:
+ export.validate_backup(path)
+ except export.RestoreError as exc:
+ QMessageBox.warning(self, "Cannot restore", str(exc))
+ return
+ reply = QMessageBox.warning(
self,
- "Update Available",
- f"AppTrackr v{version} is available. Download and launch installer now?",
- QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
+ "Replace current data?",
+ "Restoring replaces everything AppTrackr has recorded with the contents of the backup. "
+ "Consider backing up first.\n\nContinue?",
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
+ QMessageBox.StandardButton.Cancel,
)
if reply != QMessageBox.StandardButton.Yes:
return
-
- downloaded = updater_apply.download_and_apply(url)
- if not downloaded:
- QMessageBox.warning(self, "Updates", "Download failed. Please try again later.")
+ tracker = self.ctx.tracker
+ was_paused = tracker.paused
+ paused_until = tracker.snapshot().paused_until
+ tracker.pause()
+ try:
+ export.restore_db(path)
+ except Exception as exc:
+ QMessageBox.warning(self, "Restore failed", str(exc))
return
-
- QMessageBox.information(self, "Updates", "Installer launched. AppTrackr will now close.")
- sys.exit(0)
+ finally:
+ tracker.resume()
+ if was_paused:
+ remaining = (paused_until - time.time()) / 60 if paused_until else None
+ if remaining is None or remaining > 0:
+ tracker.pause(remaining)
+ tracker.reload_settings()
+ bus.data_changed.emit()
+ bus.rewards_changed.emit()
+ self.ctx.window.apply_theme()
+ self.refresh()
+ self.ctx.toast("Backup restored")
+
+ def _open_folder(self) -> None:
+ folder = db.db_path().parent
+ folder.mkdir(parents=True, exist_ok=True)
+ QDesktopServices.openUrl(QUrl.fromLocalFile(str(folder)))
+
+ # Updates -------------------------------------------------------------
+
+ def _check_updates(self) -> None:
+ self.check_btn.setEnabled(False)
+ self.update_status.setText("Checking…")
+ url = self.feed.text().strip()
+
+ def done(info):
+ self.check_btn.setEnabled(True)
+ if info is None:
+ self.update_status.setText(f"You're up to date (checked {fmt.time_of_day(time.time())})")
+ return
+ self.update_status.setText(f"Version {info.version} is available")
+ self.ctx.window.set_update_available(info)
+ self.refresh()
+
+ def failed(exc):
+ self.check_btn.setEnabled(True)
+ self.update_status.setText(str(exc) if isinstance(exc, updater.UpdateError) else "Update check failed")
+
+ run_async(lambda: updater.check_for_update(url), done, failed)
+
+ def _install_update(self) -> None:
+ info = self.ctx.update_info
+ if not info:
+ return
+ if not info.download_url:
+ QDesktopServices.openUrl(QUrl(info.page_url or REPO_URL + "/releases"))
+ return
+ cancel = threading.Event()
+ dialog = QProgressDialog(f"Downloading {APP_NAME} {info.version}…", "Cancel", 0, 1000, self)
+ dialog.setWindowTitle("Updating")
+ dialog.setWindowModality(Qt.WindowModality.WindowModal)
+ dialog.setMinimumDuration(0)
+ dialog.canceled.connect(cancel.set)
+ relay = _ProgressRelay()
+ relay.progress.connect(lambda done_, total: dialog.setValue(int(1000 * done_ / total)) if total else None)
+
+ def finished(path):
+ dialog.close()
+ if (
+ QMessageBox.question(
+ self, "Install update", f"{APP_NAME} will close and the installer will start. Continue?"
+ )
+ == QMessageBox.StandardButton.Yes
+ ):
+ updater_apply.launch_installer(path)
+ self.ctx.window.quit()
+
+ def failed(exc):
+ dialog.close()
+ if not isinstance(exc, updater_apply.DownloadCancelled):
+ QMessageBox.warning(self, "Download failed", f"The update could not be downloaded.\n\n{exc}")
+
+ run_async(lambda: updater_apply.download(info.download_url, relay.progress.emit, cancel), finished, failed)
+ self._relay = relay
diff --git a/apptrackr/ui/views/village_view.py b/apptrackr/ui/views/village_view.py
index 79ec149..f124900 100644
--- a/apptrackr/ui/views/village_view.py
+++ b/apptrackr/ui/views/village_view.py
@@ -1,179 +1,314 @@
-"""Neon Village view – buildings, inventory, upgrades."""
+"""Village: inventory, market and buildings that boost future rewards."""
from __future__ import annotations
-from PySide6.QtCore import Qt
-from PySide6.QtGui import QColor
-from PySide6.QtWidgets import (
- QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
- QScrollArea, QFrame, QGridLayout, QGraphicsDropShadowEffect,
-)
+from PySide6.QtCore import QPointF, QRectF, Qt
+from PySide6.QtGui import QColor, QPainter, QPen
+from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QProgressBar, QVBoxLayout, QWidget
-from .. import theme
-from ..widgets.components import NeonCard, StatValue
+from ...game import economy
from ...game import state as game_state
-from ...rewards import engine as reward_engine
+from ...rewards import engine as rewards
+from .. import fmt, icons, motion, theme
+from ..signals import bus
+from ..widgets.components import (
+ PAGE_MARGIN,
+ Card,
+ MetricGrid,
+ Page,
+ PageHeader,
+ StatTile,
+ animate_progress,
+ button,
+ clear_layout,
+ eyebrow,
+ icon_label,
+ label,
+ set_role,
+)
+
+BUILDING_ICONS = {
+ "workshop": "hammer",
+ "storage": "warehouse",
+ "house": "house",
+ "lab": "flask-conical",
+ "tavern": "beer",
+ "monument": "landmark",
+}
+RESOURCE_ICONS = {"wood": "tree-pine", "stone": "mountain", "metal": "cog", "food": "wheat", "blueprints": "scroll"}
-class BuildingCard(QFrame):
- """Card for a single village building."""
+class BlueprintTile(QWidget):
+ """Building glyph on a drafting grid, like a plan on blueprint paper.
- def __init__(self, name: str, spec: dict, current_level: int, parent=None):
+ The glyph takes the accent only when the building can be built right now.
+ """
+
+ def __init__(self, icon: str, state: str = "idle", size: int = 40, parent=None):
super().__init__(parent)
- self._name = name
- unlocked = current_level > 0
-
- border_color = theme.get_accent() if unlocked else theme.BORDER
- self.setStyleSheet(f"""
- QFrame {{
- background: {theme.BG_CARD};
- border: 1px solid {border_color};
- border-radius: 10px;
- padding: 12px;
- min-width: 180px;
- }}
- """)
- if unlocked:
- shadow = QGraphicsDropShadowEffect(self)
- shadow.setBlurRadius(16)
- shadow.setColor(QColor(theme.get_accent()))
- shadow.setOffset(0, 0)
- self.setGraphicsEffect(shadow)
-
- layout = QVBoxLayout(self)
- layout.setSpacing(6)
-
- # Building icon + name
- icons = {"workshop": "🔨", "storage": "📦", "house": "🏠", "lab": "🔬", "tavern": "🍺", "monument": "🏛️"}
- icon = icons.get(name, "🏗️")
- title = QLabel(f"{icon} {name.title()}")
- title.setStyleSheet(f"font-size: 16px; font-weight: 700; color: {theme.TEXT}; background: transparent;")
- layout.addWidget(title)
-
- # Level
- level_lbl = QLabel(f"Level {current_level} / {spec['max_level']}")
- level_lbl.setStyleSheet(f"color: {theme.get_accent()}; font-weight: 600; background: transparent;")
- layout.addWidget(level_lbl)
-
- # Description
- desc = QLabel(spec["desc"])
- desc.setWordWrap(True)
- desc.setStyleSheet(f"color: {theme.TEXT_DIM}; font-size: 11px; background: transparent;")
- layout.addWidget(desc)
-
- # Unlock level req
- req = QLabel(f"Unlock: Player Lvl {spec['unlock_level']}")
- req.setStyleSheet(f"color: {theme.TEXT_MUTED}; font-size: 10px; background: transparent;")
- layout.addWidget(req)
-
- # Build / upgrade button
- can, reason = game_state.can_build(name)
- self._build_btn = QPushButton("Build" if current_level == 0 else "Upgrade")
- self._build_btn.setObjectName("primary")
- self._build_btn.setEnabled(can)
- self._build_btn.setToolTip(reason if not can else "")
- self._build_btn.clicked.connect(self._do_build)
- layout.addWidget(self._build_btn)
-
- def _do_build(self):
- ok, msg = game_state.build_or_upgrade(self._name)
- if ok:
- # Refresh parent
- p = self.parent()
- while p and not isinstance(p, VillageView):
- p = p.parent()
- if p:
- p.refresh()
+ self._icon, self._state = icon, state # "locked", "idle" or "ready"
+ self.setFixedSize(size, size)
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
+ p.setPen(QPen(QColor(t.border_strong), 1))
+ p.setBrush(QColor(t.surface_alt))
+ p.drawRoundedRect(r, 4, 4)
+ p.setPen(QPen(QColor(t.border), 1))
+ step = self.width() / 5
+ for i in range(1, 5):
+ p.drawLine(QPointF(i * step, 2), QPointF(i * step, self.height() - 2))
+ p.drawLine(QPointF(2, i * step), QPointF(self.width() - 2, i * step))
+ color = {"locked": t.text_muted, "ready": t.accent_text}.get(self._state, t.text_dim)
+ pm = icons.pixmap(self._icon, color, 22)
+ p.drawPixmap(int((self.width() - 22) / 2), int((self.height() - 22) / 2), pm)
+
+
+class LevelPips(QWidget):
+ """Row of segments showing a building's level out of its maximum."""
+
+ def __init__(self, level: int, maximum: int, previous: int | None = None, parent=None):
+ super().__init__(parent)
+ self._target, self._max = level, maximum
+ self._level = float(level if previous is None else previous)
+ self.setFixedHeight(6)
+ self.setMinimumWidth(40)
+ self.setToolTip(f"Level {level} of {maximum}")
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ if self._level != self._target:
+ motion.tween(
+ self, self._level, float(self._target), motion.SLOWER, self._set_level, motion.DECELERATE, key="pips"
+ )
+
+ def _set_level(self, value: float) -> None:
+ self._level = value
+ self.update()
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ p.setPen(Qt.PenStyle.NoPen)
+ gap = 4
+ w = (self.width() - gap * (self._max - 1)) / self._max
+ for i in range(self._max):
+ x = i * (w + gap)
+ p.setBrush(QColor(t.track))
+ p.drawRoundedRect(QRectF(x, 0, w, self.height()), 3, 3)
+ fill = min(1.0, max(0.0, self._level - i)) # partially filled while animating
+ if fill > 0:
+ p.setBrush(QColor(t.text_dim))
+ p.drawRoundedRect(QRectF(x, 0, w * fill, self.height()), 3, 3)
-class VillageView(QWidget):
- """Neon Village – build, upgrade, manage your village."""
- def __init__(self, parent=None):
+class VillageView(Page):
+ def __init__(self, ctx, parent=None):
super().__init__(parent)
- self._build_ui()
- self.refresh()
-
- def _build_ui(self):
- layout = QVBoxLayout(self)
- layout.setContentsMargins(24, 24, 24, 24)
- layout.setSpacing(16)
-
- header = QLabel("🏙️ Neon Village")
- header.setObjectName("heading")
- layout.addWidget(header)
-
- # Player info
- info_row = QHBoxLayout()
- self._level_stat = StatValue("1", "Village Level", theme.PURPLE)
- self._villagers_stat = StatValue("0", "Villagers", theme.BLUE)
- self._xp_stat = StatValue("0", "XP", theme.get_accent())
-
- for w in (self._level_stat, self._villagers_stat, self._xp_stat):
- card = NeonCard(glow_color=theme.BG_CARD)
- card.content_layout().addWidget(w)
- info_row.addWidget(card)
- layout.addLayout(info_row)
-
- # Inventory
- inv_card = NeonCard(glow_color=theme.BG_CARD, title="INVENTORY")
- self._inv_layout = QHBoxLayout()
- inv_card.content_layout().addLayout(self._inv_layout)
- layout.addWidget(inv_card)
-
- # Buildings grid
- buildings_label = QLabel("Buildings")
- buildings_label.setStyleSheet(f"font-size: 16px; font-weight: 700; color: {theme.TEXT}; background: transparent;")
- layout.addWidget(buildings_label)
-
- scroll = QScrollArea()
- scroll.setWidgetResizable(True)
- scroll.setStyleSheet("QScrollArea { border: none; background: transparent; }")
- self._buildings_container = QWidget()
- self._buildings_container.setStyleSheet("background: transparent;")
- self._buildings_grid = QGridLayout(self._buildings_container)
- self._buildings_grid.setSpacing(12)
- scroll.setWidget(self._buildings_container)
- layout.addWidget(scroll, stretch=1)
-
- def refresh(self):
+ self.setObjectName("page")
+ self.ctx = ctx
+
+ self.header = PageHeader(
+ "Village", "Spend resources from rewards on buildings that boost future rewards.", kicker="Progress"
+ )
+ self.add(self.header)
+
+ self.t_level = StatTile("Player level", framed=False)
+ self.t_villagers = StatTile("Villagers", framed=False)
+ self.t_credits = StatTile("Credits", framed=False)
+ self.t_bonus = StatTile("Active bonuses", framed=False)
+ self.add(MetricGrid([self.t_level, self.t_villagers, self.t_credits, self.t_bonus], columns=4))
+
+ row = QHBoxLayout()
+ row.setSpacing(16)
+ self.inventory = Card("Inventory", index=1)
+ self.inv_grid = QGridLayout()
+ self.inv_grid.setHorizontalSpacing(12)
+ self.inv_grid.setVerticalSpacing(10)
+ self.inventory.body.addLayout(self.inv_grid)
+ self.inventory.body.addStretch(1)
+ row.addWidget(self.inventory, 3)
+
+ self.market = Card("Market", "Trade credits for resources", index=2)
+ self.market_grid = QGridLayout()
+ self.market_grid.setSpacing(8)
+ self.market.body.addLayout(self.market_grid)
+ row.addWidget(self.market, 2)
+ self.add(row)
+
+ self.add(eyebrow("Buildings", 3))
+ self.buildings = QGridLayout()
+ self.buildings.setSpacing(16)
+ self.add(self.buildings)
+ self.layout_.addStretch(1)
+
+ self._amounts: dict[str, int] = {}
+ self._levels: dict[str, int] = {}
+ self._cards: dict[str, Card] = {}
+ self._columns = 0
+ self._just_built: str | None = None
+ bus.rewards_changed.connect(lambda: self.isVisible() and self.refresh())
+
+ def refresh(self) -> None:
village = game_state.get_village()
- profile = reward_engine.get_profile()
-
- # Stats
- self._level_stat.set_value(str(profile.get("level", 1)))
- self._villagers_stat.set_value(str(village.get("villagers", 0)))
- self._xp_stat.set_value(str(profile.get("xp", 0)))
-
- # Inventory
- while self._inv_layout.count():
- item = self._inv_layout.takeAt(0)
- if item.widget():
- item.widget().deleteLater()
-
- inv = village.get("inventory", {})
- icons = {"wood": "🪵", "stone": "🪨", "metal": "⚙️", "food": "🍖", "blueprints": "📜"}
- for res, icon in icons.items():
- val = inv.get(res, 0)
- item = QLabel(f"{icon} {res.title()}: {val}")
- item.setStyleSheet(f"color: {theme.TEXT}; font-weight: 600; padding: 4px 12px; background: transparent;")
- self._inv_layout.addWidget(item)
- self._inv_layout.addStretch()
-
- # Buildings
- while self._buildings_grid.count():
- item = self._buildings_grid.takeAt(0)
- if item.widget():
- item.widget().deleteLater()
-
- buildings = village.get("buildings", {})
- col = 0
- row = 0
- for name, spec in game_state.BUILDINGS.items():
- current_level = buildings.get(name, {}).get("level", 0)
- card = BuildingCard(name, spec, current_level)
- self._buildings_grid.addWidget(card, row, col)
- col += 1
- if col >= 3:
- col = 0
- row += 1
+ profile = rewards.get_profile()
+ bonuses = game_state.get_bonuses()
+ cap = bonuses["resource_cap"]
+
+ into, need = economy.level_progress(profile["xp"])
+ self.t_level.set_number(profile["level"], _count, f"{need - into} XP to next level")
+ self.t_villagers.set_number(village.get("villagers", 0), _count, "One per house level")
+ self.t_credits.set_number(profile["credits"], lambda v: fmt.count(int(round(v))), "Earned by leveling up")
+ active = [
+ f"+{bonuses['xp_bonus_pct']}% XP" if bonuses["xp_bonus_pct"] else "",
+ f"+{bonuses['resource_bonus_pct']}% resources" if bonuses["resource_bonus_pct"] else "",
+ f"+{bonuses['streak_bonus_pct']}% streak" if bonuses["streak_bonus_pct"] else "",
+ ]
+ active = [a for a in active if a]
+ self.t_bonus.set(str(len(active)), ", ".join(active) or "Build to unlock bonuses")
+
+ clear_layout(self.inv_grid)
+ inv = village["inventory"]
+ for i, res in enumerate(economy.RESOURCES):
+ r, c = i, 0
+ cell = QVBoxLayout()
+ cell.setContentsMargins(0, 0, 0, 0)
+ cell.setSpacing(4)
+ top = QHBoxLayout()
+ top.setSpacing(6)
+ top.addWidget(icon_label(RESOURCE_ICONS[res], "text_dim", 15))
+ top.addWidget(label(res.title()))
+ top.addStretch(1)
+ amount = inv.get(res, 0)
+ top.addWidget(label(f"{amount} / {cap}", "warning" if amount >= cap else "muted"))
+ cell.addLayout(top)
+ bar = QProgressBar()
+ bar.setTextVisible(False)
+ bar.setMaximum(cap)
+ animate_progress(bar, self._amounts.get(res, 0), min(cap, amount))
+ self._amounts[res] = min(cap, amount)
+ if amount >= cap:
+ bar.setProperty("tone", "gold")
+ cell.addWidget(bar)
+ host = QWidget()
+ host.setLayout(cell)
+ self.inv_grid.addWidget(host, r, c)
+
+ clear_layout(self.market_grid)
+ for i, (res, (amount, price)) in enumerate(economy.MARKET.items()):
+ self.market_grid.addWidget(icon_label(RESOURCE_ICONS[res], "text_dim", 15), i, 0)
+ self.market_grid.addWidget(label(f"{amount} {res}"), i, 1)
+ btn = button(f"{price} credits", on_click=lambda r=res: self._buy(r))
+ btn.setEnabled(profile["credits"] >= price and inv.get(res, 0) < cap)
+ if inv.get(res, 0) >= cap:
+ btn.setToolTip("Storage full")
+ self.market_grid.addWidget(btn, i, 2)
+ self.market_grid.setColumnStretch(1, 1)
+
+ clear_layout(self.buildings)
+ self._cards = {}
+ for name in game_state.BUILDINGS:
+ self._cards[name] = self._building_card(name, village, profile["level"])
+ self._columns = 0
+ 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])
+ self._just_built = None
+
+ def resizeEvent(self, event):
+ super().resizeEvent(event)
+ self._place_buildings()
+
+ def _place_buildings(self) -> None:
+ """Lay building cards out in as many columns (up to 3) as fit the page."""
+ cards = list(self._cards.values())
+ if not cards:
+ return
+ spacing = self.buildings.horizontalSpacing()
+ widest = max(c.minimumSizeHint().width() for c in cards)
+ room = self.viewport().width() - 2 * PAGE_MARGIN
+ columns = max(1, min(3, (room + spacing) // (widest + spacing)))
+ if columns == self._columns:
+ return
+ self._columns = columns
+ for card in cards:
+ self.buildings.removeWidget(card)
+ for i, card in enumerate(cards):
+ self.buildings.addWidget(card, i // columns, i % columns)
+ for c in range(3):
+ self.buildings.setColumnStretch(c, 1 if c < columns else 0)
+
+ def _building_card(self, name: str, village: dict, player_level: int) -> Card:
+ spec = game_state.BUILDINGS[name]
+ level = game_state.building_level(village, name)
+ locked = player_level < spec["unlock_level"]
+ maxed = level >= spec["max_level"]
+ ok, reason = game_state.can_build(name)
+ card = Card(padding=16, spacing=8)
+
+ top = QHBoxLayout()
+ top.setSpacing(10)
+ top.addWidget(BlueprintTile(BUILDING_ICONS[name], "locked" if locked else ("ready" if ok else "idle")))
+ title = label(name.title(), "heading")
+ top.addWidget(title, 1)
+ pill = label(
+ "Locked" if locked else ("Max" if maxed else f"Lv {level}/{spec['max_level']}"),
+ "pill",
+ )
+ top.addWidget(pill)
+ card.body.addLayout(top)
+
+ card.body.addWidget(LevelPips(level, spec["max_level"], self._levels.get(name)))
+
+ card.body.addWidget(label(spec["desc"], "dim", wrap=True))
+
+ if locked:
+ status = f"Unlocks at player level {spec['unlock_level']}"
+ card.body.addWidget(label(status, "caption"))
+ elif not maxed:
+ cost = game_state.build_cost(name, level)
+ inv = village["inventory"]
+ parts = []
+ for res, need in cost.items():
+ color = "" if inv.get(res, 0) >= need else f" style='color:{theme.current().danger}'"
+ parts.append(f"{need} {res}")
+ card.body.addWidget(label("Cost: " + ", ".join(parts), "caption", wrap=True))
+ card.body.addStretch(1)
+
+ btn = button(
+ "Build" if level == 0 else ("Upgrade" if not maxed else "Fully upgraded"),
+ icon="hammer" if ok else None,
+ on_click=lambda: self._build(name),
+ )
+ btn.setEnabled(ok)
+ if not ok and not maxed:
+ btn.setToolTip(reason)
+ card.body.addWidget(btn)
+ if locked:
+ set_role(title, "muted")
+ return card
+
+ def _build(self, name: str) -> None:
+ ok, msg = game_state.build_or_upgrade(name)
+ self.ctx.toast(msg, "success" if ok else "danger")
+ if ok:
+ self._just_built = name
+ bus.rewards_changed.emit() # refreshes this page while it is visible
+ if not self.isVisible():
+ self.refresh()
+
+ def _buy(self, resource: str) -> None:
+ ok, msg = game_state.buy(resource)
+ self.ctx.toast(msg, "success" if ok else "danger")
+ bus.rewards_changed.emit()
+ if not self.isVisible():
+ self.refresh()
+
+
+def _count(n: float) -> str:
+ return str(int(round(n)))
diff --git a/apptrackr/ui/widgets/charts.py b/apptrackr/ui/widgets/charts.py
new file mode 100644
index 0000000..cdf77ca
--- /dev/null
+++ b/apptrackr/ui/widgets/charts.py
@@ -0,0 +1,695 @@
+"""Custom-painted charts: bar chart, month heatmap and stacked share bar."""
+
+from __future__ import annotations
+
+import calendar
+import math
+from dataclasses import dataclass
+from datetime import date, timedelta
+
+from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal
+from PySide6.QtGui import QColor, QFont, QPainter, QPainterPath, QPen
+from PySide6.QtWidgets import QSizePolicy, QToolTip, QWidget
+
+from .. import fmt, fonts, motion, theme
+
+
+def _font(widget: QWidget, px: int, bold: bool = False) -> QFont:
+ f = QFont(widget.font())
+ f.setPixelSize(px)
+ f.setBold(bold)
+ return f
+
+
+def _nice_step(max_ms: float) -> int:
+ """Gridline spacing in ms giving 2-4 lines."""
+ minute, hour = 60_000, 3_600_000
+ for step in (
+ 5 * minute,
+ 10 * minute,
+ 15 * minute,
+ 30 * minute,
+ hour,
+ 2 * hour,
+ 3 * hour,
+ 4 * hour,
+ 6 * hour,
+ 12 * hour,
+ ):
+ if max_ms / step <= 4:
+ return step
+ return 24 * hour
+
+
+def _column(x: float, baseline: float, width: float, height: float, radius: float = 3.0) -> QPainterPath:
+ """Bar with rounded data-end and a square baseline."""
+ r = min(radius, width / 2, height)
+ top = baseline - height
+ path = QPainterPath()
+ path.moveTo(x, baseline)
+ path.lineTo(x, top + r)
+ path.quadTo(x, top, x + r, top)
+ path.lineTo(x + width - r, top)
+ path.quadTo(x + width, top, x + width, top + r)
+ path.lineTo(x + width, baseline)
+ path.closeSubpath()
+ return path
+
+
+@dataclass
+class Bar:
+ label: str # axis label ('' to hide)
+ value: float
+ tooltip: str = ""
+
+
+class BarChart(QWidget):
+ """Vertical bars with gridlines, hover tooltips and an optional limit line."""
+
+ bar_clicked = Signal(int)
+
+ def __init__(self, height: int = 170, parent=None):
+ super().__init__(parent)
+ self._bars: list[Bar] = []
+ self._highlight: int | None = None
+ self._hover: int | None = None
+ 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.
+ self._from: list[float] = []
+ self._to: list[float] = []
+ self._progress = 1.0
+ self._growing = False
+ self._pending = False
+ self.setMinimumHeight(height)
+ self.setMouseTracking(True)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+
+ def sizeHint(self) -> QSize:
+ return QSize(400, self.minimumHeight())
+
+ # Motion ------------------------------------------------------------------
+
+ def _stagger(self) -> float:
+ return min(18.0, 320.0 / max(1, len(self._to)))
+
+ def _total_ms(self) -> int:
+ return int(motion.SLOWER + self._stagger() * max(0, len(self._to) - 1))
+
+ def _shown(self, i: int) -> float:
+ if self._progress >= 1.0 or i >= len(self._from):
+ return self._to[i] if i < len(self._to) else 0.0
+ local = (self._progress * self._total_ms() - i * self._stagger()) / motion.SLOWER
+ local = min(1.0, max(0.0, local))
+ curve = motion.DECELERATE if self._growing else motion.EASY_EASE
+ return motion.lerp(self._from[i], self._to[i], curve.valueForProgress(local))
+
+ def _set_progress(self, value: float) -> None:
+ self._progress = value
+ self.update()
+
+ def _start(self) -> None:
+ self._progress = 0.0
+ motion.tween(self, 0.0, 1.0, self._total_ms(), self._set_progress, motion.LINEAR, key="bars")
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ if self._pending:
+ self._pending = False
+ self._start()
+
+ def set_data(
+ self,
+ bars: list[Bar],
+ highlight: int | None = None,
+ limit: float | None = None,
+ empty_text: str = "No activity yet",
+ ) -> None:
+ target = [float(b.value) for b in bars]
+ current = [self._shown(i) for i in range(len(self._to))]
+ self._growing = len(current) != len(target) or not any(current)
+ self._from = [0.0] * len(target) if self._growing else current
+ self._to = target
+ self._bars = bars
+ self._highlight = highlight
+ self._limit = limit
+ self._empty_text = empty_text
+ if all(abs(a - b) < 1 for a, b in zip(self._from, self._to, strict=True)):
+ self._progress = 1.0
+ elif self.isVisible():
+ self._start()
+ else:
+ self._progress = 0.0
+ self._pending = True
+ self.update()
+
+ def _geometry(self):
+ left, right, top, bottom = 46, 4, 18, 30
+ plot = QRectF(left, top, max(10, self.width() - left - right), max(10, self.height() - top - bottom))
+ n = max(1, len(self._bars))
+ slot = plot.width() / n
+ bar_w = max(2.0, min(20.0, slot * 0.56))
+ return plot, slot, bar_w
+
+ def _index_at(self, x: float) -> int | None:
+ if not self._bars:
+ return None
+ plot, slot, _ = self._geometry()
+ if x < plot.left() or x > plot.right():
+ return None
+ return min(len(self._bars) - 1, int((x - plot.left()) // slot))
+
+ def mouseMoveEvent(self, event):
+ idx = self._index_at(event.position().x())
+ if idx != self._hover:
+ self._hover = idx
+ self.update()
+ if idx is not None and self._bars[idx].tooltip:
+ QToolTip.showText(event.globalPosition().toPoint(), self._bars[idx].tooltip, self)
+ else:
+ QToolTip.hideText()
+
+ def leaveEvent(self, _event):
+ self._hover = None
+ self.update()
+
+ def mouseReleaseEvent(self, event):
+ idx = self._index_at(event.position().x())
+ if idx is not None:
+ self.bar_clicked.emit(idx)
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ plot, slot, bar_w = self._geometry()
+ peak = max([b.value for b in self._bars] + [self._limit or 0, 1])
+
+ if not any(b.value for b in self._bars):
+ p.setPen(QColor(t.text_muted))
+ p.setFont(fonts.sans(12))
+ p.drawText(plot, Qt.AlignmentFlag.AlignCenter, self._empty_text)
+
+ # Gridlines: solid hairlines, labels engraved in mono.
+ step = _nice_step(peak)
+ top_value = max(step, ((peak + step - 1) // step) * step)
+ p.setFont(fonts.mono(9, 400, 4))
+ v = 0
+ while v <= top_value:
+ y = round(plot.bottom() - plot.height() * v / top_value) + 0.5
+ p.setPen(QPen(QColor(t.border_strong if v == 0 else t.border), 1))
+ p.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y))
+ p.setPen(QColor(t.text_muted))
+ p.drawText(
+ QRectF(0, y - 8, plot.left() - 10, 16),
+ Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
+ fmt.axis(v),
+ )
+ v += step
+
+ # Tick ruler under the baseline: a minor tick per slot, a major tick per label.
+ base = round(plot.bottom()) + 0.5
+ for i, bar in enumerate(self._bars):
+ cx = plot.left() + slot * i + slot / 2
+ major = bool(bar.label)
+ 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)))
+
+ ink = QColor(t.ink)
+ for i, bar in enumerate(self._bars):
+ x = plot.left() + slot * i + (slot - bar_w) / 2
+ h = plot.height() * self._shown(i) / top_value
+ highlighted = i == self._highlight
+ 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)
+ if h > 0.5:
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(color)
+ p.drawPath(_column(x, plot.bottom(), bar_w, max(h, 2.0)))
+ if highlighted and bar.value > 0 and h > 0.5:
+ p.setPen(QColor(t.text))
+ p.setFont(fonts.sans(11, 600, tabular=True))
+ p.drawText(
+ QRectF(x - 30, plot.bottom() - h - 17, bar_w + 60, 14),
+ Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignBottom,
+ fmt.duration(bar.value, short=True),
+ )
+ if bar.label:
+ p.setPen(QColor(t.text if highlighted else t.text_muted))
+ p.setFont(fonts.mono(9, 500 if highlighted else 400, 4))
+ p.drawText(QRectF(x - 20, base + 9, bar_w + 40, 14), Qt.AlignmentFlag.AlignHCenter, bar.label)
+
+ if self._limit:
+ y = round(plot.bottom() - plot.height() * self._limit / top_value) + 0.5
+ p.setPen(QPen(QColor(t.danger), 1))
+ p.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y))
+ p.setFont(fonts.mono(9, 500, 6))
+ p.drawText(
+ QRectF(plot.left(), y - 15, plot.width() - 2, 13),
+ Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignBottom,
+ f"LIMIT {fmt.duration(self._limit, short=True).upper()}",
+ )
+ p.end()
+
+
+class MonthHeatmap(QWidget):
+ """Calendar month with cells shaded by focused time. Keyboard and mouse navigable."""
+
+ day_selected = Signal(str)
+
+ COLS = 7
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self._month = date.today().replace(day=1)
+ self._totals: dict[str, int] = {}
+ self._selected: date | None = date.today()
+ self._hover: date | None = None
+ 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)
+ self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
+ self.setMinimumSize(320, 260)
+ policy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
+ policy.setHeightForWidth(True)
+ self.setSizePolicy(policy)
+ self.setAccessibleName("Usage calendar")
+
+ WAVE_STEP = 9 # ms between consecutive days
+
+ def set_month(self, month: date, totals: dict[str, int]) -> None:
+ changed = month.replace(day=1) != self._month
+ self._month = month.replace(day=1)
+ self._totals = totals
+ if changed and self.isVisible():
+ days = calendar.monthrange(self._month.year, self._month.month)[1]
+ motion.tween(
+ self, 0.0, 1.0, motion.NORMAL + self.WAVE_STEP * days, self._set_wave, motion.LINEAR, key="wave"
+ )
+ self.update()
+
+ def _set_wave(self, value: float) -> None:
+ self._wave = value
+ self.update()
+
+ def _cell_wave(self, day: int) -> float:
+ """Entrance progress (0..1) for one cell during the month-change wave."""
+ if self._wave >= 1.0:
+ return 1.0
+ days = calendar.monthrange(self._month.year, self._month.month)[1]
+ elapsed = self._wave * (motion.NORMAL + self.WAVE_STEP * days) - (day - 1) * self.WAVE_STEP
+ return motion.DECELERATE.valueForProgress(min(1.0, max(0.0, elapsed / motion.NORMAL)))
+
+ def set_selected(self, day: date | None) -> None:
+ self._glide_to(day)
+
+ def _glide_to(self, day: date | None) -> None:
+ old = self._selected
+ self._selected = day
+ same_month = day and old and day.replace(day=1) == old.replace(day=1) == self._month
+ if same_month and day != old and self.isVisible():
+ start, end = self._ring or self._cell_rect(old), self._cell_rect(day)
+ motion.tween(
+ self, start, end, motion.NORMAL, self._set_ring, motion.EASY_EASE, on_done=self._end_ring, key="ring"
+ )
+ else:
+ self._ring = None
+ self.update()
+
+ def _set_ring(self, rect: QRectF) -> None:
+ self._ring = QRectF(rect)
+ self.update()
+
+ def _end_ring(self) -> None:
+ self._ring = None
+ self.update()
+
+ def _weeks(self) -> int:
+ first_col = self._month.weekday()
+ days = calendar.monthrange(self._month.year, self._month.month)[1]
+ return (first_col + days + 6) // 7
+
+ def _layout(self):
+ header = 24
+ gap = 6
+ weeks = self._weeks()
+ cell_w = (self.width() - gap * (self.COLS - 1)) / self.COLS
+ cell_h = min(cell_w * 0.82, (self.height() - header - gap * (weeks - 1)) / weeks)
+ return header, gap, cell_w, max(24.0, cell_h)
+
+ def _cell_rect(self, d: date) -> QRectF:
+ header, gap, cw, ch = self._layout()
+ index = self._month.weekday() + d.day - 1
+ row, col = divmod(index, self.COLS)
+ return QRectF(col * (cw + gap), header + row * (ch + gap), cw, ch)
+
+ def _day_at(self, pos: QPointF) -> date | None:
+ days = calendar.monthrange(self._month.year, self._month.month)[1]
+ for n in range(1, days + 1):
+ d = self._month.replace(day=n)
+ if self._cell_rect(d).contains(pos):
+ return d
+ return None
+
+ def hasHeightForWidth(self) -> bool:
+ return True
+
+ def heightForWidth(self, width: int) -> int:
+ cell_w = (width - 6 * (self.COLS - 1)) / self.COLS
+ return int(24 + self._weeks() * (cell_w * 0.82 + 6))
+
+ def sizeHint(self) -> QSize:
+ return QSize(460, self.heightForWidth(460))
+
+ def mouseMoveEvent(self, event):
+ d = self._day_at(event.position())
+ if d != self._hover:
+ self._hover = d
+ self.update()
+ if d:
+ ms = self._totals.get(d.isoformat(), 0)
+ tip = f"{fmt.long_date(d)}\n{fmt.duration(ms) if ms else 'No activity'}"
+ QToolTip.showText(event.globalPosition().toPoint(), tip, self)
+
+ def leaveEvent(self, _event):
+ self._hover = None
+ self.update()
+
+ def mouseReleaseEvent(self, event):
+ d = self._day_at(event.position())
+ if d and d <= date.today():
+ self._glide_to(d)
+ self.day_selected.emit(d.isoformat())
+
+ def keyPressEvent(self, event):
+ steps = {Qt.Key.Key_Left: -1, Qt.Key.Key_Right: 1, Qt.Key.Key_Up: -7, Qt.Key.Key_Down: 7}
+ if event.key() in steps:
+ base = self._selected or date.today()
+ new = base + timedelta(days=steps[event.key()])
+ if new <= date.today():
+ if new.replace(day=1) == self._month:
+ self._glide_to(new)
+ else:
+ self._selected = new
+ self.day_selected.emit(new.isoformat())
+ return
+ super().keyPressEvent(event)
+
+ @staticmethod
+ def level(ms: int, peak: int) -> int:
+ """Quantize a day into 0 (empty) or 1..4 so steps read like LED segments."""
+ if ms <= 0:
+ return 0
+ return min(4, 1 + int(4 * ms / max(peak, 1) - 1e-9))
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ header, gap, cw, ch = self._layout()
+
+ p.setFont(fonts.mono(9, 500, 8))
+ p.setPen(QColor(t.text_muted))
+ for i, name in enumerate(("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")):
+ p.drawText(
+ QRectF(i * (cw + gap) + 2, 0, cw, header - 8),
+ Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
+ name,
+ )
+
+ values = [v for k, v in self._totals.items() if k.startswith(self._month.strftime("%Y-%m"))]
+ peak = max(values) if values else 1
+ today = date.today()
+ days = calendar.monthrange(self._month.year, self._month.month)[1]
+ big = ch >= 46 and cw >= 54
+ radius = 3.0
+
+ for n in range(1, days + 1):
+ d = self._month.replace(day=n)
+ r = self._cell_rect(d)
+ enter = self._cell_wave(n)
+ if enter <= 0.0:
+ continue
+ p.setOpacity(enter)
+ if enter < 1.0:
+ shrink = (1 - enter) * 0.08
+ r = r.adjusted(r.width() * shrink, r.height() * shrink, -r.width() * shrink, -r.height() * shrink)
+ ms = self._totals.get(d.isoformat(), 0)
+ future = d > today
+ level = self.level(ms, peak)
+ p.setPen(Qt.PenStyle.NoPen)
+ if future:
+ p.setPen(QPen(QColor(t.border), 1))
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.drawRoundedRect(r.adjusted(0.5, 0.5, -0.5, -0.5), radius, radius)
+ else:
+ 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))
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.drawRoundedRect(r.adjusted(0.5, 0.5, -0.5, -0.5), radius, radius)
+ if d == today:
+ # Today: a notch in the corner, like an index mark on a dial.
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(t.text))
+ notch = QPainterPath()
+ notch.moveTo(r.right() - 9, r.top())
+ notch.lineTo(r.right() - radius, r.top())
+ notch.quadTo(r.right(), r.top(), r.right(), r.top() + radius)
+ notch.lineTo(r.right(), r.top() + 9)
+ notch.closeSubpath()
+ p.drawPath(notch)
+
+ strong = level >= 3
+ if d == today and ms:
+ text_color = QColor(t.on_accent if level >= 3 else t.text)
+ elif strong:
+ text_color = QColor(t.window)
+ else:
+ text_color = QColor(t.text_muted if future or not ms else t.text)
+ p.setPen(text_color)
+ p.setFont(fonts.mono(10 if big else 9, 500 if d == today else 400, 0))
+ if big:
+ p.drawText(r.adjusted(7, 5, -6, -5), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop, f"{n:02d}")
+ if ms:
+ p.setFont(fonts.sans(11, 600, tabular=True))
+ p.drawText(
+ r.adjusted(7, 5, -6, -5),
+ Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignBottom,
+ fmt.duration(ms, short=True),
+ )
+ else:
+ p.drawText(r, Qt.AlignmentFlag.AlignCenter, str(n))
+ p.setOpacity(1.0)
+
+ ring = self._ring
+ if ring is None and self._selected and self._selected.replace(day=1) == self._month:
+ ring = self._cell_rect(self._selected)
+ if ring is not None:
+ p.setPen(QPen(QColor(t.text if self.hasFocus() else t.accent), 2))
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.drawRoundedRect(ring.adjusted(-2, -2, 2, 2), radius + 2, radius + 2)
+ p.end()
+
+
+class ShareBar(QWidget):
+ """Single stacked bar showing each segment's share of the total."""
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self._segments: list[tuple[str, float, str]] = []
+ self._from: dict[str, float] = {}
+ self._to: dict[str, float] = {}
+ self._t = 1.0
+ self._pending = False
+ self.setFixedHeight(8)
+ self.setMouseTracking(True)
+
+ def set_segments(self, segments: list[tuple[str, float, str]]) -> None:
+ self._from = {name: self._share(name) for name in self._to}
+ self._segments = [s for s in segments if s[1] > 0]
+ total = sum(v for _, v, _ in self._segments) or 1
+ self._to = {name: v / total for name, v, _ in self._segments}
+ if self._from == self._to:
+ return
+ if self.isVisible():
+ self._start()
+ else:
+ self._t, self._pending = 0.0, True
+ self.update()
+
+ def _share(self, name: str) -> float:
+ return motion.lerp(self._from.get(name, 0.0), self._to.get(name, 0.0), self._t)
+
+ def _start(self) -> None:
+ motion.tween(self, 0.0, 1.0, motion.SLOWER, self._set_t, motion.EASY_EASE, key="share")
+
+ def _set_t(self, value: float) -> None:
+ self._t = value
+ self.update()
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ if self._pending:
+ self._pending = False
+ self._start()
+
+ def _segment_at(self, x: float):
+ total = sum(v for _, v, _ in self._segments) or 1
+ pos = 0.0
+ for seg in self._segments:
+ w = self.width() * seg[1] / total
+ if pos <= x < pos + w:
+ return seg, seg[1] / total
+ pos += w
+ return None, 0
+
+ def mouseMoveEvent(self, event):
+ seg, share = self._segment_at(event.position().x())
+ if seg:
+ QToolTip.showText(event.globalPosition().toPoint(), f"{seg[0]}: {fmt.duration(seg[1])} ({share:.0%})", self)
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ h = self.height()
+ p.setPen(Qt.PenStyle.NoPen)
+ if not self._segments:
+ p.setBrush(QColor(t.track))
+ p.drawRoundedRect(QRectF(0, 0, self.width(), h), 2, 2)
+ return
+ names = [n for n, _, _ in self._segments] + [n for n in self._from if n not in self._to]
+ colors = {n: c for n, _, c in self._segments}
+ shares = [(n, self._share(n)) for n in names]
+ shares = [(n, v) for n, v in shares if v > 0.002]
+ total = sum(v for _, v in shares) or 1.0
+ gap = 2.0 # surface gap between segments
+ filled = self.width() * min(1.0, total)
+ usable = max(1.0, filled - gap * max(0, len(shares) - 1))
+ x = 0.0
+ for name, share in shares:
+ w = usable * share / total
+ p.setBrush(QColor(colors.get(name, t.text_muted)))
+ p.drawRoundedRect(QRectF(x, 0, max(1.0, w), h), 2, 2)
+ x += w + gap
+ if x < self.width() - gap:
+ p.setBrush(QColor(t.track))
+ p.drawRoundedRect(QRectF(x, 0, self.width() - x, h), 2, 2)
+ p.end()
+
+
+class HeatLegend(QWidget):
+ """ "LESS ■■■■■ MORE" key for the calendar's quantized steps."""
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.setFixedHeight(14)
+ self.setMinimumWidth(220)
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ p.setFont(fonts.mono(9, 500, 8))
+ p.setPen(QColor(t.text_muted))
+ x = 0.0
+ p.drawText(QRectF(x, 0, 40, 14), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, "LESS")
+ x = 38.0
+ p.setPen(Qt.PenStyle.NoPen)
+ for level in range(5):
+ p.setBrush(QColor(t.heat(level)))
+ p.drawRoundedRect(QRectF(x, 2, 10, 10), 2, 2)
+ x += 14
+ p.setPen(QColor(t.text_muted))
+ p.drawText(QRectF(x + 4, 0, 40, 14), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, "MORE")
+ x += 54
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(t.accent))
+ p.drawRoundedRect(QRectF(x, 2, 10, 10), 2, 2)
+ p.setPen(QColor(t.text_muted))
+ p.drawText(QRectF(x + 16, 0, 50, 14), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, "TODAY")
+
+
+class SessionDial(QWidget):
+ """Chronograph for the live session: 60 engraved ticks, a minute arc and a seconds hand."""
+
+ def __init__(self, size: int = 156, parent=None):
+ super().__init__(parent)
+ self.setFixedSize(size, size)
+ self._active = False
+ self._ms = 0
+ self._caption = ""
+ self._hand = 0.0 # degrees, eased between seconds
+ self._last_second = -1
+ self.setAccessibleName("Session timer")
+
+ def set_state(self, active: bool, session_ms: int, caption: str) -> None:
+ self._active, self._ms, self._caption = active, session_ms, caption
+ second = (session_ms // 1000) % 60
+ if active and second != self._last_second:
+ target = second * 6.0
+ start = self._hand if target >= self._hand else self._hand - 360
+ motion.tween(self, start, target, motion.FAST, self._set_hand, motion.EASY_EASE, key="hand")
+ self._last_second = second
+ elif not active:
+ self._last_second = -1
+ self.setToolTip(fmt.clock(session_ms) if active else caption)
+ self.update()
+
+ def _set_hand(self, value: float) -> None:
+ self._hand = value % 360
+ self.update()
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ c = QPointF(self.width() / 2, self.height() / 2)
+ outer = self.width() / 2 - 2
+
+ # Engraved minute ticks.
+ for i in range(60):
+ angle = math.radians(i * 6 - 90)
+ major = i % 5 == 0
+ r1 = outer - (8 if major else 4)
+ color = QColor(t.text_muted if major else t.border_strong)
+ if not self._active:
+ color.setAlphaF(0.6)
+ p.setPen(QPen(color, 1.5 if major else 1, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
+ p.drawLine(
+ QPointF(c.x() + r1 * math.cos(angle), c.y() + r1 * math.sin(angle)),
+ QPointF(c.x() + outer * math.cos(angle), c.y() + outer * math.sin(angle)),
+ )
+
+ # Minute arc: progress through the current hour of the session.
+ ring = QRectF(c.x() - outer + 14, c.y() - outer + 14, 2 * (outer - 14), 2 * (outer - 14))
+ p.setPen(QPen(QColor(t.track), 3, Qt.PenStyle.SolidLine, Qt.PenCapStyle.FlatCap))
+ p.drawEllipse(ring)
+ if self._active:
+ minutes = (self._ms % 3_600_000) / 3_600_000
+ p.setPen(QPen(QColor(t.accent), 3, Qt.PenStyle.SolidLine, Qt.PenCapStyle.FlatCap))
+ p.drawArc(ring, 90 * 16, int(-minutes * 360 * 16))
+
+ # Seconds pointer: rides the outer scale so it never crosses the readout.
+ angle = math.radians(self._hand - 90)
+ inner, tip = outer - 20, outer + 1
+ p.setPen(QPen(QColor(t.accent), 2, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
+ p.drawLine(
+ QPointF(c.x() + inner * math.cos(angle), c.y() + inner * math.sin(angle)),
+ QPointF(c.x() + tip * math.cos(angle), c.y() + tip * math.sin(angle)),
+ )
+
+ # 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)
+ 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 852d606..0ccb26a 100644
--- a/apptrackr/ui/widgets/components.py
+++ b/apptrackr/ui/widgets/components.py
@@ -1,260 +1,1219 @@
-"""Reusable neon-themed widgets."""
+"""Shared widgets. Colors always come from the active theme."""
from __future__ import annotations
-from PySide6.QtCore import Qt, QPropertyAnimation, QEasingCurve, Property, Signal
-from PySide6.QtGui import QPainter, QColor, QLinearGradient, QPen, QFont, QPixmap
+from functools import lru_cache
+from typing import Callable
+
+from PySide6.QtCore import (
+ Property,
+ QEvent,
+ QFileInfo,
+ QPoint,
+ QRect,
+ QRectF,
+ QSize,
+ Qt,
+ QTimer,
+ Signal,
+)
+from PySide6.QtGui import QColor, QFont, QPainter, QPen, QPixmap
from PySide6.QtWidgets import (
- QFrame, QLabel, QVBoxLayout, QHBoxLayout, QWidget, QGraphicsDropShadowEffect,
- QSizePolicy, QPushButton, QFileIconProvider,
+ QAbstractButton,
+ QBoxLayout,
+ QButtonGroup,
+ QFileIconProvider,
+ QFrame,
+ QGraphicsOpacityEffect,
+ QGridLayout,
+ QHBoxLayout,
+ QLabel,
+ QLayout,
+ QLayoutItem,
+ QPushButton,
+ QScrollArea,
+ QSizePolicy,
+ QVBoxLayout,
+ QWidget,
)
-from PySide6.QtCore import QFileInfo
-from .. import theme
+from .. import fonts, icons, motion, theme
+from ..signals import bus
+
+PAGE_MARGIN = 28
+MAX_CONTENT_WIDTH = 1280
+
+
+# ---------------------------------------------------------------------------
+# Small helpers
+# ---------------------------------------------------------------------------
+
+
+# Type scale. Roles listed here get their font in code (QSS cannot set letter
+# spacing or OpenType features); the stylesheet only colours them.
+ROLE_FONTS: dict[str, Callable[[], QFont]] = {
+ "title": lambda: fonts.sans(24, 600),
+ "subtitle": lambda: fonts.sans(13),
+ "heading": lambda: fonts.sans(15, 600),
+ "value": lambda: fonts.sans(28, 600, tabular=True),
+ "hero": lambda: fonts.sans(44, 600, tabular=True),
+ "caption": lambda: fonts.sans(12),
+ "eyebrow": lambda: fonts.mono(10, 500, 10),
+ "eyebrowAccent": lambda: fonts.mono(10, 500, 10),
+ "tick": lambda: fonts.mono(9, 400, 4),
+ "pill": lambda: fonts.mono(9, 500, 8),
+ "pillAccent": lambda: fonts.mono(9, 500, 8),
+ "pillDanger": lambda: fonts.mono(9, 500, 8),
+}
+UPPERCASE_ROLES = {"eyebrow", "eyebrowAccent", "pill", "pillAccent", "pillDanger"}
+
+
+def _apply_role_font(widget: QWidget, role: str | None) -> None:
+ maker = ROLE_FONTS.get(role or "")
+ widget.setFont(maker() if maker else fonts.sans(13))
+
+
+def set_role(widget: QWidget, role: str | None) -> QWidget:
+ widget.setProperty("role", role)
+ _apply_role_font(widget, role)
+ if isinstance(widget, QLabel) and role in UPPERCASE_ROLES:
+ widget.setText(widget.text().upper())
+ widget.style().unpolish(widget)
+ widget.style().polish(widget)
+ return widget
+
+
+class RoleLabel(QLabel):
+ """QLabel that upper-cases its text for engraved-label roles."""
+
+ def setText(self, text: str) -> None: # noqa: N802 - Qt naming
+ super().setText(text.upper() if self.property("role") in UPPERCASE_ROLES else text)
-class NeonCard(QFrame):
- """A glassy card with optional glow border."""
+class ElidedLabel(QLabel):
+ """Single-line label that elides in the middle to fit (paths); the full text is its tooltip."""
- def __init__(self, parent=None, glow_color: str = None, title: str = ""):
+ def __init__(self, text: str = "", role: str | None = None, parent=None):
super().__init__(parent)
- if glow_color is None:
- glow_color = theme.get_accent()
- self.setObjectName("neonCard")
- self._glow_color = glow_color
- self.setStyleSheet(f"""
- QFrame#neonCard {{
- background-color: {theme.BG_CARD};
- border: 1px solid {theme.BORDER};
- border-radius: 12px;
- }}
- QFrame#neonCard:hover {{
- border-color: {glow_color};
- }}
- """)
- self._layout = QVBoxLayout(self)
- self._layout.setContentsMargins(16, 16, 16, 16)
- self._layout.setSpacing(14)
-
- # Let cards expand/shrink naturally with the parent layout.
- self.setMinimumWidth(0)
- self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
+ self._full = ""
+ set_role(self, role)
+ self.setText(text)
+
+ def setText(self, text: str) -> None: # noqa: N802 - Qt naming
+ self._full = text
+ self.setToolTip(text)
+ self.updateGeometry()
+ self._elide()
+
+ def full_text(self) -> str:
+ return self._full
+
+ def sizeHint(self) -> QSize: # noqa: N802
+ return QSize(self.fontMetrics().horizontalAdvance(self._full), super().sizeHint().height())
+
+ def minimumSizeHint(self) -> QSize: # noqa: N802
+ return QSize(0, super().minimumSizeHint().height())
+
+ def resizeEvent(self, event):
+ super().resizeEvent(event)
+ self._elide()
+
+ def _elide(self) -> None:
+ super().setText(self.fontMetrics().elidedText(self._full, Qt.TextElideMode.ElideMiddle, self.width()))
+
+
+def label(text: str = "", role: str | None = None, wrap: bool = False, align: Qt.AlignmentFlag | None = None) -> QLabel:
+ lbl = RoleLabel()
+ if role:
+ lbl.setProperty("role", role)
+ if role in ROLE_FONTS:
+ _apply_role_font(lbl, role)
+ lbl.setText(text)
+ lbl.setWordWrap(wrap)
+ if align is not None:
+ lbl.setAlignment(align)
+ return lbl
+
+
+def eyebrow(text: str, index: int | None = None, accent: bool = False) -> QLabel:
+ """Small engraved section label, optionally numbered ("02 TODAY BY HOUR")."""
+ shown = f"{index:02d} {text}" if index is not None else text
+ return label(shown, "eyebrowAccent" if accent else "eyebrow")
+
+
+def button(
+ text: str = "",
+ kind: str | None = None,
+ icon: str | None = None,
+ tooltip: str = "",
+ on_click: Callable | None = None,
+) -> QPushButton:
+ btn = QPushButton(text)
+ if kind:
+ btn.setProperty("kind", kind)
+ btn.setCursor(Qt.CursorShape.PointingHandCursor)
+ btn.setFocusPolicy(Qt.FocusPolicy.TabFocus)
+ if tooltip:
+ btn.setToolTip(tooltip)
+ if on_click:
+ btn.clicked.connect(lambda *_: on_click())
+ if icon:
+ IconBinding.attach(
+ btn, icon, "text_on" if kind == "primary" else ("danger" if kind == "danger" else "text_dim")
+ )
+ return btn
+
+def count_to(lbl: QLabel, start: float, end: float, formatter: Callable[[float], str]) -> None:
+ """Animate a label's number from *start* to *end*."""
+ motion.tween(
+ lbl,
+ float(start),
+ float(end),
+ motion.SLOWER,
+ lambda v: lbl.setText(formatter(v)),
+ motion.DECELERATE,
+ key="count",
+ )
+
+
+def animate_progress(bar, start: float, end: float) -> None:
+ """Ease a QProgressBar between two values."""
+ motion.tween(
+ bar,
+ float(start),
+ float(end),
+ motion.SLOW,
+ lambda v: bar.setValue(int(round(v))),
+ motion.EASY_EASE,
+ key="progress",
+ )
+
+
+def divider() -> QFrame:
+ line = QFrame()
+ line.setProperty("divider", True)
+ return line
+
+
+def vdivider() -> QFrame:
+ line = QFrame()
+ line.setProperty("vdivider", True)
+ return line
+
+
+def clear_layout(layout: QLayout) -> None:
+ while layout.count():
+ item = layout.takeAt(0)
+ widget = item.widget()
+ if widget is not None:
+ widget.hide()
+ widget.deleteLater()
+ elif item.layout() is not None:
+ clear_layout(item.layout())
+
+
+def tone_color(tone: str) -> str:
+ t = theme.current()
+ return {
+ "accent": t.accent,
+ "text": t.text,
+ "text_dim": t.text_dim,
+ "text_muted": t.text_muted,
+ "text_on": t.on_accent,
+ "danger": t.danger,
+ "warning": t.warning,
+ "gold": t.gold,
+ "success": t.success,
+ "accent_text": t.accent_text,
+ "ink": t.ink,
+ }.get(tone, tone)
+
+
+class IconBinding:
+ """Keeps a button's or label's icon tinted for the current theme."""
+
+ @staticmethod
+ def attach(
+ widget: QWidget,
+ name: str,
+ tone: str = "text_dim",
+ size: int = 16,
+ checked_tone: str | None = None,
+ filled: bool = False,
+ ) -> None:
+ def apply():
+ if isinstance(widget, QLabel):
+ widget.setPixmap(icons.pixmap(name, tone_color(tone), size, filled))
+ else:
+ widget.setIcon(
+ icons.icon(name, tone_color(tone), size, tone_color(checked_tone) if checked_tone else None)
+ )
+ widget.setIconSize(QSize(size, size))
+
+ apply()
+ widget._icon_apply = apply # keep the closure alive with the widget
+ bus.theme_changed.connect(apply)
+ widget.destroyed.connect(lambda *_: _safe_disconnect(apply))
+
+
+def _safe_disconnect(slot) -> None:
+ try:
+ bus.theme_changed.disconnect(slot)
+ except (RuntimeError, TypeError, SystemError):
+ pass
+
+
+def icon_label(name: str, tone: str = "text_dim", size: int = 16, filled: bool = False) -> QLabel:
+ lbl = QLabel()
+ lbl.setFixedSize(size, size)
+ IconBinding.attach(lbl, name, tone, size, filled=filled)
+ return lbl
+
+
+# ---------------------------------------------------------------------------
+# Layout containers
+# ---------------------------------------------------------------------------
+
+
+class Card(QFrame):
+ """Panel: hairline-bordered surface with an engraved header (index, title, caption, actions)."""
+
+ def __init__(
+ self,
+ title: str = "",
+ caption: str = "",
+ parent=None,
+ padding: int = 18,
+ spacing: int = 12,
+ index: int | None = None,
+ ):
+ super().__init__(parent)
+ self.setProperty("card", True)
+ self.body = QVBoxLayout(self)
+ self.body.setContentsMargins(padding, padding - 2, padding, padding)
+ self.body.setSpacing(spacing)
+ self.header_actions = QHBoxLayout()
+ self.header_actions.setSpacing(6)
+ self.title_label: QLabel | None = None
+ self.caption_label: QLabel | None = None
+ self._index = index
if title:
- lbl = QLabel(title)
- lbl.setStyleSheet(f"font-size: 13px; font-weight: 700; color: {theme.TEXT_DIM}; background: transparent;")
- lbl.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
- self._layout.addWidget(lbl)
+ self.title_label = eyebrow(title, index)
+ head = QVBoxLayout()
+ head.setSpacing(3)
+ head.addWidget(self.title_label)
+ if caption:
+ self.caption_label = label(caption, "caption", wrap=True)
+ head.addWidget(self.caption_label)
+ row = QHBoxLayout()
+ row.setSpacing(8)
+ row.addLayout(head, 1)
+ row.addLayout(self.header_actions)
+ self.body.addLayout(row)
+
+ def set_title(self, text: str) -> None:
+ if self.title_label is not None:
+ self.title_label.setText(f"{self._index:02d} {text}" if self._index is not None else text)
+
+ def set_caption(self, text: str) -> None:
+ if self.caption_label is not None:
+ self.caption_label.setText(text)
+
- # Subtle glow effect
- shadow = QGraphicsDropShadowEffect(self)
- shadow.setBlurRadius(24)
- shadow.setColor(QColor(glow_color))
- shadow.setOffset(0, 0)
- self.setGraphicsEffect(shadow)
+class _Paper(QWidget):
+ """Page canvas: window colour with a faint graph-paper dot grid."""
- def content_layout(self) -> QVBoxLayout:
- return self._layout
+ STEP = 24
+
+ def paintEvent(self, event):
+ t = theme.current()
+ p = QPainter(self)
+ p.fillRect(event.rect(), QColor(t.window))
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(t.grid))
+ r = event.rect()
+ step = self.STEP
+ x0 = (r.left() // step) * step + step // 2
+ y0 = (r.top() // step) * step + step // 2
+ for y in range(y0, r.bottom() + step, step):
+ for x in range(x0, r.right() + step, step):
+ p.drawRect(QRectF(x - 0.75, y - 0.75, 1.5, 1.5))
-class StatValue(QWidget):
- """A large stat display: value + label underneath."""
+class Page(QScrollArea):
+ """Scrollable page with consistent margins and a centered max width.
- def __init__(self, value: str = "0", label: str = "", accent: str = None, parent=None):
+ Rows registered with stack_when_narrow() switch to a vertical stack while
+ the side-by-side layout would not fit the viewport.
+ """
+
+ def __init__(self, parent=None):
super().__init__(parent)
- if accent is None:
- accent = theme.get_accent()
- layout = QVBoxLayout(self)
- layout.setContentsMargins(0, 0, 0, 0)
- layout.setSpacing(2)
- layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
-
- self._value_label = QLabel(value)
- self._value_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
- self._value_label.setStyleSheet(
- f"font-size: 28px; font-weight: 700; color: {accent}; background: transparent;"
- )
- layout.addWidget(self._value_label)
+ self.setWidgetResizable(True)
+ self.setFrameShape(QFrame.Shape.NoFrame)
+ self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
+ self._rows: list[QBoxLayout] = []
+ self._compact = False
+ self._wide_need = 0
+ self._pending = False
+ outer = _Paper()
+ outer.setObjectName("scrollContent")
+ outer.installEventFilter(self)
+ outer_lay = QHBoxLayout(outer)
+ outer_lay.setContentsMargins(PAGE_MARGIN, PAGE_MARGIN - 2, PAGE_MARGIN, PAGE_MARGIN)
+ self.content = QWidget()
+ self.content.setMaximumWidth(MAX_CONTENT_WIDTH)
+ self.layout_ = QVBoxLayout(self.content)
+ self.layout_.setContentsMargins(0, 0, 0, 0)
+ self.layout_.setSpacing(16)
+ outer_lay.addWidget(self.content)
+ self.setWidget(outer)
- self._desc_label = QLabel(label)
- self._desc_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
- self._desc_label.setStyleSheet(
- f"font-size: 11px; color: {theme.TEXT_DIM}; background: transparent;"
- )
- layout.addWidget(self._desc_label)
+ def add(self, item, stretch: int = 0) -> None:
+ if isinstance(item, QLayout):
+ self.layout_.addLayout(item, stretch)
+ else:
+ self.layout_.addWidget(item, stretch)
+
+ def stack_when_narrow(self, row: QBoxLayout) -> QBoxLayout:
+ self._rows.append(row)
+ return row
+
+ def resizeEvent(self, event):
+ super().resizeEvent(event)
+ self._update_compact()
+
+ def eventFilter(self, obj, event):
+ if event.type() == QEvent.Type.LayoutRequest and obj is self.widget() and self._rows and not self._pending:
+ self._pending = True
+ QTimer.singleShot(0, self, self._update_compact)
+ return super().eventFilter(obj, event)
+
+ def _update_compact(self) -> None:
+ self._pending = False
+ if not self._rows:
+ return
+ available = self.viewport().width()
+ if self._compact:
+ compact = available < self._wide_need
+ else:
+ self._wide_need = self.widget().minimumSizeHint().width()
+ compact = self._wide_need > available
+ if compact != self._compact:
+ self._compact = compact
+ direction = QBoxLayout.Direction.TopToBottom if compact else QBoxLayout.Direction.LeftToRight
+ for row in self._rows:
+ row.setDirection(direction)
+
+
+class PageHeader(QWidget):
+ """Kicker (engraved context line), title, subtitle and right-aligned actions."""
+
+ def __init__(self, title: str, subtitle: str = "", parent=None, kicker: str = ""):
+ super().__init__(parent)
+ lay = QHBoxLayout(self)
+ lay.setContentsMargins(0, 0, 0, 8)
+ lay.setSpacing(10)
+ left = QVBoxLayout()
+ left.setSpacing(4)
+ self.kicker = label(kicker, "eyebrowAccent")
+ self.kicker.setVisible(bool(kicker))
+ left.addWidget(self.kicker)
+ self.title = label(title, "title")
+ left.addWidget(self.title)
+ self.subtitle = label(subtitle, "subtitle")
+ self.subtitle.setVisible(bool(subtitle))
+ left.addWidget(self.subtitle)
+ lay.addLayout(left, 1)
+ self.actions = QHBoxLayout()
+ self.actions.setSpacing(8)
+ lay.addLayout(self.actions)
+ lay.setAlignment(self.actions, Qt.AlignmentFlag.AlignBottom)
+
+ def set_subtitle(self, text: str) -> None:
+ self.subtitle.setText(text)
+ self.subtitle.setVisible(bool(text))
+
+ def set_kicker(self, text: str) -> None:
+ self.kicker.setText(text)
+ self.kicker.setVisible(bool(text))
+
+
+# ---------------------------------------------------------------------------
+# Data display
+# ---------------------------------------------------------------------------
+
+
+class StatTile(QFrame):
+ """Readout: engraved caption, large tabular value and a secondary line.
+
+ Framed tiles are panels of their own; unframed ones sit in a MetricGrid.
+ """
+
+ def __init__(self, caption: str, icon: str | None = None, tone: str = "accent", parent=None, framed: bool = True):
+ super().__init__(parent)
+ self.setProperty("card" if framed else "cell", True)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ lay = QVBoxLayout(self)
+ lay.setContentsMargins(18, 14, 18, 16)
+ lay.setSpacing(6)
+ self.caption = eyebrow(caption)
+ lay.addWidget(self.caption)
+ self.value = label("–", "value")
+ lay.addWidget(self.value)
+ self.sub = label("", "caption")
+ lay.addWidget(self.sub)
+ self._number: float | None = None
+ self._formatter: Callable[[float], str] | None = None
+ self._count_on_show = False
+
+ def set(self, value: str, sub: str = "", sub_role: str = "caption", tooltip: str = "") -> None:
+ self.value.setText(value)
+ self.sub.setText(sub)
+ if self.sub.property("role") != sub_role:
+ set_role(self.sub, sub_role)
+ self.setToolTip(tooltip)
+
+ def set_number(
+ self,
+ number: float,
+ formatter: Callable[[float], str],
+ sub: str = "",
+ 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."""
+ previous, self._number, self._formatter = self._number, number, formatter
+ self.set(self.value.text(), sub, sub_role, tooltip)
+ current = motion.running(self, "count")
+ if current is not None:
+ current.setEndValue(float(number))
+ return
+ if previous is None:
+ if self.isVisible():
+ self._count(0.0, number)
+ else:
+ 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():
+ self._count(previous, number)
+ else:
+ self.value.setText(formatter(number))
+
+ def reset(self) -> None:
+ """Forget the shown number so the next value counts up from zero (e.g. a different item)."""
+ self._number = None
+
+ def _count(self, start: float, end: float) -> None:
+ motion.tween(self, float(start), float(end), motion.SLOWER, self._show_count, motion.DECELERATE, key="count")
+
+ def _show_count(self, value: float) -> None:
+ if self._formatter is not None:
+ self.value.setText(self._formatter(value))
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ if self._count_on_show and self._number is not None:
+ self._count_on_show = False
+ self._count(0.0, self._number)
+
+
+class MetricGrid(QFrame):
+ """One panel holding readouts in a grid separated by hairlines."""
+
+ def __init__(self, tiles: list[StatTile], columns: int = 2, parent=None):
+ super().__init__(parent)
+ self.setProperty("card", True)
+ grid = QGridLayout(self)
+ grid.setContentsMargins(0, 0, 0, 0)
+ grid.setSpacing(0)
+ rows = (len(tiles) + columns - 1) // columns
+ for i, tile in enumerate(tiles):
+ r, c = divmod(i, columns)
+ grid.addWidget(tile, r * 2, c * 2)
+ if c < columns - 1:
+ line = vdivider()
+ grid.addWidget(line, r * 2, c * 2 + 1)
+ if r < rows - 1:
+ grid.addWidget(divider(), r * 2 + 1, c * 2)
+ if c < columns - 1:
+ grid.addWidget(divider(), r * 2 + 1, c * 2 + 1)
+ for c in range(columns):
+ grid.setColumnStretch(c * 2, 1)
+
+
+@lru_cache(maxsize=256)
+def _file_icon(path: str, size: int) -> QPixmap:
+ try:
+ ic = QFileIconProvider().icon(QFileInfo(path))
+ return ic.pixmap(size, size) if not ic.isNull() else QPixmap()
+ except Exception:
+ return QPixmap()
+
+
+class AppAvatar(QWidget):
+ """The app's own icon when available, otherwise a colored monogram."""
+
+ def __init__(self, name: str, icon_path: str | None = None, size: int = 28, parent=None):
+ super().__init__(parent)
+ self._name = name or "?"
+ self._size = size
+ self._pixmap = _file_icon(icon_path, size) if icon_path else QPixmap()
+ self.setFixedSize(size, size)
+
+ def set_app(self, name: str, icon_path: str | None) -> None:
+ self._name = name or "?"
+ self._pixmap = _file_icon(icon_path, self._size) if icon_path else QPixmap()
+ self.update()
+
+ def paintEvent(self, _event):
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ if not self._pixmap.isNull():
+ p.drawPixmap(self.rect(), self._pixmap)
+ return
+ # Neutral monogram plate: calm, consistent, never a random colour.
+ t = theme.current()
+ radius = max(3.0, self._size * 0.16)
+ p.setPen(QPen(QColor(t.border_strong), 1))
+ p.setBrush(QColor(t.surface_alt))
+ p.drawRoundedRect(QRectF(0.5, 0.5, self._size - 1, self._size - 1), radius, radius)
+ p.setFont(fonts.mono(int(self._size * 0.42), 500, 0))
+ p.setPen(QColor(t.text_dim))
+ p.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, self._name.strip()[:1].upper())
+
+
+class UsageBar(QWidget):
+ """Thin horizontal meter with an optional limit marker."""
+
+ def __init__(
+ self,
+ fraction: float = 0.0,
+ tone: str = "accent",
+ marker: float | None = None,
+ animate_from: float | None = None,
+ parent=None,
+ ):
+ super().__init__(parent)
+ self._target = fraction
+ self._fraction = fraction if animate_from is None else animate_from
+ self._tone = tone
+ self._marker = marker
+ self._pending = animate_from is not None and abs(animate_from - fraction) > 0.001
+ self.setFixedHeight(10)
+ self.setMinimumWidth(60)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+
+ def set_value(self, fraction: float, tone: str | None = None, marker: float | None = None) -> None:
+ self._tone = tone or self._tone
+ self._marker = marker
+ self._morph(fraction)
+
+ def _morph(self, fraction: float) -> None:
+ self._target = fraction
+ motion.tween(self, self._fraction, fraction, motion.SLOW, self._set_fraction, motion.EASY_EASE, key="bar")
+
+ def _set_fraction(self, value: float) -> None:
+ self._fraction = value
+ self.update()
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ if self._pending:
+ self._pending = False
+ self._morph(self._target)
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ p.setPen(Qt.PenStyle.NoPen)
+ h, y = 4.0, (self.height() - 4) / 2
+ p.setBrush(QColor(t.track))
+ p.drawRoundedRect(QRectF(0, y, self.width(), h), 2, 2)
+ frac = max(0.0, min(1.0, self._fraction))
+ if frac > 0:
+ p.setBrush(QColor(tone_color(self._tone)))
+ p.drawRoundedRect(QRectF(0, y, max(h, self.width() * frac), h), 2, 2)
+ if self._marker is not None and 0 < self._marker < 1:
+ x = self.width() * self._marker
+ p.setBrush(QColor(t.text_dim))
+ p.drawRect(QRectF(x - 1, 0, 2, self.height()))
+
+
+class Swatch(QWidget):
+ """Small square colour key (category identity next to its label)."""
+
+ def __init__(self, color: str, size: int = 8, parent=None):
+ super().__init__(parent)
+ self._color = color
+ self.setFixedSize(size, size)
+
+ def paintEvent(self, _event):
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(self._color))
+ p.drawRoundedRect(QRectF(self.rect()), 1.5, 1.5)
+
+
+def legend_item(color: str, text: str) -> QWidget:
+ """Swatch plus caption, kept together when a legend wraps."""
+ host = QWidget()
+ row = QHBoxLayout(host)
+ row.setContentsMargins(0, 0, 0, 0)
+ row.setSpacing(6)
+ row.addWidget(Swatch(color, 8))
+ row.addWidget(label(text, "caption"))
+ return host
+
+
+class FlowLayout(QLayout):
+ """Left-to-right layout that wraps onto new lines (legends, chips)."""
- def set_value(self, v: str) -> None:
- self._value_label.setText(v)
+ def __init__(self, parent: QWidget | None = None, h_spacing: int = 16, v_spacing: int = 6):
+ super().__init__(parent)
+ self._items: list[QLayoutItem] = []
+ self._h, self._v = h_spacing, v_spacing
+ self.setContentsMargins(0, 0, 0, 0)
+
+ def addItem(self, item: QLayoutItem) -> None:
+ self._items.append(item)
+
+ def count(self) -> int:
+ return len(self._items)
+
+ def itemAt(self, index: int) -> QLayoutItem | None:
+ return self._items[index] if 0 <= index < len(self._items) else None
+
+ def takeAt(self, index: int) -> QLayoutItem | None:
+ return self._items.pop(index) if 0 <= index < len(self._items) else None
+
+ def expandingDirections(self) -> Qt.Orientation:
+ return Qt.Orientation(0)
+
+ def hasHeightForWidth(self) -> bool:
+ return True
+
+ def heightForWidth(self, width: int) -> int:
+ return self._arrange(QRect(0, 0, width, 0), apply=False)
+
+ def setGeometry(self, rect: QRect) -> None:
+ super().setGeometry(rect)
+ self._arrange(rect, apply=True)
+
+ def sizeHint(self) -> QSize:
+ return self.minimumSize()
+
+ def minimumSize(self) -> QSize:
+ size = QSize()
+ for item in self._items:
+ size = size.expandedTo(item.minimumSize())
+ return size
+
+ def _arrange(self, rect: QRect, apply: bool) -> int:
+ x, y, line = rect.x(), rect.y(), 0
+ for item in self._items:
+ hint = item.sizeHint()
+ if x > rect.x() and x + hint.width() > rect.right() + 1:
+ x, y, line = rect.x(), y + line + self._v, 0
+ if apply:
+ item.setGeometry(QRect(QPoint(x, y), hint))
+ x += hint.width() + self._h
+ line = max(line, hint.height())
+ return y + line - rect.y()
class AppRow(QFrame):
- """A row showing an app's name + usage bar."""
+ """Clickable list row: avatar, name, meter and value."""
clicked = Signal(int)
+ context_requested = Signal(int, QPoint)
- def __init__(self, app_id: int, name: str, value_ms: int, max_ms: int,
- is_favorite: bool = False, icon_path: str | None = None, parent=None):
+ def __init__(
+ self,
+ app: dict,
+ value: str,
+ fraction: float,
+ sub: str = "",
+ tone: str = "ink",
+ extra: str = "",
+ marker: float | None = None,
+ animate_from: float | None = None,
+ rank: int | None = None,
+ dot: str | None = None,
+ parent=None,
+ ):
super().__init__(parent)
- self._app_id = app_id
+ self.app_id = app["app_id"]
+ self.fraction = fraction
+ self._hover = 0.0
self.setCursor(Qt.CursorShape.PointingHandCursor)
- self.setMinimumHeight(56)
- self.setStyleSheet(f"""
- QFrame {{
- background: {theme.BG_CARD};
- border-radius: 8px;
- }}
- QFrame:hover {{
- background: {theme.BG_HOVER};
- }}
- """)
-
- layout = QHBoxLayout(self)
- layout.setContentsMargins(12, 8, 12, 8)
- layout.setSpacing(12)
-
- # Favorite star
- fav = QLabel("\u2605" if is_favorite else "\u2606")
- fav.setStyleSheet(f"color: {theme.YELLOW if is_favorite else theme.TEXT_MUTED}; font-size: 16px; background: transparent;")
- fav.setFixedWidth(20)
- layout.addWidget(fav)
-
- # App icon thumbnail (best-effort)
- icon_lbl = QLabel()
- icon_lbl.setFixedSize(20, 20)
- icon_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
- icon_lbl.setStyleSheet("background: transparent;")
- icon = self._load_app_icon(icon_path)
- if not icon.isNull():
- icon_lbl.setPixmap(icon)
- layout.addWidget(icon_lbl)
-
- # App name
- name_lbl = QLabel(name)
- name_lbl.setStyleSheet(f"font-weight: 600; color: {theme.TEXT}; background: transparent;")
- name_lbl.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
- name_lbl.setMinimumWidth(0)
- layout.addWidget(name_lbl, stretch=2)
-
- # Usage bar
- bar_container = QWidget()
- bar_container.setStyleSheet("background: transparent;")
- bar_layout = QHBoxLayout(bar_container)
- bar_layout.setContentsMargins(0, 0, 0, 0)
-
- bar_bg = QFrame()
- bar_bg.setFixedHeight(8)
- bar_bg.setStyleSheet(f"background: {theme.BG_INPUT}; border-radius: 4px;")
- bar_bg.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
-
- pct = min(value_ms / max(max_ms, 1), 1.0)
- bar_fill = QFrame(bar_bg)
- bar_fill.setFixedHeight(8)
- bar_fill.setMinimumWidth(max(int(pct * 300), 2))
- bar_fill.setMaximumWidth(int(pct * 300))
- bar_fill.setStyleSheet(
- f"background: qlineargradient(x1:0,y1:0,x2:1,y2:0, stop:0 {theme.get_accent()}, stop:1 {theme.PURPLE});"
- f"border-radius: 4px;"
+ self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
+ self.setAccessibleName(f"{app.get('name', '')}, {value}")
+ self.setToolTip(f"{app.get('name', '')}: {value}" + (f" ({sub})" if sub else ""))
+ self.setMinimumHeight(46)
+
+ lay = QHBoxLayout(self)
+ lay.setContentsMargins(8, 6, 10, 6)
+ lay.setSpacing(12)
+ if rank is not None:
+ num = label(f"{rank:02d}", "tick")
+ num.setFixedWidth(18)
+ lay.addWidget(num)
+ lay.addWidget(AppAvatar(app.get("name", ""), app.get("icon_path"), 28))
+
+ text = QVBoxLayout()
+ text.setContentsMargins(0, 0, 0, 0)
+ text.setSpacing(1)
+ name_row = QHBoxLayout()
+ name_row.setSpacing(6)
+ name = label(app.get("name", ""))
+ name.setFont(fonts.sans(13, 600))
+ name_row.addWidget(name)
+ if app.get("is_favorite"):
+ name_row.addWidget(icon_label("star", "gold", 12, filled=True))
+ name_row.addStretch(1)
+ text.addLayout(name_row)
+ if sub:
+ sub_row = QHBoxLayout()
+ sub_row.setSpacing(6)
+ if dot:
+ sub_row.addWidget(Swatch(dot, 6))
+ sub_row.addWidget(label(sub, "caption"), 1)
+ text.addLayout(sub_row)
+ holder = QWidget()
+ holder.setLayout(text)
+ holder.setMinimumWidth(120)
+ holder.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
+ lay.addWidget(holder, 3)
+
+ self.bar = UsageBar(fraction, tone, marker, animate_from)
+ lay.addWidget(self.bar, 2)
+
+ val = label(
+ value,
+ "danger" if tone == "danger" else None,
+ align=Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
)
+ val.setFont(fonts.sans(13, 600, tabular=True))
+ val.setMinimumWidth(70)
+ lay.addWidget(val)
+ if extra:
+ ex = label(extra, "tick", align=Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
+ ex.setMinimumWidth(34)
+ lay.addWidget(ex)
- bar_layout.addWidget(bar_bg)
- layout.addWidget(bar_container, stretch=1)
+ def mouseReleaseEvent(self, event):
+ if event.button() == Qt.MouseButton.LeftButton and self.rect().contains(event.position().toPoint()):
+ self.clicked.emit(self.app_id)
+ super().mouseReleaseEvent(event)
- # Time label
- time_lbl = QLabel(theme.format_ms(value_ms))
- time_lbl.setStyleSheet(f"color: {theme.get_accent()}; font-weight: 600; background: transparent;")
- time_lbl.setFixedWidth(84)
- time_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
- layout.addWidget(time_lbl)
+ def keyPressEvent(self, event):
+ if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter, Qt.Key.Key_Space):
+ self.clicked.emit(self.app_id)
+ return
+ if event.key() == Qt.Key.Key_Menu:
+ self.context_requested.emit(self.app_id, self.mapToGlobal(self.rect().center()))
+ return
+ super().keyPressEvent(event)
- def mousePressEvent(self, event):
- self.clicked.emit(self._app_id)
- super().mousePressEvent(event)
+ def contextMenuEvent(self, event):
+ self.context_requested.emit(self.app_id, event.globalPos())
- @staticmethod
- def _load_app_icon(icon_path: str | None) -> QPixmap:
- if not icon_path:
- return QPixmap()
- try:
- provider = QFileIconProvider()
- icon = provider.icon(QFileInfo(icon_path))
- if icon.isNull():
- return QPixmap()
- return icon.pixmap(20, 20)
- except Exception:
- return QPixmap()
-
-
-class SidebarButton(QPushButton):
- """Navigation sidebar button with icon + text."""
-
- def __init__(self, icon_char: str, text: str, parent=None):
+ def enterEvent(self, event):
+ motion.tween(self, self._hover, 1.0, motion.FASTER, self._set_hover, motion.DECELERATE, key="hover")
+ super().enterEvent(event)
+
+ def leaveEvent(self, event):
+ motion.tween(self, self._hover, 0.0, motion.FAST, self._set_hover, motion.ACCELERATE, key="hover")
+ super().leaveEvent(event)
+
+ def _set_hover(self, value: float) -> None:
+ self._hover = value
+ self.update()
+
+ def focusInEvent(self, event):
+ self.update()
+ super().focusInEvent(event)
+
+ def focusOutEvent(self, event):
+ self.update()
+ super().focusOutEvent(event)
+
+ def paintEvent(self, event):
+ t = theme.current()
+ strength = max(self._hover, 1.0 if self.hasFocus() else 0.0)
+ if strength > 0:
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ fill = QColor(t.hover)
+ fill.setAlphaF(strength)
+ p.setPen(QPen(QColor(t.accent), 1) if self.hasFocus() else Qt.PenStyle.NoPen)
+ p.setBrush(fill)
+ p.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 8, 8)
+ p.end()
+ super().paintEvent(event)
+
+
+ILLUSTRATIONS = {
+ "calendar-days": "calendar",
+ "search": "search",
+ "layout-grid": "search",
+ "star": "star",
+ "mouse-pointer-click": "clicks",
+ "power": "unplugged",
+ "gift": "gift",
+ "zap": "waiting",
+ "clock": "waiting",
+ "castle": "blueprint",
+}
+
+
+class Illustration(QLabel):
+ """Hairline line-art that re-tints itself with the theme."""
+
+ def __init__(self, name: str, width: int = 120, parent=None):
super().__init__(parent)
- self.setText(f" {icon_char} {text}")
- self.setFixedHeight(44)
- self.setCheckable(True)
- self.setStyleSheet(f"""
- QPushButton {{
- background: transparent;
- color: {theme.TEXT_DIM};
- border: none;
- border-radius: 8px;
- text-align: left;
- padding: 0 16px;
- font-size: 14px;
- font-weight: 600;
- }}
- QPushButton:hover {{
- background: {theme.BG_HOVER};
- color: {theme.TEXT};
- }}
- QPushButton:checked {{
- background: {theme.BG_CARD};
- color: {theme.get_accent()};
- border-left: 3px solid {theme.get_accent()};
- }}
- """)
-
-
-class GradientBar(QWidget):
- """Horizontal gradient bar for charts."""
-
- def __init__(self, value: float = 0.0, max_val: float = 1.0,
- color_start: str = None, color_end: str = theme.PURPLE,
- parent=None):
+ self._name = name
+ self._width = width
+ self.setFixedSize(width, int(width * 0.8))
+
+ def apply():
+ t = theme.current()
+ try:
+ self.setPixmap(icons.illustration(name, t.text_dim, t.accent, t.border, width))
+ except RuntimeError:
+ pass
+
+ apply()
+ self._apply = apply
+ bus.theme_changed.connect(apply)
+ self.destroyed.connect(lambda *_: _safe_disconnect(apply))
+
+
+class EmptyState(QWidget):
+ """Illustration, title, explanation and an optional next step."""
+
+ def __init__(
+ self, icon: str, title: str, message: str = "", action: str = "", on_action: Callable | None = None, parent=None
+ ):
+ super().__init__(parent)
+ lay = QVBoxLayout(self)
+ lay.setContentsMargins(16, 20, 16, 24)
+ lay.setSpacing(6)
+ lay.setAlignment(Qt.AlignmentFlag.AlignCenter)
+ art = ILLUSTRATIONS.get(icon)
+ if art:
+ lay.addWidget(Illustration(art, 110), 0, Qt.AlignmentFlag.AlignHCenter)
+ else:
+ lay.addWidget(icon_label(icon, "text_muted", 28), 0, Qt.AlignmentFlag.AlignHCenter)
+ lay.addSpacing(2)
+ lay.addWidget(label(title, "heading", align=Qt.AlignmentFlag.AlignCenter))
+ if message:
+ msg = label(message, "dim", wrap=True, align=Qt.AlignmentFlag.AlignCenter)
+ msg.setMaximumWidth(400)
+ lay.addWidget(msg, 0, Qt.AlignmentFlag.AlignHCenter)
+ if action and on_action:
+ lay.addSpacing(8)
+ lay.addWidget(button(action, on_click=on_action), 0, Qt.AlignmentFlag.AlignHCenter)
+
+
+class SegmentedControl(QFrame):
+ changed = Signal(int)
+
+ def __init__(self, options: list[str], current: int = 0, parent=None):
+ super().__init__(parent)
+ self.setProperty("segmented", True)
+ lay = QHBoxLayout(self)
+ lay.setContentsMargins(3, 3, 3, 3)
+ lay.setSpacing(2)
+ self._thumb = QFrame(self)
+ self._thumb.setObjectName("segThumb")
+ self._thumb.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self._group = QButtonGroup(self)
+ self._group.setExclusive(True)
+ for i, text in enumerate(options):
+ b = QPushButton(text)
+ b.setProperty("segment", True)
+ b.setCheckable(True)
+ b.setCursor(Qt.CursorShape.PointingHandCursor)
+ b.setFocusPolicy(Qt.FocusPolicy.TabFocus)
+ b.installEventFilter(self)
+ self._group.addButton(b, i)
+ lay.addWidget(b)
+ self._group.button(current).setChecked(True)
+ self._group.idClicked.connect(self._on_clicked)
+
+ def current(self) -> int:
+ return self._group.checkedId()
+
+ def set_current(self, index: int) -> None:
+ btn = self._group.button(index)
+ if btn and not btn.isChecked():
+ btn.setChecked(True)
+ self._move_thumb(animate=self.isVisible())
+
+ def _on_clicked(self, index: int) -> None:
+ self._move_thumb(animate=True)
+ self.changed.emit(index)
+
+ def _move_thumb(self, animate: bool) -> None:
+ btn = self._group.checkedButton()
+ if btn is None:
+ return
+ target = QRectF(btn.geometry())
+ if animate:
+ start = QRectF(self._thumb.geometry())
+ motion.tween(
+ self,
+ start,
+ target,
+ motion.NORMAL,
+ lambda r: self._thumb.setGeometry(r.toRect()),
+ motion.EASY_EASE,
+ key="thumb",
+ )
+ else:
+ self._thumb.setGeometry(target.toRect())
+ self._thumb.lower()
+
+ def eventFilter(self, obj, event):
+ if event.type() in (QEvent.Type.Resize, QEvent.Type.Move) and obj is self._group.checkedButton():
+ if motion.running(self, "thumb") is None:
+ self._move_thumb(animate=False)
+ return super().eventFilter(obj, event)
+
+
+class Toggle(QAbstractButton):
+ """Animated on/off switch."""
+
+ def __init__(self, checked: bool = False, parent=None):
super().__init__(parent)
- if color_start is None:
- color_start = theme.get_accent()
- self._value = value
- self._max_val = max_val
- self._c1 = QColor(color_start)
- self._c2 = QColor(color_end)
- self.setFixedHeight(12)
- self.setMinimumWidth(40)
-
- def set_value(self, v: float, max_v: float | None = None):
- self._value = v
- if max_v is not None:
- self._max_val = max_v
+ self.setCheckable(True)
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.setFocusPolicy(Qt.FocusPolicy.TabFocus)
+ self._knob = 1.0 if checked else 0.0
+ super().setChecked(checked)
+ self.toggled.connect(self._animate)
+
+ def sizeHint(self) -> QSize:
+ return QSize(40, 22)
+
+ def set_silently(self, checked: bool) -> None:
+ self.blockSignals(True)
+ self.setChecked(checked)
+ self.blockSignals(False)
+ self._knob = 1.0 if checked else 0.0
self.update()
- def paintEvent(self, event):
+ def _get_knob(self) -> float:
+ return self._knob
+
+ def _set_knob(self, value: float) -> None:
+ self._knob = value
+ self.update()
+
+ knob = Property(float, _get_knob, _set_knob)
+
+ 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"
+ )
+
+ def paintEvent(self, _event):
+ t = theme.current()
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
- w = self.width()
- h = self.height()
-
- # Background
+ 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),
+ )
+ 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)
- p.setBrush(QColor(theme.BG_INPUT))
- p.drawRoundedRect(0, 0, w, h, h // 2, h // 2)
-
- # Fill
- pct = min(self._value / max(self._max_val, 1), 1.0)
- fill_w = max(int(pct * w), 0)
- if fill_w > 0:
- grad = QLinearGradient(0, 0, fill_w, 0)
- grad.setColorAt(0, self._c1)
- grad.setColorAt(1, self._c2)
- p.setBrush(grad)
- p.drawRoundedRect(0, 0, fill_w, h, h // 2, h // 2)
- p.end()
+ 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)
+
+
+class SettingRow(QWidget):
+ """Title and description on the left, a control on the right."""
+
+ def __init__(self, title: str, description: str = "", control: QWidget | None = None, parent=None):
+ super().__init__(parent)
+ lay = QHBoxLayout(self)
+ lay.setContentsMargins(0, 6, 0, 6)
+ lay.setSpacing(16)
+ text = QVBoxLayout()
+ text.setSpacing(2)
+ t = label(title)
+ t.setFont(fonts.sans(13, 600))
+ text.addWidget(t)
+ if description:
+ text.addWidget(label(description, "caption", wrap=True))
+ lay.addLayout(text, 1)
+ if control is not None:
+ lay.addWidget(control, 0, Qt.AlignmentFlag.AlignVCenter)
+ if isinstance(control, QAbstractButton):
+ control.setAccessibleName(title)
+
+
+class Toast(QFrame):
+ """Transient message at the bottom of the window, with an optional action."""
+
+ def __init__(self, parent: QWidget):
+ super().__init__(parent)
+ self.setObjectName("toast")
+ lay = QHBoxLayout(self)
+ lay.setContentsMargins(14, 10, 10, 10)
+ lay.setSpacing(10)
+ self._icon = QLabel()
+ self._icon.setFixedSize(16, 16)
+ lay.addWidget(self._icon)
+ self._text = QLabel()
+ lay.addWidget(self._text, 1)
+ self._action = button("", kind="link")
+ self._action.hide()
+ lay.addWidget(self._action)
+ self._callback: Callable | None = None
+ self._action.clicked.connect(self._run_action)
+ self._effect = QGraphicsOpacityEffect(self)
+ self.setGraphicsEffect(self._effect)
+ self._rest_y = 0
+ self._timer = QTimer(self)
+ self._timer.setSingleShot(True)
+ self._timer.timeout.connect(self.dismiss)
+ self.hide()
+
+ def show_message(
+ self, text: str, tone: str = "success", action: str = "", callback: Callable | None = None, msec: int = 3200
+ ) -> None:
+ name = {"success": "circle-check", "danger": "triangle-alert", "warning": "triangle-alert", "info": "info"}.get(
+ tone, "info"
+ )
+ self._icon.setPixmap(icons.pixmap(name, tone_color("accent" if tone == "success" else tone), 16))
+ self._text.setText(text)
+ self._callback = callback
+ self._action.setText(action)
+ self._action.setVisible(bool(action and callback))
+ was_visible = self.isVisible() and self._effect.opacity() > 0.5
+ self.adjustSize()
+ self.reposition()
+ self.raise_()
+ self.show()
+ if was_visible:
+ self._animate(0, 0, 1.0, 1.0, 0, motion.LINEAR) # cancel a dismissal in progress
+ else:
+ self._animate(12, 0, 0.0, 1.0, motion.GENTLE, motion.DECELERATE)
+ self._timer.start(msec + (2500 if action else 0))
+
+ def _animate(self, dy0: float, dy1: float, op0: float, op1: float, duration: int, easing, on_done=None) -> None:
+ def step(t: float) -> None:
+ self.move(self.x(), int(self._rest_y + motion.lerp(dy0, dy1, t)))
+ self._effect.setOpacity(motion.lerp(op0, op1, t))
+
+ motion.tween(self, 0.0, 1.0, duration, step, easing, on_done, key="toast")
+
+ def reposition(self) -> None:
+ parent = self.parentWidget()
+ if not parent:
+ return
+ self.setMaximumWidth(min(560, parent.width() - 40))
+ self.adjustSize()
+ x = (parent.width() - self.width()) // 2
+ self._rest_y = parent.height() - self.height() - 24
+ self.move(max(20, x), self._rest_y)
+
+ def dismiss(self) -> None:
+ if self.isVisible():
+ self._animate(0, 8, self._effect.opacity(), 0.0, motion.FAST, motion.ACCELERATE, self.hide)
+
+ def _run_action(self) -> None:
+ callback, self._callback = self._callback, None
+ self.dismiss()
+ if callback:
+ callback()
+
+
+class Badge(QLabel):
+ """Small counter pill used on navigation items."""
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.setObjectName("navBadge")
+ self.setFont(fonts.mono(9, 500, 0))
+ self.setFixedHeight(16)
+ self.setAlignment(Qt.AlignmentFlag.AlignCenter)
+ self.hide()
+
+ def set_count(self, n: int) -> None:
+ self.setText(str(n) if n < 100 else "99+")
+ self.setVisible(n > 0)
+
+
+class StatusModule(QAbstractButton):
+ """Sidebar recorder module: live dot, state, current app and session clock."""
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.setFocusPolicy(Qt.FocusPolicy.TabFocus)
+ self.setFixedHeight(60)
+ self._head, self._name, self._clock, self._tone, self._live = "", "", "", "text_muted", False
+ self._hover = False
+ self.pulse = motion.PulseDot(5, self)
+ self.pulse.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self.pulse.move(10, 9)
+
+ def set_status(self, head: str, name: str, clock: str, tone: str, live: bool) -> None:
+ self._head, self._name, self._clock, self._tone, self._live = head, name, clock, tone, live
+ self.pulse.set_state(live, tone_color(tone))
+ self.setAccessibleName(f"{head}: {name} {clock}".strip())
+ self.update()
+
+ def enterEvent(self, event):
+ self._hover = True
+ self.update()
+ super().enterEvent(event)
+
+ def leaveEvent(self, event):
+ self._hover = False
+ self.update()
+ super().leaveEvent(event)
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ edge = t.accent if self.hasFocus() else (t.text_muted if self._hover else t.border)
+ p.setPen(QPen(QColor(edge), 1))
+ p.setBrush(QColor(t.surface))
+ p.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), theme.RADIUS_PANEL, theme.RADIUS_PANEL)
+ if not self._live:
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(tone_color(self._tone)))
+ p.drawRoundedRect(QRectF(16, 16, 8, 8), 1.5, 1.5)
+ p.setFont(fonts.mono(9, 500, 10))
+ p.setPen(QColor(tone_color("accent_text" if self._live else self._tone)))
+ p.drawText(QRectF(32, 10, self.width() - 40, 16), Qt.AlignmentFlag.AlignVCenter, self._head.upper())
+ p.setPen(QColor(t.text_dim))
+ p.drawText(
+ QRectF(32, 10, self.width() - 44, 16),
+ Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignRight,
+ self._clock,
+ )
+ p.setFont(fonts.sans(13, 600))
+ p.setPen(QColor(t.text))
+ name = p.fontMetrics().elidedText(self._name, Qt.TextElideMode.ElideRight, self.width() - 26)
+ p.drawText(QRectF(14, 30, self.width() - 26, 20), Qt.AlignmentFlag.AlignVCenter, name)
diff --git a/apptrackr/updater/__init__.py b/apptrackr/updater/__init__.py
index e69de29..985f14b 100644
--- a/apptrackr/updater/__init__.py
+++ b/apptrackr/updater/__init__.py
@@ -0,0 +1 @@
+"""Update checks against GitHub releases."""
diff --git a/apptrackr/updater/apply.py b/apptrackr/updater/apply.py
index 916823b..55bd2ed 100644
--- a/apptrackr/updater/apply.py
+++ b/apptrackr/updater/apply.py
@@ -1,33 +1,61 @@
-"""Apply downloaded updates."""
+"""Download and launch an installer."""
from __future__ import annotations
import logging
-import os
import subprocess
import sys
import tempfile
+import threading
from pathlib import Path
-from urllib.request import urlopen, Request
+from typing import Callable
+from urllib.request import Request, urlopen
+
+from .. import __version__
log = logging.getLogger(__name__)
-def download_and_apply(url: str) -> str | None:
- """Download installer from *url* and launch it, then exit the current app."""
- if not url:
- return None
+class DownloadCancelled(Exception):
+ pass
+
+
+def download(
+ url: str,
+ progress: Callable[[int, int], None] | None = None,
+ cancel: threading.Event | None = None,
+ dest_dir: Path | None = None,
+) -> Path:
+ """Stream *url* to a temp file, reporting (received, total) bytes."""
+ dest = (dest_dir or Path(tempfile.gettempdir())) / "AppTrackr_Setup.exe"
+ partial = dest.with_suffix(".part")
+ req = Request(url, headers={"User-Agent": f"AppTrackr/{__version__}"})
try:
- req = Request(url)
- with urlopen(req, timeout=120) as resp: # noqa: S310 — URL comes from configured update manifest
- data = resp.read()
-
- tmp = Path(tempfile.gettempdir()) / "apptrackr_update.exe"
- tmp.write_bytes(data)
-
- # Launch installer and exit
- subprocess.Popen([str(tmp)], creationflags=subprocess.DETACHED_PROCESS) # noqa: S603
- return str(tmp)
- except Exception:
- log.exception("Failed to download/apply update")
- return None
+ with urlopen(req, timeout=60) as resp, open(partial, "wb") as out: # noqa: S310
+ total = int(resp.headers.get("Content-Length") or 0)
+ received = 0
+ while True:
+ if cancel is not None and cancel.is_set():
+ raise DownloadCancelled()
+ chunk = resp.read(256 * 1024)
+ if not chunk:
+ break
+ out.write(chunk)
+ received += len(chunk)
+ if progress:
+ progress(received, total)
+ if total and received != total:
+ raise OSError(f"Download incomplete ({received} of {total} bytes)")
+ except BaseException:
+ partial.unlink(missing_ok=True)
+ raise
+ partial.replace(dest)
+ return dest
+
+
+def launch_installer(path: Path) -> None:
+ """Start the installer detached from this process."""
+ flags = 0
+ if sys.platform.startswith("win"):
+ flags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
+ subprocess.Popen([str(path)], creationflags=flags, close_fds=True) # noqa: S603
diff --git a/apptrackr/updater/check.py b/apptrackr/updater/check.py
index c30f364..a1f7160 100644
--- a/apptrackr/updater/check.py
+++ b/apptrackr/updater/check.py
@@ -1,39 +1,89 @@
-"""Check for updates from a remote manifest."""
+"""Check GitHub releases for a newer version."""
from __future__ import annotations
import json
import logging
-from urllib.request import urlopen, Request
+import os
+import re
+from dataclasses import dataclass
from urllib.error import URLError
+from urllib.request import Request, urlopen
-from .manifest import CURRENT_VERSION, get_update_url
+from .. import __version__
log = logging.getLogger(__name__)
+DEFAULT_UPDATE_URL = "https://api.github.com/repos/H4ch1Net/AppTrackr/releases/latest"
+INSTALLER_NAME = "AppTrackr_Setup.exe"
-def parse_version(v: str) -> tuple[int, ...]:
- return tuple(int(x) for x in v.strip().lstrip("v").split("."))
+class UpdateError(Exception):
+ """The update feed could not be reached or understood."""
-def check_for_update(update_url: str | None = None) -> dict | None:
- """Return {'version': str, 'url': str} if an update is available, else None."""
- resolved_url = (update_url or get_update_url()).strip()
- if not resolved_url:
- return None
+
+@dataclass(frozen=True)
+class UpdateInfo:
+ version: str
+ download_url: str
+ page_url: str
+ size: int = 0
+
+
+def resolve_url(configured: str = "") -> str:
+ """Configured URL, then the APPTRACKR_UPDATE_URL environment variable, then the default."""
+ return (configured or "").strip() or os.environ.get("APPTRACKR_UPDATE_URL", "").strip() or DEFAULT_UPDATE_URL
+
+
+def parse_version(text: str) -> tuple[int, ...]:
+ """Parse "v1.2.3", "1.2" or "1.2.3-beta" into a comparable tuple of ints."""
+ match = re.match(r"\s*v?(\d+(?:\.\d+)*)", text or "")
+ if not match:
+ raise ValueError(f"Unrecognised version: {text!r}")
+ parts = [int(p) for p in match.group(1).split(".")]
+ while len(parts) < 3:
+ parts.append(0)
+ return tuple(parts)
+
+
+def is_newer(remote: str, current: str = __version__) -> bool:
+ return parse_version(remote) > parse_version(current)
+
+
+def _pick_asset(assets: list[dict]) -> dict | None:
+ exes = [a for a in assets if str(a.get("name", "")).lower().endswith(".exe")]
+ for asset in exes:
+ if asset.get("name") == INSTALLER_NAME:
+ return asset
+ return exes[0] if exes else None
+
+
+def check_for_update(url: str = "", current: str = __version__, timeout: float = 10) -> UpdateInfo | None:
+ """Return UpdateInfo when a newer release exists, None when up to date.
+
+ Raises UpdateError when the feed cannot be read.
+ """
+ feed = resolve_url(url)
+ req = Request(feed, headers={"Accept": "application/vnd.github+json", "User-Agent": f"AppTrackr/{current}"})
+ try:
+ with urlopen(req, timeout=timeout) as resp: # noqa: S310 - https feed chosen by the user
+ data = json.loads(resp.read().decode("utf-8"))
+ except (URLError, OSError) as exc:
+ raise UpdateError(f"Could not reach the update server ({exc}).") from exc
+ except ValueError as exc:
+ raise UpdateError("The update server returned an unexpected response.") from exc
+
+ tag = str(data.get("tag_name") or "")
try:
- req = Request(resolved_url, headers={"Accept": "application/json"})
- with urlopen(req, timeout=10) as resp: # noqa: S310 — URL is configured by the developer
- data = json.loads(resp.read())
- remote_version = data.get("tag_name", "").lstrip("v")
- if parse_version(remote_version) > parse_version(CURRENT_VERSION):
- assets = data.get("assets", [])
- download_url = ""
- for asset in assets:
- if asset.get("name", "").endswith(".exe"):
- download_url = asset["browser_download_url"]
- break
- return {"version": remote_version, "url": download_url}
- except (URLError, ValueError, KeyError):
- log.debug("Update check failed", exc_info=True)
- return None
+ newer = is_newer(tag, current)
+ except ValueError as exc:
+ raise UpdateError(f"The latest release has an unrecognised version ({tag!r}).") from exc
+ if not newer:
+ return None
+ asset = _pick_asset(data.get("assets") or [])
+ return UpdateInfo(
+ version=tag.lstrip("v"),
+ download_url=(asset or {}).get("browser_download_url", ""),
+ page_url=str(data.get("html_url") or ""),
+ size=int((asset or {}).get("size") or 0),
+ )
diff --git a/apptrackr/updater/manifest.py b/apptrackr/updater/manifest.py
deleted file mode 100644
index 15563a3..0000000
--- a/apptrackr/updater/manifest.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""Update manifest and version checking."""
-
-from __future__ import annotations
-
-import os
-
-CURRENT_VERSION = "1.0.0"
-UPDATE_URL = "" # Set to GitHub releases URL when ready, e.g.: https://api.github.com/repos/user/apptrackr/releases/latest
-
-
-def get_update_url() -> str:
- """Return configured update URL from environment or built-in default."""
- return os.environ.get("APPTRACKR_UPDATE_URL", "").strip() or UPDATE_URL
diff --git a/docs/banner-dark.png b/docs/banner-dark.png
new file mode 100644
index 0000000..51895fb
Binary files /dev/null and b/docs/banner-dark.png differ
diff --git a/docs/banner-light.png b/docs/banner-light.png
new file mode 100644
index 0000000..fdc2aec
Binary files /dev/null and b/docs/banner-light.png differ
diff --git a/docs/screenshots/app-detail.png b/docs/screenshots/app-detail.png
new file mode 100644
index 0000000..a217b16
Binary files /dev/null and b/docs/screenshots/app-detail.png differ
diff --git a/docs/screenshots/apps.png b/docs/screenshots/apps.png
new file mode 100644
index 0000000..9961a0d
Binary files /dev/null and b/docs/screenshots/apps.png differ
diff --git a/docs/screenshots/calendar.png b/docs/screenshots/calendar.png
new file mode 100644
index 0000000..8c83045
Binary files /dev/null and b/docs/screenshots/calendar.png differ
diff --git a/docs/screenshots/dashboard-light.png b/docs/screenshots/dashboard-light.png
new file mode 100644
index 0000000..797df2f
Binary files /dev/null and b/docs/screenshots/dashboard-light.png differ
diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png
new file mode 100644
index 0000000..ebebe31
Binary files /dev/null and b/docs/screenshots/dashboard.png differ
diff --git a/docs/screenshots/demo.gif b/docs/screenshots/demo.gif
new file mode 100644
index 0000000..a8dba98
Binary files /dev/null and b/docs/screenshots/demo.gif differ
diff --git a/docs/screenshots/rewards.png b/docs/screenshots/rewards.png
new file mode 100644
index 0000000..ad1732a
Binary files /dev/null and b/docs/screenshots/rewards.png differ
diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png
new file mode 100644
index 0000000..3308b66
Binary files /dev/null and b/docs/screenshots/settings.png differ
diff --git a/docs/screenshots/village.png b/docs/screenshots/village.png
new file mode 100644
index 0000000..d758853
Binary files /dev/null and b/docs/screenshots/village.png differ
diff --git a/docs/social-preview.png b/docs/social-preview.png
new file mode 100644
index 0000000..072cb45
Binary files /dev/null and b/docs/social-preview.png differ
diff --git a/packaging/apptrackr.ico b/packaging/apptrackr.ico
new file mode 100644
index 0000000..ab2a632
Binary files /dev/null and b/packaging/apptrackr.ico differ
diff --git a/packaging/apptrackr.spec b/packaging/apptrackr.spec
index 30c3f83..e4d2f24 100644
--- a/packaging/apptrackr.spec
+++ b/packaging/apptrackr.spec
@@ -1,58 +1,47 @@
# -*- mode: python ; coding: utf-8 -*-
-# PyInstaller spec for AppTrackr
+# PyInstaller spec for AppTrackr. Build from the repository root:
+# pyinstaller packaging/apptrackr.spec
import os
-import sys
-block_cipher = None
ROOT = os.path.abspath(os.getcwd())
+PKG = os.path.join(ROOT, "apptrackr")
a = Analysis(
- [os.path.join(ROOT, 'apptrackr', '__main__.py')],
+ [os.path.join(PKG, "__main__.py")],
pathex=[ROOT],
binaries=[],
datas=[
- (os.path.join(ROOT, 'apptrackr', 'data', 'schema.sql'), os.path.join('apptrackr', 'data')),
- ],
- hiddenimports=[
- 'PySide6.QtWidgets',
- 'PySide6.QtCore',
- 'PySide6.QtGui',
- 'psutil',
+ (os.path.join(PKG, "data", "schema.sql"), os.path.join("apptrackr", "data")),
+ (os.path.join(PKG, "assets"), os.path.join("apptrackr", "assets")),
],
+ hiddenimports=["PySide6.QtSvg", "PySide6.QtNetwork", "pynput.mouse._win32"],
hookspath=[],
- hooksconfig={},
runtime_hooks=[],
- excludes=[],
- win_no_prefer_redirects=False,
- win_private_assemblies=False,
- cipher=block_cipher,
+ excludes=["tkinter", "PySide6.QtWebEngineCore", "PySide6.QtQml", "PySide6.QtQuick", "PySide6.Qt3DCore"],
noarchive=False,
)
-pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
+pyz = PYZ(a.pure, a.zipped_data)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
- name='AppTrackr',
+ name="AppTrackr",
debug=False,
- bootloader_ignore_signals=False,
strip=False,
- upx=True,
+ upx=False,
console=False,
- icon=None, # Add .ico path here when available
+ icon=os.path.join(ROOT, "packaging", "apptrackr.ico"),
)
coll = COLLECT(
exe,
a.binaries,
- a.zipfiles,
a.datas,
strip=False,
- upx=True,
- upx_exclude=[],
- name='AppTrackr',
+ upx=False,
+ name="AppTrackr",
)
diff --git a/packaging/installer.iss b/packaging/installer.iss
index fe7cd81..3261317 100644
--- a/packaging/installer.iss
+++ b/packaging/installer.iss
@@ -1,37 +1,55 @@
-; Inno Setup script for AppTrackr
+; Inno Setup script for AppTrackr. Build after PyInstaller from the repository root:
+; iscc /DAppVersion=1.1.0 packaging\installer.iss
+
+#ifndef AppVersion
+ #define AppVersion "1.1.0"
+#endif
[Setup]
+; Same AppId as v1.0 (Inno defaults it to AppName) so upgrades replace the old install.
+AppId=AppTrackr
AppName=AppTrackr
-AppVersion=1.0.0
-AppPublisher=AppTrackr
+AppVersion={#AppVersion}
+AppVerName=AppTrackr {#AppVersion}
+AppPublisher=H4ch1Net
+AppPublisherURL=https://github.com/H4ch1Net/AppTrackr
+AppSupportURL=https://github.com/H4ch1Net/AppTrackr/issues
DefaultDirName={localappdata}\AppTrackr
DefaultGroupName=AppTrackr
+DisableProgramGroupPage=yes
+OutputDir=Output
OutputBaseFilename=AppTrackr_Setup
+SetupIconFile=apptrackr.ico
+UninstallDisplayIcon={app}\AppTrackr.exe
Compression=lzma2
SolidCompression=yes
PrivilegesRequired=lowest
-SetupIconFile=
-UninstallDisplayIcon={app}\AppTrackr.exe
+ArchitecturesInstallIn64BitMode=x64compatible
+CloseApplications=force
+RestartApplications=no
+WizardStyle=modern
+
+[Tasks]
+Name: "desktopicon"; Description: "Create a desktop shortcut"; GroupDescription: "Shortcuts:"
+Name: "autostart"; Description: "Start AppTrackr when I sign in"; GroupDescription: "Startup:"
[Files]
-Source: "..\dist\AppTrackr\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs
+Source: "..\dist\AppTrackr\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons]
Name: "{group}\AppTrackr"; Filename: "{app}\AppTrackr.exe"
-Name: "{autodesktop}\AppTrackr"; Filename: "{app}\AppTrackr.exe"
-
-[Tasks]
-Name: "autostart"; Description: "Launch AppTrackr on system startup"; GroupDescription: "System:"
+Name: "{autodesktop}\AppTrackr"; Filename: "{app}\AppTrackr.exe"; Tasks: desktopicon
[Registry]
-Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; \
- ValueType: string; ValueName: "AppTrackr"; \
- ValueData: """{app}\AppTrackr.exe"""; Flags: uninsdeletevalue; Tasks: autostart
+Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; \
+ ValueName: "AppTrackr"; ValueData: """{app}\AppTrackr.exe"" --minimized"; \
+ Flags: uninsdeletevalue; Tasks: autostart
[Run]
Filename: "{app}\AppTrackr.exe"; Description: "Launch AppTrackr"; Flags: nowait postinstall skipifsilent
[UninstallRun]
-; Clean up autostart on uninstall
+Filename: "{cmd}"; Parameters: "/C taskkill /IM AppTrackr.exe /F"; Flags: runhidden; RunOnceId: "StopAppTrackr"
+
[UninstallDelete]
Type: filesandordirs; Name: "{app}"
diff --git a/pyproject.toml b/pyproject.toml
index 47995a3..ff23550 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,30 +1,69 @@
+[build-system]
+requires = ["setuptools>=68.0", "wheel"]
+build-backend = "setuptools.build_meta"
+
[project]
name = "apptrackr"
-version = "1.0.0"
-description = "Desktop app usage time tracker with neon UI and gamification"
+dynamic = ["version"]
+description = "Foreground app usage tracker for Windows with a calendar, per-app limits and an optional rewards game"
+readme = "README.md"
+license = { text = "MIT" }
requires-python = ">=3.10"
+classifiers = [
+ "Programming Language :: Python :: 3",
+ "Operating System :: Microsoft :: Windows",
+ "Environment :: Win32 (MS Windows)",
+ "Intended Audience :: End Users/Desktop",
+ "Topic :: Utilities",
+]
dependencies = [
"PySide6>=6.6",
- "pywin32>=306",
"psutil>=5.9",
- "pynput>=1.7",
+ "pynput>=1.7; sys_platform == 'win32'",
]
[project.optional-dependencies]
dev = [
- "pyinstaller>=6.0",
- "pytest>=7.0",
+ "pytest>=8.0",
+ "ruff>=0.6",
+ "pillow>=10", # scripts/record_demo.py
+ "pyinstaller>=6.0; sys_platform == 'win32'",
]
+[project.urls]
+Homepage = "https://github.com/H4ch1Net/AppTrackr"
+Issues = "https://github.com/H4ch1Net/AppTrackr/issues"
+
[project.scripts]
apptrackr = "apptrackr.__main__:main"
-[build-system]
-requires = ["setuptools>=68.0", "wheel"]
-build-backend = "setuptools.build_meta"
+[tool.setuptools.dynamic]
+version = { attr = "apptrackr.__version__" }
[tool.setuptools.packages.find]
include = ["apptrackr*"]
[tool.setuptools.package-data]
-apptrackr = ["data/schema.sql"]
+apptrackr = [
+ "data/schema.sql",
+ "assets/*.svg",
+ "assets/icons/*",
+ "assets/illustrations/*",
+ "assets/fonts/*",
+]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+addopts = "-q"
+
+[tool.ruff]
+line-length = 120
+target-version = "py310"
+
+[tool.ruff.lint]
+select = ["E", "F", "W", "B", "UP", "I"]
+ignore = ["UP035"] # typing.Callable is fine on 3.10
+
+[tool.ruff.lint.per-file-ignores]
+"tests/*" = ["B011"]
+"apptrackr/ui/theme.py" = ["E501"] # stylesheet text
diff --git a/scripts/make_art.py b/scripts/make_art.py
new file mode 100644
index 0000000..a91759e
--- /dev/null
+++ b/scripts/make_art.py
@@ -0,0 +1,156 @@
+"""Render the README banner (dark and light) and the GitHub social preview.
+
+ python scripts/make_art.py [--out docs]
+
+Drawn with the app's own theme tokens, fonts and chart conventions, so the
+art stays in step with the interface.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+from dataclasses import replace
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+SCALE = 2 # render at 2x for high-density screens
+# Minutes of focus per hour for the sample day; the last entry is the current hour.
+HOURS = [0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 52, 55, 28, 10, 41, 49, 17]
+KICKER = "Foreground time tracker · Windows"
+TAGLINE = "Counts the time each app actually has focus."
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--out", default=str(ROOT / "docs"))
+ args = parser.parse_args()
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ from PySide6.QtCore import QPointF, QRectF, Qt
+ from PySide6.QtGui import QColor, QGuiApplication, QImage, QPainter, QPainterPath, QPen
+ from PySide6.QtSvg import QSvgRenderer
+
+ from apptrackr import paths
+ from apptrackr.ui import fonts, theme
+ from apptrackr.ui.widgets.charts import _column
+
+ _app = QGuiApplication(sys.argv[:1])
+ fonts.load()
+ logo = QSvgRenderer(str(paths.assets_dir() / "logo.svg"))
+
+ def text(p: QPainter, x: float, y: float, s: str, font, color: str, align=Qt.AlignmentFlag.AlignLeft) -> None:
+ """Draw *s* with its baseline at *y*; right-aligned text ends at *x*."""
+ p.setFont(font)
+ p.setPen(QColor(color))
+ if align & Qt.AlignmentFlag.AlignRight:
+ x -= p.fontMetrics().horizontalAdvance(s)
+ p.drawText(QPointF(x, y), s)
+
+ def paper(p: QPainter, t: theme.Theme, w: float, h: float, radius: float) -> None:
+ frame = QPainterPath()
+ frame.addRoundedRect(QRectF(0.5, 0.5, w - 1, h - 1), radius, radius)
+ p.fillPath(frame, QColor(t.window))
+ p.save()
+ p.setClipPath(frame)
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(t.grid))
+ step = 24
+ for gx in range(step, int(w), step):
+ for gy in range(step, int(h), step):
+ p.drawEllipse(QPointF(gx, gy), 0.9, 0.9)
+ p.restore()
+ p.setPen(QPen(QColor(t.border), 1))
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.drawPath(frame)
+
+ def instrument(p: QPainter, t: theme.Theme, r: QRectF, title: str = "Today by hour") -> None:
+ """A cut-out of the dashboard's 'Today by hour' panel."""
+ p.setPen(QPen(QColor(t.border), 1))
+ p.setBrush(QColor(t.surface))
+ p.drawRoundedRect(r.adjusted(0.5, 0.5, -0.5, -0.5), theme.RADIUS_PANEL, theme.RADIUS_PANEL)
+ pad = 20
+ text(p, r.left() + pad, r.top() + 30, f"01 {title.upper()}", fonts.mono(10, 500, 8), t.text_muted)
+ total = sum(HOURS)
+ readout = f"{total // 60}h {total % 60:02d}m"
+ big = fonts.sans(24, 600, tabular=True)
+ text(p, r.right() - pad, r.top() + 36, readout, big, t.text, Qt.AlignmentFlag.AlignRight)
+
+ left, right = r.left() + pad + 30, r.right() - pad
+ top, base = r.top() + 70, r.bottom() - 40
+ peak = 60
+ axis_font = fonts.mono(9, 400, 4)
+ for minutes, name in ((0, "0"), (30, "30M"), (60, "1H")):
+ y = base - (base - top) * minutes / peak
+ p.setPen(QPen(QColor(t.border), 1))
+ p.drawLine(QPointF(left, y), QPointF(right, y))
+ text(p, left - 8, y + 3.5, name, axis_font, t.text_muted, Qt.AlignmentFlag.AlignRight)
+
+ slot = (right - left) / 24
+ bar_w = min(10.0, slot * 0.62)
+ now = len(HOURS) - 1
+ for hour in range(24):
+ x = left + hour * slot + (slot - bar_w) / 2
+ tick = 5 if hour % 6 == 0 else 3
+ p.setPen(QPen(QColor(t.border_strong), 1))
+ p.drawLine(QPointF(left + (hour + 0.5) * slot, base), QPointF(left + (hour + 0.5) * slot, base + tick))
+ if hour % 6 == 0:
+ text(p, left + (hour + 0.5) * slot - 7, base + 18, f"{hour:02d}", axis_font, t.text_muted)
+ minutes = HOURS[hour] if hour < len(HOURS) else 0
+ if not minutes:
+ continue
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(t.accent if hour == now else t.ink))
+ p.drawPath(_column(x, base, bar_w, (base - top) * minutes / peak, 2))
+ # Value label for the current hour, beside its bar where the rest of the day is still empty.
+ x_now = left + now * slot + (slot + bar_w) / 2 + 5
+ y_now = base - (base - top) * HOURS[now] / peak + 9
+ text(p, x_now, y_now, f"{HOURS[now]}m", fonts.sans(11, 600, tabular=True), t.text)
+
+ def identity(p: QPainter, t: theme.Theme, x: float, y: float, title_px: int, tagline_px: int = 15) -> None:
+ """Logo, kicker, wordmark and tagline stacked from (x, y)."""
+ logo.render(p, QRectF(x, y, 56, 56))
+ text(p, x, y + 98, KICKER.upper(), fonts.mono(10, 500, 10), t.accent_text)
+ text(p, x - 2, y + 98 + title_px + 4, "AppTrackr", fonts.sans(title_px, 600), t.text)
+ text(p, x, y + 98 + title_px + 34, TAGLINE, fonts.sans(tagline_px, 400), t.text_dim)
+
+ def render(name: str, t: theme.Theme, w: int, h: int, draw) -> None:
+ image = QImage(w * SCALE, h * SCALE, QImage.Format.Format_ARGB32_Premultiplied)
+ image.setDevicePixelRatio(SCALE)
+ image.fill(Qt.GlobalColor.transparent)
+ p = QPainter(image)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ p.setRenderHint(QPainter.RenderHint.TextAntialiasing)
+ draw(p, t, w, h)
+ p.end()
+ out = Path(args.out) / name
+ out.parent.mkdir(parents=True, exist_ok=True)
+ image.save(str(out))
+ print(f"wrote {out}")
+
+ def banner(p, t, w, h):
+ paper(p, t, w, h, 10)
+ identity(p, t, 48, 44, 46)
+ instrument(p, t, QRectF(w - 48 - 360, 40, 360, h - 80))
+
+ def social(p, t, w, h):
+ # Some surfaces crop the preview toward its center, so everything keeps a 40px margin.
+ paper(p, t, w, h, 0)
+ identity(p, t, 40, 52, 40, 13)
+ 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)
+ render("banner-dark.png", dark, 880, 280, banner)
+ render("banner-light.png", light, 880, 280, banner)
+ render("social-preview.png", dark, 640, 320, social)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/make_icon.py b/scripts/make_icon.py
new file mode 100644
index 0000000..b519d99
--- /dev/null
+++ b/scripts/make_icon.py
@@ -0,0 +1,64 @@
+"""Build packaging/apptrackr.ico from apptrackr/assets/logo.svg (logo-small.svg up to 32 px).
+
+ python scripts/make_icon.py
+
+The .ico holds PNG-compressed frames from 16 to 256 px (supported since Windows Vista).
+"""
+
+from __future__ import annotations
+
+import os
+import struct
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+SIZES = (16, 20, 24, 32, 40, 48, 64, 128, 256)
+SMALL = 32
+
+
+def render_png(svg: bytes, size: int) -> bytes:
+ from PySide6.QtCore import QBuffer, QByteArray, QIODevice, Qt
+ from PySide6.QtGui import QImage, QPainter
+ from PySide6.QtSvg import QSvgRenderer
+
+ image = QImage(size, size, QImage.Format.Format_ARGB32)
+ image.fill(Qt.GlobalColor.transparent)
+ painter = QPainter(image)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ QSvgRenderer(QByteArray(svg)).render(painter)
+ painter.end()
+ data = QByteArray()
+ buf = QBuffer(data)
+ buf.open(QIODevice.OpenModeFlag.WriteOnly)
+ image.save(buf, "PNG")
+ return bytes(data)
+
+
+def build_ico(frames: list[tuple[int, bytes]]) -> bytes:
+ header = struct.pack("= 256 else size
+ entries += struct.pack(" int:
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ from PySide6.QtGui import QGuiApplication
+
+ _app = QGuiApplication(sys.argv[:1])
+ assets = ROOT / "apptrackr" / "assets"
+ full, small = (assets / "logo.svg").read_bytes(), (assets / "logo-small.svg").read_bytes()
+ out = ROOT / "packaging" / "apptrackr.ico"
+ out.write_bytes(build_ico([(s, render_png(small if s <= SMALL else full, s)) for s in SIZES]))
+ print(f"wrote {out}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/record_demo.py b/scripts/record_demo.py
new file mode 100644
index 0000000..615bb66
--- /dev/null
+++ b/scripts/record_demo.py
@@ -0,0 +1,175 @@
+"""Record a short animated GIF of AppTrackr's UI in motion, from demo data.
+
+ pip install pillow
+ python scripts/record_demo.py [--out docs/screenshots/demo.gif] [--frames-dir DIR]
+
+Runs offscreen against a temporary database. Frames are grabbed in real time
+while a scripted tour drives the window, then written as an optimized GIF.
+"""
+
+from __future__ import annotations
+
+import argparse
+import io
+import os
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / "scripts"))
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--out", default=str(ROOT / "docs" / "screenshots" / "demo.gif"))
+ parser.add_argument("--frames-dir", help="also save every frame as PNG here (for inspection)")
+ 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(
+ "--slowdown", type=float, default=4.0, help="run animations this many times slower while capturing"
+ )
+ args = parser.parse_args()
+
+ try:
+ from PIL import Image
+ except ImportError:
+ print("Pillow is required: pip install pillow")
+ return 1
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ from screenshots import shift_clock_to_afternoon
+
+ shift_clock_to_afternoon()
+
+ from apptrackr import paths
+
+ paths.set_data_dir(Path(tempfile.mkdtemp(prefix="apptrackr-demo-gif-")))
+
+ from PySide6.QtCore import QBuffer, QByteArray, QElapsedTimer, QEventLoop, QIODevice, QTimer
+ from PySide6.QtWidgets import QApplication
+
+ from apptrackr.core.platform import DemoPlatform
+ from apptrackr.core.tracker import Tracker
+ from apptrackr.data import db, demo, queries
+ from apptrackr.ui import motion
+ from apptrackr.ui.main import MainWindow, prepare_app
+
+ db.init_db()
+ demo.seed()
+ motion.force(True)
+ motion.time_scale = args.slowdown
+ app = QApplication(sys.argv[:1])
+ prepare_app(app)
+
+ tracker = Tracker(DemoPlatform())
+ tracker.reload_settings()
+ tracker.tick()
+ backdate = 47 * 60 + 12
+ tracker._session_start -= backdate
+ tracker._committed_until -= backdate
+ db.execute(
+ "UPDATE usage_sessions SET start_ts = ? WHERE session_id = ?", (tracker._session_start, tracker._session_id)
+ )
+ tracker._checkpoint(time.time())
+
+ window = MainWindow(tracker, None, demo=True)
+ window.setWindowTitle("AppTrackr")
+ window.resize(args.width, args.height)
+ window.show_page("calendar") # start elsewhere so the dashboard entrance is visible
+ window.show()
+
+ frames: list[tuple[int, Image.Image]] = []
+ clock = QElapsedTimer()
+ clock.start()
+ interval = int(1000 / args.fps * args.slowdown)
+
+ def capture() -> None:
+ pixmap = window.grab()
+ data = QByteArray()
+ buf = QBuffer(data)
+ buf.open(QIODevice.OpenModeFlag.WriteOnly)
+ pixmap.toImage().save(buf, "PNG")
+ image = Image.open(io.BytesIO(bytes(data))).convert("RGB")
+ if args.scale != 1:
+ image = image.resize((int(image.width * args.scale), int(image.height * args.scale)), Image.LANCZOS)
+ frames.append((clock.elapsed(), image))
+
+ def wait(ms: int) -> None:
+ """Wait *ms* of playback time (scaled by the slowdown while capturing)."""
+ loop = QEventLoop()
+ QTimer.singleShot(int(ms * args.slowdown), loop.quit)
+ loop.exec()
+
+ timer = QTimer()
+ timer.timeout.connect(capture)
+
+ wait(150)
+ timer.start(interval)
+
+ # Tour ------------------------------------------------------------------
+ window.show_page("dashboard")
+ wait(1700)
+ window.show_page("calendar")
+ wait(900)
+ cal = window._views["calendar"]
+ from datetime import date, timedelta
+
+ target = date.today() - timedelta(days=1)
+ cal.heatmap.set_selected(target)
+ cal._on_day(target.isoformat())
+ wait(900)
+ cal._shift(-1)
+ wait(1100)
+ window.show_page("apps")
+ wait(800)
+ window._views["apps"].sort._group.button(2).click()
+ wait(1000)
+ window.open_app(queries.find_app_id("code.exe"))
+ wait(1200)
+ window.show_page("rewards")
+ wait(700)
+ window._views["rewards"]._claim_all()
+ wait(1500)
+ window.show_page("dashboard")
+ wait(700)
+ db.set_setting("ui_mode", "light")
+ window.apply_theme()
+ wait(1300)
+
+ timer.stop()
+ tracker.stop()
+
+ if args.frames_dir:
+ out_dir = Path(args.frames_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ for i, (_t, image) in enumerate(frames):
+ image.save(out_dir / f"frame_{i:03d}.png")
+
+ # Merge frames that barely differ (idle moments where only the timer ticks) to keep the GIF small.
+ from PIL import ImageChops, ImageStat
+
+ times = [t for t, _ in frames] + [frames[-1][0] + 1500 * args.slowdown]
+ kept: list[tuple[Image.Image, int]] = []
+ for i, (_t, image) in enumerate(frames):
+ duration = int((times[i + 1] - times[i]) / args.slowdown)
+ if kept and sum(ImageStat.Stat(ImageChops.difference(kept[-1][0], image)).mean) < 0.6:
+ 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]
+ durations = [max(20, d) for _, d in kept]
+ out = Path(args.out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ images[0].save(out, save_all=True, append_images=images[1:], duration=durations, loop=0, optimize=True, disposal=1)
+ print(f"wrote {out} ({len(images)} frames, {out.stat().st_size / 1e6:.1f} MB)")
+ window.quit()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/screenshots.py b/scripts/screenshots.py
new file mode 100644
index 0000000..7b5c6db
--- /dev/null
+++ b/scripts/screenshots.py
@@ -0,0 +1,116 @@
+"""Render README screenshots from demo data.
+
+ python scripts/screenshots.py [--out docs/screenshots] [--width 1280 --height 800]
+
+Runs offscreen (no window appears) with a temporary database, so it never
+touches your real data. The demo clock is shifted to mid-afternoon so the
+"today" charts have content whatever time you run it.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+import tempfile
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+
+def shift_clock_to_afternoon(hour: int = 16) -> None:
+ """Pick a fixed UTC offset so local time is about *hour*:30 (POSIX only)."""
+ if not hasattr(time, "tzset"):
+ return
+ now = datetime.now(timezone.utc)
+ offset = (round(hour + 0.5 - now.hour - now.minute / 60) + 12) % 24 - 12
+ os.environ["TZ"] = f"DEMO{-offset}" # POSIX TZ offsets are west-positive
+ time.tzset()
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--out", default=str(ROOT / "docs" / "screenshots"))
+ parser.add_argument("--width", type=int, default=1280)
+ parser.add_argument("--height", type=int, default=800)
+ parser.add_argument("--show", action="store_true", help="use the real display instead of offscreen")
+ args = parser.parse_args()
+
+ if not args.show:
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ shift_clock_to_afternoon()
+
+ from apptrackr import paths
+
+ paths.set_data_dir(Path(tempfile.mkdtemp(prefix="apptrackr-shots-")))
+
+ from PySide6.QtCore import QEventLoop, QTimer
+ from PySide6.QtWidgets import QApplication
+
+ from apptrackr.core.platform import DemoPlatform
+ from apptrackr.core.tracker import Tracker
+ from apptrackr.data import db, demo, queries
+ from apptrackr.ui import motion
+ from apptrackr.ui.main import MainWindow, prepare_app
+
+ db.init_db()
+ demo.seed()
+ motion.force(False) # capture final states, not mid-transition frames
+ app = QApplication(sys.argv[:1])
+ prepare_app(app)
+
+ tracker = Tracker(DemoPlatform())
+ tracker.reload_settings()
+ tracker.tick()
+ # Backdate the live session so the "Now" card shows a believable timer.
+ backdate = 47 * 60 + 12
+ tracker._session_start -= backdate
+ tracker._committed_until -= backdate
+ db.execute(
+ "UPDATE usage_sessions SET start_ts = ? WHERE session_id = ?", (tracker._session_start, tracker._session_id)
+ )
+ tracker._checkpoint(time.time())
+
+ window = MainWindow(tracker, None, demo=True)
+ window.setWindowTitle("AppTrackr")
+ window.resize(args.width, args.height)
+ window.show()
+
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+
+ def settle(ms: int = 250) -> None:
+ loop = QEventLoop()
+ QTimer.singleShot(ms, loop.quit)
+ loop.exec()
+
+ def shot(name: str) -> None:
+ window._tick()
+ settle()
+ window.toast.hide()
+ window.grab().save(str(out / f"{name}.png"))
+ print(f"wrote {out / name}.png")
+
+ for page in ("dashboard", "calendar", "apps", "rewards", "village", "settings"):
+ window.show_page(page)
+ shot(page)
+
+ window.show_page("apps")
+ window.open_app(queries.find_app_id("code.exe"))
+ shot("app-detail")
+
+ db.set_setting("ui_mode", "light")
+ window.apply_theme()
+ window.show_page("dashboard")
+ shot("dashboard-light")
+
+ tracker.stop()
+ window.quit()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..77accf9
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,29 @@
+import os
+import tempfile
+
+import pytest
+
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+# Never let a test fall back to the real per-user data folder.
+os.environ["APPTRACKR_DATA_DIR"] = tempfile.mkdtemp(prefix="apptrackr-tests-")
+
+from apptrackr import paths # noqa: E402
+from apptrackr.data import db # noqa: E402
+
+
+@pytest.fixture(autouse=True)
+def temp_db(tmp_path):
+ """Every test gets an empty, migrated database in a temp directory."""
+ paths.set_data_dir(tmp_path)
+ db.configure(tmp_path / "data.sqlite")
+ db.init_db()
+ from apptrackr.ui import motion
+
+ motion.force(None)
+ motion._cached = None
+ yield tmp_path / "data.sqlite"
+ motion.force(None)
+ motion._cached = None
+ db.close()
+ db.configure(None)
+ paths.set_data_dir(None)
diff --git a/tests/test_data.py b/tests/test_data.py
new file mode 100644
index 0000000..1a7190c
--- /dev/null
+++ b/tests/test_data.py
@@ -0,0 +1,179 @@
+import json
+import sqlite3
+
+import pytest
+
+from apptrackr.core.limits import LimitMonitor
+from apptrackr.core.process_watch import ProcessWatcher
+from apptrackr.data import catalog, db, demo, export, queries
+
+
+def test_friendly_names():
+ assert catalog.friendly_name("Code.exe") == "VS Code"
+ assert catalog.friendly_name("my_cool-tool.exe") == "My Cool Tool"
+ assert catalog.friendly_name("C:/Apps/obs64.exe") == "OBS Studio"
+ assert catalog.display_name({"exe_name": "foo.exe", "display_name": "foo.exe"}) == "Foo"
+ assert catalog.display_name({"exe_name": "foo.exe", "display_name": "Bar"}) == "Bar"
+
+
+def test_noise_filters():
+ assert not catalog.is_trackable("explorer.exe")
+ assert not catalog.is_trackable("GoogleCrashHandler.exe")
+ assert catalog.is_trackable("steamwebhelper.exe") # aliased to steam.exe
+ assert catalog.is_trackable("code.exe")
+
+
+def test_top_apps_filters_and_sorts():
+ demo.seed(days=14)
+ today = queries.today_str()
+ start = queries.days_ago(13)
+ apps = queries.top_apps(start, today, limit=None)
+ assert apps == sorted(apps, key=lambda a: -a["focused_ms"])
+ assert all(a["exe_name"] not in demo.HIDDEN for a in apps)
+ dev = queries.top_apps(start, today, category="Development", limit=None)
+ assert dev and all(a["category"] == "Development" for a in dev)
+ favs = queries.top_apps(start, today, favorites_only=True, limit=None)
+ assert {a["exe_name"] for a in favs} <= {"code.exe", "obsidian.exe"}
+ found = queries.top_apps(start, today, search="chrome", limit=None)
+ assert [a["exe_name"] for a in found] == ["chrome.exe"]
+ assert queries.total_ms(start, today) == sum(queries.daily_totals(start, today).values())
+
+
+def test_history_is_zero_filled():
+ app_id = queries.get_or_create_app("code.exe")
+ history = queries.app_daily_history(app_id, days=7)
+ assert len(history) == 7
+ assert history[-1]["day"] == queries.today_str()
+
+
+def test_launch_counting_counts_transitions_once():
+ watcher = ProcessWatcher()
+ app_id = queries.get_or_create_app("chrome.exe")
+ watcher.check({"svchost.exe"}, now=0)
+ watcher.check({"svchost.exe", "chrome.exe"}, now=5)
+ watcher.check({"svchost.exe", "chrome.exe"}, now=10)
+ watcher.check({"svchost.exe"}, now=15)
+ watcher.check({"svchost.exe", "chrome.exe"}, now=20)
+ row = db.fetchone("SELECT opens_count FROM daily_rollup WHERE app_id = ?", (app_id,))
+ assert row["opens_count"] == 2
+ assert queries.find_app_id("svchost.exe") is None
+
+
+def test_launch_of_new_app_waits_for_first_focus():
+ watcher = ProcessWatcher()
+ watcher.check(set(), now=0)
+ watcher.check({"figma.exe"}, now=5)
+ assert queries.find_app_id("figma.exe") is None
+ app_id = queries.get_or_create_app("figma.exe") # tracker saw it in focus
+ watcher.check({"figma.exe"}, now=10)
+ row = db.fetchone("SELECT opens_count FROM daily_rollup WHERE app_id = ?", (app_id,))
+ assert row["opens_count"] == 1
+
+
+def test_limit_monitor_reports_once():
+ app_id = queries.get_or_create_app("discord.exe")
+ queries.set_daily_limit(app_id, 60_000)
+ monitor = LimitMonitor()
+ assert monitor.check() == []
+ assert [a["app_id"] for a in monitor.check(live_app_id=app_id, live_ms=61_000)] == [app_id]
+ assert monitor.check(live_app_id=app_id, live_ms=120_000) == []
+
+
+def test_export_formats(tmp_path):
+ demo.seed(days=3)
+ n = export.export_csv(tmp_path / "out.csv")
+ lines = (tmp_path / "out.csv").read_text(encoding="utf-8").splitlines()
+ assert lines[0].startswith("day,exe_name,app")
+ assert len(lines) == n + 1
+ assert export.export_json(tmp_path / "out.json") == n
+ assert len(json.loads((tmp_path / "out.json").read_text())) == n
+
+
+def test_backup_and_restore_roundtrip(tmp_path):
+ queries.get_or_create_app("code.exe")
+ export.backup_db(tmp_path / "backup.sqlite")
+ queries.get_or_create_app("chrome.exe")
+ export.restore_db(tmp_path / "backup.sqlite")
+ assert queries.find_app_id("code.exe") is not None
+ assert queries.find_app_id("chrome.exe") is None
+
+
+def test_restore_from_path_with_special_characters(tmp_path):
+ folder = tmp_path / "Backups #2 100%"
+ folder.mkdir()
+ queries.get_or_create_app("code.exe")
+ export.backup_db(folder / "backup.sqlite")
+ export.restore_db(folder / "backup.sqlite")
+ assert queries.find_app_id("code.exe") is not None
+ assert sorted(p.name for p in tmp_path.iterdir()) == [
+ "Backups #2 100%",
+ "data.sqlite",
+ "data.sqlite-shm",
+ "data.sqlite-wal",
+ ]
+
+
+def test_restore_rejects_foreign_files(tmp_path):
+ bogus = tmp_path / "bogus.sqlite"
+ bogus.write_text("not a database")
+ with pytest.raises(export.RestoreError):
+ export.restore_db(bogus)
+ other = tmp_path / "other.sqlite"
+ sqlite3.connect(other).execute("CREATE TABLE t (x)").connection.close()
+ with pytest.raises(export.RestoreError):
+ export.restore_db(other)
+
+
+def test_v1_migration_recovers_idle_sessions(tmp_path):
+ legacy = tmp_path / "legacy.sqlite"
+ conn = sqlite3.connect(legacy)
+ conn.executescript("""
+ 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);
+ CREATE TABLE usage_sessions (session_id INTEGER PRIMARY KEY AUTOINCREMENT, app_id INTEGER NOT NULL,
+ start_ts REAL NOT NULL, end_ts REAL, duration_ms INTEGER, was_idle INTEGER NOT NULL DEFAULT 0);
+ CREATE TABLE daily_rollup (day TEXT NOT NULL, app_id INTEGER NOT NULL, 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));
+ CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ INSERT INTO settings VALUES ('idle_threshold_sec', '300');
+ INSERT INTO apps (exe_name) VALUES ('code.exe');
+ """)
+ from datetime import datetime
+
+ start = datetime(2026, 2, 1, 10, 0).timestamp()
+ # A 40 minute session that ended in idle (35 real minutes) was never counted by v1.0.
+ conn.execute(
+ "INSERT INTO usage_sessions (app_id, start_ts, end_ts, duration_ms, was_idle) VALUES (1, ?, ?, ?, 1)",
+ (start, start + 2400, 2_400_000),
+ )
+ conn.execute(
+ "INSERT INTO usage_sessions (app_id, start_ts, end_ts, duration_ms, was_idle) VALUES (1, ?, ?, ?, 0)",
+ (start + 3600, start + 4200, 600_000),
+ )
+ conn.execute("INSERT INTO daily_rollup (day, app_id, focused_ms, opens_count) VALUES ('2026-02-01', 1, 600000, 7)")
+ conn.commit()
+ conn.close()
+
+ # v1.0 also stored helper processes under their own names.
+ conn = sqlite3.connect(legacy)
+ conn.execute("INSERT INTO apps (exe_name) VALUES ('steam.exe'), ('steamwebhelper.exe')")
+ conn.execute(
+ "INSERT INTO usage_sessions (app_id, start_ts, end_ts, duration_ms) VALUES (3, ?, ?, 60000)",
+ (start, start + 60),
+ )
+ conn.execute("INSERT INTO daily_rollup (day, app_id, focused_ms, opens_count) VALUES ('2026-02-01', 3, 60000, 2)")
+ conn.execute("INSERT INTO daily_rollup (day, app_id, focused_ms, opens_count) VALUES ('2026-02-01', 2, 0, 1)")
+ conn.commit()
+ conn.close()
+
+ db.configure(legacy)
+ db.init_db()
+ row = db.fetchone("SELECT focused_ms, opens_count FROM daily_rollup WHERE day = '2026-02-01' AND app_id = 1")
+ assert row["focused_ms"] == 2_100_000 + 600_000
+ assert row["opens_count"] == 7
+ assert queries.find_app_id("steamwebhelper.exe") == queries.find_app_id("steam.exe") == 2
+ steam = db.fetchone("SELECT focused_ms, opens_count FROM daily_rollup WHERE app_id = 2")
+ assert (steam["focused_ms"], steam["opens_count"]) == (60_000, 3)
+ assert db.fetchone("SELECT COUNT(*) AS n FROM apps WHERE exe_name LIKE 'steam%'")["n"] == 1
+ assert db.fetchone("PRAGMA user_version")[0] == db.SCHEMA_VERSION
+ assert "is_hidden" in {r["name"] for r in db.fetchall("PRAGMA table_info(apps)")}
diff --git a/tests/test_motion.py b/tests/test_motion.py
new file mode 100644
index 0000000..ca0916f
--- /dev/null
+++ b/tests/test_motion.py
@@ -0,0 +1,131 @@
+"""Motion system: helpers finish cleanly, respect reduced motion and leave no effects behind."""
+
+import pytest
+
+pytest.importorskip("PySide6.QtWidgets")
+
+from PySide6.QtCore import QEventLoop, QTimer # noqa: E402
+from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget # noqa: E402
+
+from apptrackr.data import db, demo, queries # noqa: E402
+from apptrackr.ui import motion # noqa: E402
+
+
+@pytest.fixture
+def qapp():
+ from apptrackr.ui.main import prepare_app
+
+ app = QApplication.instance() or QApplication([])
+ prepare_app(app)
+ return app
+
+
+def settle(ms=700):
+ loop = QEventLoop()
+ QTimer.singleShot(ms, loop.quit)
+ loop.exec()
+
+
+def test_setting_overrides_system_preference(qapp):
+ assert motion.enabled() == motion.system_allows_animation()
+ motion.set_enabled(False)
+ assert db.get_setting("animations") == "0" and not motion.enabled()
+ motion.set_enabled(True)
+ assert motion.enabled()
+ motion.set_enabled(None)
+ assert motion.enabled() == motion.system_allows_animation()
+
+
+def test_reduced_motion_applies_end_state_immediately(qapp):
+ motion.force(False)
+ seen, done = [], []
+ w = QWidget()
+ motion.tween(w, 0.0, 1.0, motion.SLOW, seen.append, on_done=lambda: done.append(True))
+ assert seen == [1.0] and done == [True]
+ motion.fade(w, 0.0, 1.0)
+ assert w.graphicsEffect() is None
+
+
+def test_tween_runs_to_completion_and_retargets(qapp):
+ motion.force(True)
+ w = QWidget()
+ seen = []
+ motion.tween(w, 0.0, 10.0, motion.FAST, seen.append, key="x")
+ assert seen[0] == 0.0 # first frame applied immediately
+ motion.tween(w, seen[-1], 20.0, motion.FAST, seen.append, key="x")
+ settle(400)
+ assert seen[-1] == pytest.approx(20.0)
+ assert motion.running(w, "x") is None
+
+
+def test_fade_and_collapse_clean_up(qapp):
+ motion.force(True)
+ host = QWidget()
+ lay = QVBoxLayout(host)
+ row = QLabel("row")
+ lay.addWidget(row)
+ host.show()
+ motion.fade(row, 0.0, 1.0)
+ assert row.graphicsEffect() is not None
+ settle()
+ assert row.graphicsEffect() is None
+ removed = []
+ motion.collapse(row, lambda: removed.append(True))
+ settle()
+ assert removed == [True] and row.maximumHeight() == 0
+
+
+def test_stat_tile_counts_to_value(qapp):
+ from apptrackr.ui.widgets.components import StatTile
+
+ motion.force(True)
+ tile = StatTile("Today", "clock")
+ tile.show()
+ tile.set_number(120, lambda v: str(int(round(v))))
+ assert tile.value.text() != "120" # counting up from zero
+ settle()
+ assert tile.value.text() == "120"
+ tile.set_number(121, lambda v: str(int(round(v)))) # small change: no animation
+ assert tile.value.text() == "121"
+
+
+def test_window_animations_settle(qapp):
+ from apptrackr.core.platform import DemoPlatform
+ from apptrackr.core.tracker import Tracker
+ from apptrackr.ui.main import MainWindow
+
+ motion.force(True)
+ demo.seed(days=20)
+ tracker = Tracker(DemoPlatform())
+ tracker.reload_settings()
+ tracker.tick()
+ win = MainWindow(tracker, None, demo=True)
+ win.resize(1200, 780)
+ win.show()
+ for page in ("calendar", "apps", "rewards", "village", "dashboard"):
+ win.show_page(page)
+ settle(120) # switch again before animations finish
+ win._views["apps"].sort._group.button(2).click()
+ win.open_app(queries.find_app_id("code.exe"))
+ db.set_setting("ui_mode", "light")
+ win.apply_theme()
+ win.show_page("rewards")
+ win._views["rewards"]._claim_all()
+ settle(1500)
+
+ from apptrackr.rewards import engine
+
+ assert engine.unclaimed_count() == 0
+ for view in win._views.values():
+ assert view.graphicsEffect() is None
+ sort = win._views["apps"].sort
+ assert sort._thumb.geometry() == sort._group.checkedButton().geometry()
+ checked = win._nav_buttons["rewards"]
+ assert abs(win._indicator.geometry().center().y() - checked.geometry().center().y()) <= 1
+ overlays = [
+ c for c in win.centralWidget().children() if isinstance(c, QLabel) and c.pixmap() and not c.pixmap().isNull()
+ ]
+ assert overlays == [] # theme crossfade overlay removed
+ tracker.stop()
+ win._quitting = True
+ win.close()
diff --git a/tests/test_rewards.py b/tests/test_rewards.py
new file mode 100644
index 0000000..91b2907
--- /dev/null
+++ b/tests/test_rewards.py
@@ -0,0 +1,107 @@
+from apptrackr.data import db, queries
+from apptrackr.game import economy, state
+from apptrackr.rewards import engine, rules
+
+
+def _use(app_id, minutes):
+ db.execute(
+ "INSERT INTO daily_rollup (day, app_id, focused_ms) VALUES (?, ?, ?) "
+ "ON CONFLICT(day, app_id) DO UPDATE SET focused_ms = excluded.focused_ms",
+ (queries.today_str(), app_id, minutes * 60_000),
+ )
+ db.commit()
+
+
+def test_rules_are_created_disabled_and_can_be_enabled():
+ app_id = queries.get_or_create_app("code.exe")
+ rules.ensure_app_rules(app_id)
+ assert not rules.app_rewards_enabled(app_id)
+ rules.enable_app_rewards(app_id)
+ assert rules.app_rewards_enabled(app_id)
+ assert rules.earning_app_ids() == {app_id}
+
+
+def test_repeatable_milestones_grant_once_per_crossing():
+ app_id = queries.get_or_create_app("code.exe")
+ rules.enable_app_rewards(app_id)
+ _use(app_id, 65)
+ first = engine.evaluate()
+ assert len(first) == 3 # 2x 30m + 1x 60m
+ assert engine.evaluate() == []
+ _use(app_id, 95)
+ assert len(engine.evaluate()) == 1
+
+
+def test_disabled_rewards_grant_nothing():
+ app_id = queries.get_or_create_app("code.exe")
+ rules.enable_app_rewards(app_id)
+ _use(app_id, 65)
+ db.set_setting("rewards_enabled", False)
+ assert engine.evaluate() == []
+
+
+def test_claim_applies_bonuses_caps_and_levels():
+ app_id = queries.get_or_create_app("code.exe")
+ rules.enable_app_rewards(app_id)
+ village = state.get_village()
+ village["buildings"]["workshop"] = {"level": 2} # +10% xp
+ village["inventory"]["wood"] = economy.BASE_RESOURCE_CAP - 2
+ state.save_village(village)
+ db.execute("UPDATE player_profile SET xp = 95 WHERE profile_id = 1")
+ db.commit()
+ _use(app_id, 30)
+ engine.evaluate()
+ applied = engine.claim_many()
+ assert applied["xp"] == 11
+ assert applied["wood"] == 2 # capped
+ assert applied["level_up"] == 2
+ assert applied["credits"] == economy.CREDITS_PER_LEVEL * 2
+ profile = engine.get_profile()
+ assert profile["level"] == 2 and profile["xp"] == 106
+ assert engine.unclaimed_count() == 0
+
+
+def test_streak_grows_once_per_day_and_pays_tiers():
+ from datetime import date, timedelta
+
+ app_id = queries.get_or_create_app("code.exe")
+ queries.set_favorite(app_id, True)
+ yesterday = (date.today() - timedelta(days=1)).isoformat()
+ db.execute("UPDATE player_profile SET streak_days = 2, last_streak_day = ? WHERE profile_id = 1", (yesterday,))
+ db.commit()
+ assert engine.update_streak() is None # goal not met yet
+ result = engine.update_streak(extra_ms=economy.STREAK_GOAL_MS)
+ assert result["streak"] == 3
+ assert result["reward"]["xp"] == economy.STREAK_REWARDS[3]["xp"]
+ assert engine.update_streak(extra_ms=economy.STREAK_GOAL_MS) is None
+
+
+def test_broken_streak_reads_as_zero():
+ db.execute("UPDATE player_profile SET streak_days = 5, last_streak_day = '2000-01-01' WHERE profile_id = 1")
+ assert engine.get_profile()["streak"] == 0
+
+
+def test_building_and_market():
+ ok, reason = state.can_build("workshop")
+ assert not ok and reason.startswith("Need")
+ village = state.get_village()
+ village["inventory"].update({"wood": 20, "stone": 10})
+ state.save_village(village)
+ assert state.build_or_upgrade("workshop") == (True, "Workshop built")
+ assert state.build_cost("workshop", 1) == {"wood": 40, "stone": 20}
+ assert state.can_build("lab")[1] == "Unlocks at level 3"
+
+ assert not state.buy("wood")[0]
+ db.execute("UPDATE player_profile SET credits = 20 WHERE profile_id = 1")
+ assert state.buy("wood") == (True, "Bought 10 wood")
+ assert state.get_village()["inventory"]["wood"] == 10
+ assert engine.get_profile()["credits"] == 15
+
+
+def test_next_milestone_sums_coinciding_rewards():
+ app_id = queries.get_or_create_app("code.exe")
+ rules.enable_app_rewards(app_id)
+ _use(app_id, 95)
+ (item,) = engine.next_milestones()
+ assert item["next"]["target_ms"] == 120 * 60_000
+ assert item["next"]["reward"]["xp"] == 10 + 25 + 60
diff --git a/tests/test_tracker.py b/tests/test_tracker.py
new file mode 100644
index 0000000..9d241fc
--- /dev/null
+++ b/tests/test_tracker.py
@@ -0,0 +1,214 @@
+from datetime import datetime, timedelta
+
+from apptrackr.core.platform import ForegroundApp
+from apptrackr.core.tracker import (
+ STATUS_IDLE,
+ STATUS_LOCKED,
+ STATUS_PAUSED,
+ STATUS_TRACKING,
+ Tracker,
+)
+from apptrackr.data import db, queries
+
+
+class FakePlatform:
+ supported = True
+
+ def __init__(self):
+ self.exe = None
+ self.idle = 0.0
+ self.locked = False
+
+ def foreground_app(self):
+ return ForegroundApp(1, self.exe, None) if self.exe else None
+
+ def idle_seconds(self):
+ return self.idle
+
+ def is_locked(self):
+ return self.locked
+
+
+class Clock:
+ def __init__(self, start):
+ self.t = start
+
+ def __call__(self):
+ return self.t
+
+
+def make(start=None):
+ start = start or datetime(2026, 3, 10, 12, 0).timestamp()
+ platform, clock = FakePlatform(), Clock(start)
+ tracker = Tracker(platform, clock=clock)
+ tracker.reload_settings()
+ return tracker, platform, clock
+
+
+def run(tracker, platform, clock, seconds, step=5, idle=False):
+ """Advance time in small steps, sampling like the real loop does."""
+ for _ in range(int(seconds // step)):
+ clock.t += step
+ platform.idle = platform.idle + step if idle else 0.0
+ tracker.tick()
+
+
+def focused(exe, day="2026-03-10"):
+ app_id = queries.find_app_id(exe)
+ return queries.app_usage_on(day, app_id) if app_id else 0
+
+
+def test_switching_apps_records_time():
+ tracker, platform, clock = make()
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 120)
+ platform.exe = "chrome.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 60)
+ tracker.stop()
+ assert focused("code.exe") == 120_000
+ assert focused("chrome.exe") == 60_000
+
+
+def test_checkpoints_make_totals_live():
+ tracker, platform, clock = make()
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 35)
+ assert focused("code.exe") == 30_000 # committed at the 30 s checkpoint
+ assert tracker.snapshot().uncommitted_ms == 5_000
+ assert tracker.snapshot().status == STATUS_TRACKING
+
+
+def test_idle_session_is_counted_up_to_last_input():
+ tracker, platform, clock = make()
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 600)
+ run(tracker, platform, clock, 330, idle=True)
+ assert tracker.snapshot().status == STATUS_IDLE
+ assert focused("code.exe") == 600_000
+
+
+def test_lock_stops_tracking():
+ tracker, platform, clock = make()
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 45)
+ platform.locked = True
+ tracker.tick()
+ assert tracker.snapshot().status == STATUS_LOCKED
+ run(tracker, platform, clock, 600)
+ assert focused("code.exe") == 45_000
+
+
+def test_sleep_gap_is_not_counted():
+ tracker, platform, clock = make()
+ db.set_setting("idle_threshold_sec", 0) # even with idle detection off
+ tracker.reload_settings()
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 60)
+ clock.t += 8 * 3600 # lid closed overnight
+ tracker.tick()
+ run(tracker, platform, clock, 30)
+ tracker.stop()
+ assert focused("code.exe") == 90_000
+
+
+def test_focus_stolen_while_away_ends_at_last_input():
+ tracker, platform, clock = make()
+ db.set_setting("idle_threshold_sec", 600)
+ tracker.reload_settings()
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 120)
+ run(tracker, platform, clock, 240, idle=True) # away, below the idle timeout
+ platform.exe = "teams.exe" # a popup takes focus, no input
+ tracker.tick()
+ tracker.stop()
+ assert focused("code.exe") == 120_000
+
+
+def test_midnight_split():
+ start = datetime(2026, 3, 10, 23, 59).timestamp()
+ tracker, platform, clock = make(start)
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 180)
+ tracker.stop()
+ assert focused("code.exe", "2026-03-10") == 60_000
+ assert focused("code.exe", "2026-03-11") == 120_000
+
+
+def test_system_and_excluded_apps_are_ignored():
+ tracker, platform, clock = make()
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 30)
+ platform.exe = "explorer.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 300)
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 30)
+ tracker.stop()
+ assert focused("code.exe") == 60_000
+ assert queries.find_app_id("explorer.exe") is None
+
+ queries.set_hidden(queries.find_app_id("code.exe"), True)
+ tracker.reload_settings()
+ tracker.tick()
+ run(tracker, platform, clock, 100)
+ tracker.stop()
+ assert focused("code.exe") == 60_000
+
+
+def test_timed_pause_resumes():
+ tracker, platform, clock = make()
+ platform.exe = "code.exe"
+ tracker.pause(minutes=15)
+ tracker.tick()
+ assert tracker.snapshot().status == STATUS_PAUSED
+ run(tracker, platform, clock, 15 * 60)
+ assert not tracker.paused
+ assert tracker.snapshot().app_id is not None
+
+
+def test_helper_alias_folds_into_app():
+ tracker, platform, clock = make()
+ platform.exe = "steamwebhelper.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 10)
+ tracker.stop()
+ assert focused("steam.exe") == 10_000
+
+
+def test_session_rows_have_durations():
+ tracker, platform, clock = make()
+ platform.exe = "code.exe"
+ tracker.tick()
+ run(tracker, platform, clock, 90)
+ tracker.stop()
+ rows = db.fetchall("SELECT duration_ms FROM usage_sessions")
+ assert [r["duration_ms"] for r in rows] == [90_000]
+ hours = queries.hourly_totals("2026-03-10")
+ assert hours[12] == 90_000 and sum(hours) == 90_000
+
+
+def test_current_app_id_is_lock_free():
+ tracker, platform, clock = make()
+ platform.exe = "code.exe"
+ tracker.tick()
+ with tracker._lock: # held by another thread in practice
+ assert tracker.current_app_id == queries.find_app_id("code.exe")
+
+
+def test_split_by_day_spans_multiple_days():
+ from apptrackr.data.spans import split_by_day
+
+ start = datetime(2026, 1, 1, 22, 0)
+ parts = split_by_day(start.timestamp(), (start + timedelta(hours=28)).timestamp())
+ assert [p[0] for p in parts] == ["2026-01-01", "2026-01-02", "2026-01-03"]
+ assert sum(p[1] for p in parts) == 28 * 3600 * 1000
diff --git a/tests/test_ui.py b/tests/test_ui.py
new file mode 100644
index 0000000..b2ee70c
--- /dev/null
+++ b/tests/test_ui.py
@@ -0,0 +1,129 @@
+"""Offscreen smoke tests: every page builds, refreshes and survives a theme switch."""
+
+import pytest
+
+pytest.importorskip("PySide6.QtWidgets")
+
+from PySide6.QtWidgets import QApplication # noqa: E402
+
+from apptrackr.core.platform import DemoPlatform, NullPlatform # noqa: E402
+from apptrackr.core.tracker import Tracker # noqa: E402
+from apptrackr.data import db, demo, queries # noqa: E402
+from apptrackr.ui import fmt # noqa: E402
+
+
+@pytest.fixture
+def qapp():
+ from apptrackr.ui.main import prepare_app
+
+ app = QApplication.instance() or QApplication([])
+ prepare_app(app)
+ return app
+
+
+@pytest.fixture
+def window(qapp):
+ from apptrackr.ui.main import MainWindow
+
+ demo.seed(days=20)
+ tracker = Tracker(DemoPlatform())
+ tracker.reload_settings()
+ tracker.tick()
+ win = MainWindow(tracker, None, demo=True)
+ win.resize(1200, 780)
+ win.show()
+ qapp.processEvents()
+ yield win
+ tracker.stop()
+ win._quitting = True
+ win.close()
+ win.deleteLater()
+ qapp.processEvents()
+
+
+def test_every_page_renders(window, qapp):
+ for page in ("dashboard", "calendar", "apps", "rewards", "village", "settings"):
+ window.show_page(page)
+ window._tick()
+ qapp.processEvents()
+ assert window._stack.currentWidget() is window._views[page]
+ assert not window.grab().isNull()
+
+
+def test_pages_fit_minimum_window(window, qapp):
+ """At the smallest window size, two-column rows stack instead of clipping on the right."""
+ window.resize(window.minimumSize())
+ window.open_app(queries.find_app_id("code.exe"))
+ for page in ("dashboard", "calendar", "apps", "rewards", "village", "settings", "app"):
+ if page != "app":
+ window.show_page(page)
+ view = window._views[page]
+ for _ in range(3): # layout requests settle over a few event-loop passes
+ qapp.processEvents()
+ assert view.widget().minimumSizeHint().width() <= view.viewport().width(), page
+
+
+def test_app_detail_and_back_navigation(window, qapp):
+ window.show_page("calendar")
+ app_id = queries.find_app_id("code.exe")
+ window.open_app(app_id)
+ qapp.processEvents()
+ assert window._views["app"].title.text() == "VS Code"
+ window.go_back()
+ assert window._current == "calendar"
+
+
+def test_theme_switch_and_rewards_toggle(window, qapp):
+ db.set_setting("ui_mode", "light")
+ window.apply_theme()
+ db.set_setting("ui_theme", "Purple")
+ window.apply_theme()
+ qapp.processEvents()
+ db.set_setting("rewards_enabled", False)
+ window.apply_rewards_visibility()
+ assert not window._nav_buttons["rewards"].isVisibleTo(window)
+ window.show_page("rewards")
+ db.set_setting("rewards_enabled", True)
+ window.apply_rewards_visibility()
+
+
+def test_exclude_with_undo(window, qapp):
+ app_id = queries.find_app_id("chrome.exe")
+ window.show_page("apps")
+ window.exclude_app(app_id)
+ assert queries.get_app(app_id)["is_hidden"] == 1
+ window.toast._run_action()
+ assert queries.get_app(app_id)["is_hidden"] == 0
+
+
+def test_claim_from_rewards_page(window, qapp):
+ view = window._views["rewards"]
+ window.show_page("rewards")
+ view._claim_all()
+ from apptrackr.rewards import engine
+
+ assert engine.unclaimed_count() == 0
+
+
+def test_unsupported_platform_shows_state(qapp):
+ from apptrackr.ui.main import MainWindow
+
+ tracker = Tracker(NullPlatform())
+ win = MainWindow(tracker, None)
+ win.show_page("dashboard")
+ win._tick()
+ assert win._views["dashboard"].now.name.text() == "Tracking unavailable"
+ assert "Windows" in win._status.accessibleName()
+ win._quitting = True
+ win.close()
+
+
+def test_formatters():
+ assert fmt.duration(59_000) == "59s"
+ assert fmt.duration(65_000) == "1m 5s"
+ assert fmt.duration(65_000, short=True) == "1m"
+ assert fmt.duration(3_600_000 * 2 + 60_000 * 5) == "2h 5m"
+ assert fmt.clock(3_725_000) == "1:02:05"
+ 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
diff --git a/tests/test_updater.py b/tests/test_updater.py
new file mode 100644
index 0000000..58e7a02
--- /dev/null
+++ b/tests/test_updater.py
@@ -0,0 +1,62 @@
+import io
+import json
+
+import pytest
+
+from apptrackr.updater import check
+
+
+def test_parse_version():
+ assert check.parse_version("v1.2") == (1, 2, 0)
+ assert check.parse_version("1.10.3-beta") == (1, 10, 3)
+ assert check.is_newer("v1.10.0", "1.9.9")
+ assert not check.is_newer("1.1.0", "1.1.0")
+ with pytest.raises(ValueError):
+ check.parse_version("latest")
+
+
+def _fake_urlopen(payload):
+ class Resp(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ return lambda req, timeout=0: Resp(json.dumps(payload).encode())
+
+
+def test_check_reports_newer_release(monkeypatch):
+ payload = {
+ "tag_name": "v9.0.0",
+ "html_url": "https://example/rel",
+ "assets": [
+ {"name": "AppTrackr_Portable.zip", "browser_download_url": "zip"},
+ {"name": "AppTrackr_Setup.exe", "browser_download_url": "exe", "size": 42},
+ ],
+ }
+ monkeypatch.setattr(check, "urlopen", _fake_urlopen(payload))
+ info = check.check_for_update("https://feed")
+ assert info == check.UpdateInfo("9.0.0", "exe", "https://example/rel", 42)
+
+
+def test_check_up_to_date(monkeypatch):
+ monkeypatch.setattr(check, "urlopen", _fake_urlopen({"tag_name": "v0.1.0"}))
+ assert check.check_for_update("https://feed") is None
+
+
+def test_check_errors_are_not_reported_as_up_to_date(monkeypatch):
+ def boom(req, timeout=0):
+ raise OSError("offline")
+
+ monkeypatch.setattr(check, "urlopen", boom)
+ with pytest.raises(check.UpdateError):
+ check.check_for_update("https://feed")
+
+
+def test_resolve_url(monkeypatch):
+ monkeypatch.delenv("APPTRACKR_UPDATE_URL", raising=False)
+ assert check.resolve_url("") == check.DEFAULT_UPDATE_URL
+ monkeypatch.setenv("APPTRACKR_UPDATE_URL", "https://env")
+ assert check.resolve_url("") == "https://env"
+ assert check.resolve_url(" https://cfg ") == "https://cfg"