Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 49 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,15 @@ time in chosen apps into XP and a small village-building game.
| Area | What you get |
| --- | --- |
| Tracking | Foreground-only time, idle cut-off at your last input, lock-screen detection, midnight-accurate daily totals, UWP apps resolved to the real app, elevated apps tracked by name |
| Dashboard | Live session card, today vs. this time yesterday, week total, today by hour, last 14 days, top apps with share and category breakdown |
| Dashboard | Live session dial, today vs. this time yesterday, week total, today by hour, last 14 days, top apps with share and category breakdown |
| In other terms | Today, this week or all time retold as Everest summit days, Apollo 11 trips, ISS laps, marathons, novels and more, each with the basis for its number |
| Calendar | Month heatmap with keyboard navigation, month totals and busiest day, per-day hourly chart and app list |
| Apps | Search, period filter (today to all time), category and favorite filters, sort by time, launches or clicks |
| App detail | Today / 7 / 30 day totals, 30-day chart, recent sessions, first and last seen, longest session, rename, category |
| Control | Per-app daily limits with notifications, exclude any app (with undo), pause from the tray for a set time |
| Control | Per-app daily limits with notifications, per-type notification switches, exclude any app (with undo), pause from the tray for a set time |
| Rewards | Optional XP, levels, streaks and a village-building game whose buildings boost future rewards |
| Desktop | Tray icon with live tooltip, launch at sign-in (starts hidden), single instance, dark, light or system theme with 8 accents |
| Motion | Fluent-timed page transitions, counters, chart and list motion that explain each change; follows Windows *Animation effects* and can be turned off in Settings |
| Desktop | Tray icon with live tooltip, launch at sign-in (starts hidden), single instance, six palettes (three dark, three light) with system switching and 8 accents |
| Motion | Fluent-timed page transitions, odometer readouts, springy switches, check marks that draw in, a gliding fader, hover fades and a tick burst on claims and builds; follows Windows *Animation effects* and can be turned off in Settings |
| Data | CSV and JSON export, consistent database backup and validated restore, automatic schema migrations |
| Updates | Once-a-day check against GitHub releases, in-app download and install |

Expand All @@ -60,11 +61,17 @@ time in chosen apps into XP and a small village-building game.
<td><img src="docs/screenshots/village.png" alt="Village"><br><sub>Village: buildings, inventory and market</sub></td>
</tr>
<tr>
<td><img src="docs/screenshots/settings.png" alt="Settings"><br><sub>Settings apply immediately</sub></td>
<td><img src="docs/screenshots/dashboard-light.png" alt="Dashboard in the light theme"><br><sub>Light theme</sub></td>
<td><img src="docs/screenshots/dashboard-perspective.png" alt="In other terms"><br><sub>In other terms: the week as Voyager kilometres, marathons and Everest</sub></td>
<td><img src="docs/screenshots/settings-appearance.png" alt="Appearance settings"><br><sub>Palette gallery, accents and animation switch</sub></td>
</tr>
<tr>
<td><img src="docs/screenshots/settings.png" alt="Settings"><br><sub>Check boxes and a ruler slider for idle timeout</sub></td>
<td><img src="docs/screenshots/dashboard-light.png" alt="Dashboard in the light theme"><br><sub>Paper, the default light palette</sub></td>
</tr>
</table>

<img src="docs/screenshots/themes.png" alt="All six palettes, each with a different accent" width="100%">

Screenshots and the animation above are generated from demo data with `python scripts/screenshots.py`
and `python scripts/record_demo.py`.

Expand All @@ -73,13 +80,14 @@ and `python scripts/record_demo.py`.
The interface is styled as an instrument panel: warm neutrals, hairline rules, engraved monospaced labels
and one signal color. Recorded history is drawn in neutral ink; the signal color marks only what is live,
selected or current. Charts use hairline grids, thin bars on tick-mark rulers and a five-step calendar ramp.
Category colors are a categorical palette checked for color-vision-deficiency separation in both themes,
and text never takes a data color.
Category colors are a categorical palette checked for color-vision-deficiency separation in both modes,
and text never takes a data color. Every palette and accent pair keeps small text at 4.5:1 and marks at
3:1; accents are re-stepped per palette to hold that (`tests/test_theme.py` checks all 48 pairs).

| Element | Choice |
| --- | --- |
| Type | Instrument Sans (interface, tabular figures), Martian Mono (labels) |
| Themes | Graphite (dark) and Paper (light), or follow Windows |
| Palettes | Dark: Graphite, Carbon (true black), Midnight. Light: Paper, Porcelain, Sage. System mode switches between your two picks |
| Signal color | Orange `#ff6b1a` by default, 8 presets in Settings |
| Shape | 6 px panels, 4 px controls, 1 px borders, no shadows |

Expand All @@ -92,7 +100,29 @@ Download the latest build from [Releases](https://github.com/H4ch1Net/AppTrackr/
| `AppTrackr_Setup.exe` | You want Start Menu entries, optional sign-in startup and uninstall support. Installs per user, no admin rights needed. |
| `AppTrackr_Portable.zip` | You want to run it from a folder. Extract anywhere and start `AppTrackr.exe`. |

Requirements: Windows 10 or 11 (64-bit). Upgrading over v1.0 keeps your data and migrates it on first start.
Requirements: Windows 10 or 11 (64-bit).

### Upgrading

Every version keeps your data in `%APPDATA%\AppTrackr`, and installers and portable builds of any
version read the same folder, so upgrading never starts you from zero.

- **From 1.1 or later.** AppTrackr checks GitHub once a day. Choose *Download and install* in Settings;
the installer replaces the old build and starts the new one, and tracking picks up where it stopped.
- **From 1.0.x.** Run the new `AppTrackr_Setup.exe`. It installs over 1.0 in the same folder, closes the
running copy and keeps the Start Menu and sign-in entries. To update from inside 1.0 instead, paste
`https://api.github.com/repos/H4ch1Net/AppTrackr/releases/latest` into *Settings > Updates > Update feed
URL* (1.0 ships without one) and press *Check for Updates*.
- **Portable.** Extract the new zip anywhere, or over the old folder, and start it. Data stays in `%APPDATA%`.

On the first start after an upgrade that changes the database, AppTrackr copies it to
`data-backup-schema<N>-<date>.sqlite` in the same folder and then upgrades it in a single transaction:
either everything is converted or nothing changes. Upgrading from 1.0 keeps every app, finished session, open
and click count, reward, building and setting, and rebuilds daily totals from the raw sessions, which also
recovers time 1.0 left out (sessions that ended in idle, and sessions that ran past midnight). Sign-in
entries made by 1.0 are updated to start in the tray. If an upgrade ever fails, AppTrackr says so, leaves
the data as it was and points to the backup and the log. `tests/test_upgrade.py` runs this upgrade on a
database written by v1.0.2's own code.

## Usage

Expand All @@ -108,6 +138,9 @@ use **Quit** from the tray menu (or <kbd>Ctrl</kbd>+<kbd>Q</kbd>) to stop it.
- **Favorites and streaks.** Star apps you want to spend time in. A streak day needs 30 minutes in favorites.
- **Rewards.** Pick earning apps on the Rewards page or from an app's page. Milestones (30 min, 1 h, 2 h, 5 h
of focus per day) pay XP and resources you spend in the village. Turn the whole layer off in Settings.
- **In other terms.** The dashboard card retells today, this week or all time against known yardsticks.
*Shuffle* shows others. Each comparison names its basis, for example "South Col to the summit and back
down: about 14 h".

### Keyboard shortcuts

Expand Down Expand Up @@ -225,13 +258,14 @@ both to the GitHub release. `ci.yml` runs lint and tests on Windows and Linux fo
apptrackr/
__main__.py entry point: arguments, logging, single instance, service wiring
paths.py data, log and asset locations
perspective.py yardsticks for 'In other terms' and how they are picked
core/ tracker, platform (Win32), launch watcher, click counter, autostart, limits
data/ SQLite access and migrations, queries, export/backup, app catalog, demo data
rewards/ milestone rules, reward engine, streaks
game/ village state and balance values
updater/ GitHub release check and installer download
ui/ main window, theme and motion tokens, icons, views and shared widgets
assets/ logo, Lucide icons, illustrations, bundled fonts
assets/ logo, Lucide and AppTrackr line icons, illustrations, bundled fonts
packaging/ PyInstaller spec, Inno Setup script, app icon
scripts/ screenshot, demo animation, README art and icon generators
tests/ pytest suite (data, tracker, rewards, updater, offscreen UI)
Expand All @@ -257,8 +291,8 @@ flowchart LR
- **Nothing is tracked.** Check the tracking module at the bottom of the sidebar. *Paused* resumes on click. *Idle* means no
input for the idle timeout. Apps you excluded are listed in Settings.
- **An app shows up under an odd name.** Open it and use the menu next to *Favorite* to rename it.
- **The window opens at sign-in instead of staying in the tray.** Startup entries created by v1.0 lack
`--minimized`. Turn *Launch at startup* off and on again in Settings to rewrite the entry.
- **The window opens at sign-in instead of staying in the tray.** Start AppTrackr once; it updates startup
entries left by older versions. If that does not help, turn *Launch at startup* off and on in Settings.
- **Something broke.** Run with `--debug` and look at `%APPDATA%\AppTrackr\logs\apptrackr.log`, then
[open an issue](https://github.com/H4ch1Net/AppTrackr/issues) with the relevant lines.

Expand All @@ -272,7 +306,8 @@ regenerated screenshots if they change what the README shows.

## License

[MIT](LICENSE). Icons from [Lucide](https://lucide.dev) (ISC, see `apptrackr/assets/icons/LICENSE`).
[MIT](LICENSE). Icons from [Lucide](https://lucide.dev) (ISC, see `apptrackr/assets/icons/LICENSE`), plus a few
drawn for AppTrackr (marked in the SVG).
Fonts: [Instrument Sans](https://github.com/Instrument/instrument-sans) and
[Martian Mono](https://github.com/evilmartians/mono), both SIL Open Font License 1.1
(see `apptrackr/assets/fonts`).
21 changes: 20 additions & 1 deletion apptrackr/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,24 @@ def main(argv: list[str] | None = None) -> int:
from apptrackr.data import db
from apptrackr.ui.main import MainWindow, prepare_app

db.init_db()
try:
db.init_db()
except Exception:
log.exception("Could not open or upgrade the database")
from PySide6.QtWidgets import QMessageBox

QMessageBox.critical(
None,
APP_NAME,
"AppTrackr could not open or upgrade its data, so it did not start. Your data was not changed, "
f"and a backup copy is kept next to it in:\n{paths.data_dir()}\n\n"
f"Details are in the log:\n{paths.log_dir()}",
)
return 1
if not args.demo:
from apptrackr.core import autostart

autostart.repair()
if args.demo:
from apptrackr.data import demo

Expand Down Expand Up @@ -163,6 +180,8 @@ def shutdown():
shutil.rmtree(paths.data_dir(), ignore_errors=True)

app.aboutToQuit.connect(shutdown)
# Windows sign-out and installers closing the app (Restart Manager) ask to save first.
app.commitDataRequest.connect(lambda *_: tracker.flush())
log.info("%s %s started (data: %s)", APP_NAME, __version__, paths.data_dir())
return app.exec()

Expand Down
1 change: 1 addition & 0 deletions apptrackr/assets/icons/book.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions apptrackr/assets/icons/footprints.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions apptrackr/assets/icons/languages.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions apptrackr/assets/icons/orbit.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions apptrackr/assets/icons/plane.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 43 additions & 0 deletions apptrackr/core/autostart.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import sys
from pathlib import Path

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -60,3 +61,45 @@ def set_enabled(enable: bool) -> bool:
except OSError:
log.exception("Could not update autostart entry")
return False


def _exe_in(cmd: str) -> str:
"""The program path at the start of a Run-key command line."""
cmd = cmd.strip()
if cmd.startswith('"'):
end = cmd.find('"', 1)
return cmd[1:end] if end > 0 else cmd[1:]
return cmd.split(" ", 1)[0]


def needs_repair(current: str, ours: str, exists=lambda p: Path(p).exists()) -> bool:
"""True when an existing entry should be rewritten for this build.

1.1 and later always add --minimized, so an entry without it was made by 1.0 (even
when it points at an old portable copy) and is moved to this build. An entry whose
program no longer exists is repaired too; one for another live 1.1+ copy is left alone.
"""
if "--minimized" not in current:
return True
exe = _exe_in(current)
return not exe or not exists(exe)


def repair() -> bool:
"""Bring an existing startup entry up to date after an upgrade. Returns True if rewritten."""
if not supported() or not getattr(sys, "frozen", False):
return False
import winreg

try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _RUN_KEY) as key:
current, _kind = winreg.QueryValueEx(key, _VALUE)
except FileNotFoundError:
return False
except OSError:
log.exception("Could not read autostart entry")
return False
if not needs_repair(str(current), sys.executable):
return False
log.info("Updating the startup entry for this version (was %r)", current)
return set_enabled(True)
5 changes: 5 additions & 0 deletions apptrackr/core/tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ def stop(self) -> None:
with self._lock:
self._close(self._clock())

def flush(self) -> None:
"""Commit the live session so far without ending it (sign-out, installer closing the app)."""
with self._lock:
self._checkpoint(self._clock())

def reload_settings(self) -> None:
with self._lock:
self._idle_threshold = max(0, db.get_int("idle_threshold_sec", 300))
Expand Down
57 changes: 48 additions & 9 deletions apptrackr/data/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import logging
import sqlite3
import threading
import time
from pathlib import Path
from typing import Any, Callable

Expand Down Expand Up @@ -73,20 +74,58 @@ def _columns(conn: sqlite3.Connection, table: str) -> set[str]:


def init_db() -> None:
"""Create the schema on first run and migrate older databases."""
"""Create the schema on first run and migrate older databases.

Before migrating, the database is copied next to itself (see backup_path), and
all migrations run in one transaction: an upgrade either completes or leaves the
database exactly as the previous version wrote it.
"""
conn = get_connection()
fresh = not _table_exists(conn, "apps")
version = SCHEMA_VERSION if fresh else conn.execute("PRAGMA user_version").fetchone()[0]
pending = [(target, migrate) for target, migrate in _MIGRATIONS if version < target]
if pending:
_backup(conn, version)
conn.executescript(_SCHEMA.read_text(encoding="utf-8"))
version = conn.execute("PRAGMA user_version").fetchone()[0]
if fresh:
version = SCHEMA_VERSION
for target, migrate in _MIGRATIONS:
if version < target:
log.info("Migrating database to schema v%d", target)
if not pending:
if fresh:
conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
conn.commit() # a database from a newer version keeps its higher user_version
return
conn.execute("BEGIN IMMEDIATE")
try:
for target, migrate in pending:
log.info("Migrating database from schema v%d to v%d", version, target)
migrate(conn)
version = target
conn.execute(f"PRAGMA user_version = {int(version)}")
conn.commit()
conn.execute(f"PRAGMA user_version = {int(version)}")
conn.commit()
except Exception:
conn.rollback()
log.exception("Database migration failed; the database was left unchanged")
raise


def backup_path(version: int) -> Path:
"""Where the pre-upgrade copy of a schema *version* database is kept."""
stamp = time.strftime("%Y%m%d-%H%M%S")
return db_path().with_name(f"data-backup-schema{version}-{stamp}.sqlite")


def _backup(conn: sqlite3.Connection, version: int) -> Path | None:
"""Copy the database before an upgrade touches it. A failed copy is logged, not fatal."""
target = backup_path(version)
try:
dest = sqlite3.connect(str(target))
try:
conn.backup(dest)
finally:
dest.close()
log.info("Backed up the database to %s before upgrading", target)
return target
except (sqlite3.Error, OSError):
log.exception("Could not back up the database before upgrading")
return None


# ---------------------------------------------------------------------------
Expand Down
Loading
Loading