diff --git a/README.md b/README.md
index 2f50063..97cd569 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@ shows it as a dashboard, calendar and per-app history, and stays out of the way

[](LICENSE)
-
+
@@ -25,8 +25,8 @@ in front of you: time is credited only to the focused app, stops when you go idl
screen, and is written to a local SQLite database every 30 seconds. Nothing leaves your machine.
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.
+trends and sessions, daily limits with notifications, a floating timer over other apps, and an
+optional idle game that rewards staying focused in the apps you choose.
## Features
@@ -34,12 +34,13 @@ time in chosen apps into XP and a small village-building game.
| --- | --- |
| 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 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 |
+| In other terms | Today, this week or all time as six plain counts drawn from 56 yardsticks (films, football matches, loaves of bread, ISS laps, 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, 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 |
+| Focus game | Optional idle game: unbroken time in your focus apps builds flow (x1 to x3), flow powers a village that produces resources while you work, and a daily focus goal grows a streak and opens a chest |
+| Floating timer | A small always-on-top clock over other apps with the time in the current app, today's total and, for focus apps, the flow tier; hides over full-screen windows |
| 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 |
@@ -54,14 +55,14 @@ time in chosen apps into XP and a small village-building game.
All apps for a period, filterable and sortable
-
Per-app history, limit, rewards and sessions
+
Per-app history, limit, focus switch and sessions
-
Level progress, pending rewards and earning apps
-
Village: buildings, inventory and market
+
Focus: live flow multiplier, tier ladder, daily goal and chest
+
Village: harvest, production, buildings and market
-
In other terms: the week as Voyager kilometres, marathons and Everest
+
In other terms: the week as lectures, football matches and loaves of bread
Palette gallery, accents and animation switch
@@ -135,18 +136,26 @@ use **Quit** from the tray menu (or Ctrl+Q) to stop it.
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.
+- **Focus apps.** Pick the apps you want to spend time in (an editor, a design tool, docs) on the Focus page or
+ with the *Focus app* switch on an app's page. Only time in them counts toward the game.
+- **Flow.** Every minute in a focus app earns focus points. Stay with it and the run climbs tiers: x1.5 after
+ 10 minutes, x2 after 25, x2.5 after 45, x3 after 75. A short look elsewhere (3 minutes, more with taverns)
+ does not end a run.
+- **Village.** Lumberyards, quarries, farms, mines and labs turn focus points into resources. They wait in the
+ harvest until you collect them on the Village page, up to what storage holds. Spend them on buildings.
+- **Daily goal.** Reach your focus goal (2 h by default, set in Settings) to grow your streak and open the
+ daily chest. Turn the whole game off in Settings.
+- **Floating timer.** While you work in another app, a small clock in the corner shows how long you have
+ been in it. Drag it anywhere, double-click it to open AppTrackr, right-click to hide it.
- **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".
+ *Shuffle* shows others. Each comparison names its basis, for example "football matches: two 45-minute
+ halves".
### Keyboard shortcuts
| Keys | Action |
| --- | --- |
-| Ctrl+1 to Ctrl+5 | Dashboard, Calendar, Apps, Rewards, Village |
+| Ctrl+1 to Ctrl+5 | Dashboard, Calendar, Apps, Focus, Village |
| Ctrl+, | Settings |
| Ctrl+F | Search apps |
| Ctrl+Shift+P | Pause or resume tracking |
@@ -265,14 +274,14 @@ apptrackr/
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
+ rewards/ focus app rules, XP and levels, daily goal and streak, rewards from 1.x
+ game/ flow and focus points, village production and harvest, balance values
updater/ GitHub release check and installer download
ui/ main window, theme and motion tokens, icons, views and shared widgets
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)
+tests/ pytest suite (data, tracker, game, upgrades, updater, offscreen UI)
```
```mermaid
@@ -283,7 +292,8 @@ flowchart LR
C[core.clicks] --> DB
DB --> Q[data.queries]
Q --> UI[ui views]
- DB --> R[rewards.engine] --> G[game.state]
+ DB --> F[game.focus flow, focus points] --> G[game.state village, harvest]
+ G --> R[rewards.engine XP, streak]
R --> UI
G --> UI
T -->|snapshot| UI
diff --git a/apptrackr/__init__.py b/apptrackr/__init__.py
index 473b74a..508da6f 100644
--- a/apptrackr/__init__.py
+++ b/apptrackr/__init__.py
@@ -1,6 +1,6 @@
"""AppTrackr: foreground app usage tracker for Windows."""
-__version__ = "1.1.0"
+__version__ = "1.2.0"
APP_NAME = "AppTrackr"
APP_USER_MODEL_ID = "H4ch1Net.AppTrackr"
diff --git a/apptrackr/__main__.py b/apptrackr/__main__.py
index cd6e5c9..a23daf3 100644
--- a/apptrackr/__main__.py
+++ b/apptrackr/__main__.py
@@ -141,8 +141,10 @@ def main(argv: list[str] | None = None) -> int:
return 1
if not args.demo:
from apptrackr.core import autostart
+ from apptrackr.rewards import rules
autostart.repair()
+ rules.adopt_favorites_once()
if args.demo:
from apptrackr.data import demo
diff --git a/apptrackr/assets/icons/ball.svg b/apptrackr/assets/icons/ball.svg
new file mode 100644
index 0000000..f36b783
--- /dev/null
+++ b/apptrackr/assets/icons/ball.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/bike.svg b/apptrackr/assets/icons/bike.svg
new file mode 100644
index 0000000..83c5091
--- /dev/null
+++ b/apptrackr/assets/icons/bike.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/briefcase.svg b/apptrackr/assets/icons/briefcase.svg
new file mode 100644
index 0000000..751ef26
--- /dev/null
+++ b/apptrackr/assets/icons/briefcase.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/car.svg b/apptrackr/assets/icons/car.svg
new file mode 100644
index 0000000..136ac17
--- /dev/null
+++ b/apptrackr/assets/icons/car.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/clapperboard.svg b/apptrackr/assets/icons/clapperboard.svg
new file mode 100644
index 0000000..d7b2581
--- /dev/null
+++ b/apptrackr/assets/icons/clapperboard.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/cup.svg b/apptrackr/assets/icons/cup.svg
new file mode 100644
index 0000000..39cdf24
--- /dev/null
+++ b/apptrackr/assets/icons/cup.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/droplet.svg b/apptrackr/assets/icons/droplet.svg
new file mode 100644
index 0000000..3c4190a
--- /dev/null
+++ b/apptrackr/assets/icons/droplet.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/globe.svg b/apptrackr/assets/icons/globe.svg
new file mode 100644
index 0000000..d4c065c
--- /dev/null
+++ b/apptrackr/assets/icons/globe.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/music.svg b/apptrackr/assets/icons/music.svg
new file mode 100644
index 0000000..b76c16c
--- /dev/null
+++ b/apptrackr/assets/icons/music.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/planet.svg b/apptrackr/assets/icons/planet.svg
new file mode 100644
index 0000000..66b2443
--- /dev/null
+++ b/apptrackr/assets/icons/planet.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/steering-wheel.svg b/apptrackr/assets/icons/steering-wheel.svg
new file mode 100644
index 0000000..ed88d6d
--- /dev/null
+++ b/apptrackr/assets/icons/steering-wheel.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/tennis.svg b/apptrackr/assets/icons/tennis.svg
new file mode 100644
index 0000000..d9c28ce
--- /dev/null
+++ b/apptrackr/assets/icons/tennis.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/train.svg b/apptrackr/assets/icons/train.svg
new file mode 100644
index 0000000..be6b920
--- /dev/null
+++ b/apptrackr/assets/icons/train.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/assets/icons/wind.svg b/apptrackr/assets/icons/wind.svg
new file mode 100644
index 0000000..23ef08c
--- /dev/null
+++ b/apptrackr/assets/icons/wind.svg
@@ -0,0 +1 @@
+
diff --git a/apptrackr/core/platform.py b/apptrackr/core/platform.py
index 8c97049..221cf1b 100644
--- a/apptrackr/core/platform.py
+++ b/apptrackr/core/platform.py
@@ -85,12 +85,23 @@ class _LASTINPUTINFO(ctypes.Structure):
_fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
+class _RECT(ctypes.Structure):
+ _fields_ = [("left", ctypes.c_long), ("top", ctypes.c_long), ("right", ctypes.c_long), ("bottom", ctypes.c_long)]
+
+
+class _MONITORINFO(ctypes.Structure):
+ _fields_ = [("cbSize", ctypes.c_ulong), ("rcMonitor", _RECT), ("rcWork", _RECT), ("dwFlags", ctypes.c_ulong)]
+
+
class WindowsPlatform:
"""Win32 implementation using user32/kernel32 through ctypes."""
supported = True
_DESKTOP_READOBJECTS = 0x0001
_UWP_HOST = "applicationframehost.exe"
+ _GWL_STYLE = -16
+ _WS_CAPTION = 0x00C00000
+ _MONITOR_DEFAULTTONEAREST = 2
def __init__(self) -> None:
from ctypes import wintypes
@@ -112,6 +123,18 @@ def __init__(self) -> None:
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
+ u.GetWindowRect.argtypes = [wintypes.HWND, ctypes.POINTER(_RECT)]
+ u.GetWindowRect.restype = wintypes.BOOL
+ u.GetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int]
+ u.GetWindowLongW.restype = ctypes.c_long
+ u.MonitorFromWindow.argtypes = [wintypes.HWND, wintypes.DWORD]
+ u.MonitorFromWindow.restype = wintypes.HANDLE
+ u.GetMonitorInfoW.argtypes = [wintypes.HANDLE, ctypes.POINTER(_MONITORINFO)]
+ u.GetMonitorInfoW.restype = wintypes.BOOL
+ u.GetShellWindow.argtypes = []
+ u.GetShellWindow.restype = wintypes.HWND
+ u.GetDesktopWindow.argtypes = []
+ u.GetDesktopWindow.restype = wintypes.HWND
k.GetTickCount.argtypes = []
k.GetTickCount.restype = wintypes.DWORD
@@ -167,6 +190,25 @@ def foreground_app(self) -> ForegroundApp | None:
self._last_key, self._last_app = key, app
return app
+ def foreground_fullscreen(self) -> bool:
+ """True while the foreground window covers its whole monitor (a game, a video, a slideshow)."""
+ u = self._user32
+ hwnd = u.GetForegroundWindow()
+ if not hwnd or hwnd in (u.GetShellWindow(), u.GetDesktopWindow()):
+ return False
+ rect = _RECT()
+ info = _MONITORINFO()
+ info.cbSize = ctypes.sizeof(_MONITORINFO)
+ monitor = u.MonitorFromWindow(hwnd, self._MONITOR_DEFAULTTONEAREST)
+ if not u.GetWindowRect(hwnd, ctypes.byref(rect)) or not u.GetMonitorInfoW(monitor, ctypes.byref(info)):
+ return False
+ m = info.rcMonitor
+ exact = (rect.left, rect.top, rect.right, rect.bottom) == (m.left, m.top, m.right, m.bottom)
+ covers = rect.left <= m.left and rect.top <= m.top and rect.right >= m.right and rect.bottom >= m.bottom
+ # A maximized window overhangs the monitor by its borders but keeps its title bar.
+ captionless = (u.GetWindowLongW(hwnd, self._GWL_STYLE) & self._WS_CAPTION) != self._WS_CAPTION
+ return exact or (covers and captionless)
+
def idle_seconds(self) -> float:
info = _LASTINPUTINFO()
info.cbSize = ctypes.sizeof(_LASTINPUTINFO)
diff --git a/apptrackr/core/tracker.py b/apptrackr/core/tracker.py
index 0119469..f74793c 100644
--- a/apptrackr/core/tracker.py
+++ b/apptrackr/core/tracker.py
@@ -139,6 +139,14 @@ def current_app_id(self) -> int | None:
"""Lock-free read for hot paths such as the mouse hook."""
return self._app_id
+ def foreground_fullscreen(self) -> bool:
+ """True while a full-screen window is in front (Windows only)."""
+ check = getattr(self._platform, "foreground_fullscreen", None)
+ try:
+ return bool(check()) if check else False
+ except OSError:
+ return False
+
def snapshot(self) -> Snapshot:
with self._lock:
now = self._clock()
diff --git a/apptrackr/data/demo.py b/apptrackr/data/demo.py
index 2c30608..fa22cd5 100644
--- a/apptrackr/data/demo.py
+++ b/apptrackr/data/demo.py
@@ -4,6 +4,7 @@
import json
import random
+import time
from datetime import date, datetime, timedelta
from . import db
@@ -108,21 +109,30 @@ def seed(days: int = 120, seed_value: int = 7, now: datetime | None = None) -> N
def _seed_rewards(app_ids: dict[str, int]) -> None:
- from ..rewards import engine, rules
+ from ..rewards import 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}},
+ "buildings": {
+ "lumberyard": {"level": 4},
+ "quarry": {"level": 3},
+ "farm": {"level": 2},
+ "mine": {"level": 1},
+ "storage": {"level": 3},
+ "house": {"level": 2},
+ "workshop": {"level": 3},
+ "lab": {"level": 1},
+ },
"villagers": 2,
- "inventory": {"wood": 142, "stone": 96, "metal": 38, "food": 61, "blueprints": 3},
+ "inventory": {"wood": 342, "stone": 196, "metal": 38, "food": 161, "blueprints": 3},
+ "collected_until": time.time() - 3 * 3600, # a harvest from the last three hours is waiting
+ "chests": {},
}
db.execute("UPDATE village_state SET state_json = ? WHERE profile_id = 1", (json.dumps(village),))
diff --git a/apptrackr/game/economy.py b/apptrackr/game/economy.py
index 99d085d..fe3d3b0 100644
--- a/apptrackr/game/economy.py
+++ b/apptrackr/game/economy.py
@@ -1,33 +1,64 @@
-"""Balance values for rewards and the village."""
+"""Balance values for the focus village.
+
+Focus points are the currency of everything: one minute in a focus app earns
+one point times the current flow multiplier. Points turn into XP and, through
+the village's buildings, into resources.
+"""
from __future__ import annotations
XP_PER_LEVEL = 100
CREDITS_PER_LEVEL = 10 # granted per level reached, times the level number
+XP_PER_POINT = 0.25 # about a level every three hours of good focus
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
+# Flow: an unbroken run of focus-app time. (minutes into the run, multiplier, name)
+FLOW_TIERS = (
+ (0, 1.0, "Warming up"),
+ (10, 1.5, "Focused"),
+ (25, 2.0, "In the zone"),
+ (45, 2.5, "Deep work"),
+ (75, 3.0, "Flow"),
+)
+FLOW_GRACE_SEC = 180 # time away from focus apps that does not end a run
+TAVERN_GRACE_SEC = 60 # extra grace per tavern level
-STREAK_REWARDS = {
- 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},
+# Resources produced per focus point: (producer building, amount per level, free levels)
+PRODUCTION = {
+ "wood": ("lumberyard", 0.25, 1),
+ "stone": ("quarry", 0.15, 1),
+ "food": ("farm", 0.20, 1),
+ "metal": ("mine", 0.08, 0),
+ "blueprints": ("lab", 0.0025, 0),
}
+VILLAGER_PCT = 4 # production bonus per villager
+MONUMENT_PCT = 15 # production bonus once the monument stands
+WORKSHOP_XP_PCT = 5 # XP bonus per workshop level
+
+BASE_RESOURCE_CAP = 200
+STORAGE_GROWTH = 1.6
+
+# Daily focus goal (minutes in focus apps), streaks and the chest it opens.
+DEFAULT_GOAL_MIN = 120
+GOAL_CHOICES = (30, 60, 90, 120, 180, 240, 360)
+
+
+def chest_for(streak: int) -> dict:
+ """What the daily chest holds on day *streak* of a goal streak."""
+ reward = {"xp": 25, "credits": 20 + 5 * min(max(streak, 1), 10), "blueprints": 1}
+ if streak and streak % 7 == 0:
+ reward["blueprints"] += 1
+ reward["credits"] += 50
+ return reward
+
# Credits needed to buy a bundle of resources at the market.
MARKET = {
- "wood": (10, 5),
- "food": (10, 5),
- "stone": (10, 8),
- "metal": (5, 10),
+ "wood": (25, 5),
+ "food": (25, 5),
+ "stone": (20, 8),
+ "metal": (10, 10),
"blueprints": (1, 40),
}
@@ -42,4 +73,12 @@ def level_progress(xp: int) -> tuple[int, int]:
def resource_cap(storage_level: int) -> int:
- return BASE_RESOURCE_CAP + STORAGE_CAP_PER_LEVEL * storage_level
+ return int(round(BASE_RESOURCE_CAP * STORAGE_GROWTH**storage_level, -1))
+
+
+def tier_index(run_minutes: float) -> int:
+ index = 0
+ for i, (start, _mult, _name) in enumerate(FLOW_TIERS):
+ if run_minutes >= start:
+ index = i
+ return index
diff --git a/apptrackr/game/focus.py b/apptrackr/game/focus.py
new file mode 100644
index 0000000..7d429a1
--- /dev/null
+++ b/apptrackr/game/focus.py
@@ -0,0 +1,161 @@
+"""Flow: unbroken runs of time in focus apps, and the focus points they earn.
+
+A run continues while the gaps between focus-app sessions stay within the
+grace period (a quick look at chat or docs does not end it). Time outside
+focus apps never earns points; inside a run, each minute earns the multiplier
+of the tier the run has reached.
+"""
+
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass
+from datetime import datetime
+
+from ..data import db
+from . import economy
+
+LOOKBACK_SEC = (economy.FLOW_TIERS[-1][0] + 60) * 60 # enough history to know a run's tier
+
+
+@dataclass(frozen=True)
+class Flow:
+ active: bool # the foreground app is a focus app right now
+ run_ms: int # length of the current (or last) run, wall clock
+ multiplier: float
+ tier: str
+ next_tier: str | None
+ next_in_ms: int # time until the next tier, 0 at the top
+ today_focus_ms: int
+
+
+def multiplier_at(run_minutes: float) -> float:
+ return economy.FLOW_TIERS[economy.tier_index(run_minutes)][1]
+
+
+def _weighted_minutes(e0: float, e1: float) -> float:
+ """Integral of the multiplier between e0 and e1 seconds into a run, in minutes."""
+ total = 0.0
+ tiers = economy.FLOW_TIERS
+ for i, (start, mult, _name) in enumerate(tiers):
+ lo = start * 60
+ hi = tiers[i + 1][0] * 60 if i + 1 < len(tiers) else float("inf")
+ a, b = max(e0, lo), min(e1, hi)
+ if b > a:
+ total += (b - a) * mult
+ return total / 60
+
+
+def runs(spans: list[tuple[float, float]], grace_sec: float) -> list[list[tuple[float, float]]]:
+ """Group sorted (start, end) focus spans into runs."""
+ out: list[list[tuple[float, float]]] = []
+ last_end = None
+ for start, end in sorted(spans):
+ if end <= start:
+ continue
+ if last_end is None or start - last_end > grace_sec:
+ out.append([])
+ out[-1].append((start, end))
+ last_end = max(end, last_end or end)
+ return out
+
+
+def points(spans: list[tuple[float, float]], grace_sec: float, since: float, until: float) -> tuple[float, int]:
+ """Focus points and focused milliseconds earned between *since* and *until*."""
+ fp = 0.0
+ focus_ms = 0
+ for run in runs(spans, grace_sec):
+ run_start = run[0][0]
+ for start, end in run:
+ a, b = max(start, since), min(end, until)
+ if b <= a:
+ continue
+ fp += _weighted_minutes(a - run_start, b - run_start)
+ focus_ms += int((b - a) * 1000)
+ return fp, focus_ms
+
+
+def focus_app_ids() -> set[int]:
+ rows = db.fetchall(
+ "SELECT DISTINCT r.app_id FROM reward_rules r JOIN apps a ON a.app_id = r.app_id "
+ "WHERE r.enabled = 1 AND a.is_hidden = 0"
+ )
+ return {r["app_id"] for r in rows}
+
+
+def load_spans(since: float, until: float, app_ids: set[int] | None = None) -> list[tuple[float, float]]:
+ """Focus-app sessions overlapping [since, until], clipped to it."""
+ app_ids = focus_app_ids() if app_ids is None else app_ids
+ if not app_ids:
+ return []
+ marks = ",".join("?" * len(app_ids))
+ rows = db.fetchall(
+ f"SELECT start_ts, end_ts FROM usage_sessions WHERE app_id IN ({marks}) "
+ "AND end_ts IS NOT NULL AND end_ts > ? AND start_ts < ? ORDER BY start_ts",
+ (*app_ids, since, until),
+ )
+ return [(max(r["start_ts"], since), min(r["end_ts"], until)) for r in rows]
+
+
+def grace_sec(tavern_level: int = 0) -> float:
+ return economy.FLOW_GRACE_SEC + economy.TAVERN_GRACE_SEC * tavern_level
+
+
+def points_between(since: float, until: float, tavern_level: int = 0) -> tuple[float, int]:
+ """Focus points earned in [since, until], reading sessions from the database."""
+ spans = load_spans(since - LOOKBACK_SEC, until)
+ return points(spans, grace_sec(tavern_level), since, until)
+
+
+def _day_start(ts: float) -> float:
+ d = datetime.fromtimestamp(ts)
+ return datetime(d.year, d.month, d.day).timestamp()
+
+
+def current(
+ now: float | None = None,
+ live_app_id: int | None = None,
+ live_since: float | None = None,
+ tavern_level: int = 0,
+) -> Flow:
+ """The flow state right now. *live_app_id*/*live_since* extend the stored sessions with
+ the session still in progress (the tracker writes it every 30 seconds)."""
+ now = now or time.time()
+ ids = focus_app_ids()
+ spans = load_spans(now - max(LOOKBACK_SEC, now - _day_start(now)), now, ids)
+ active = live_app_id in ids
+ if active and live_since is not None:
+ spans.append((live_since, now))
+ grace = grace_sec(tavern_level)
+ all_runs = runs(spans, grace)
+ today = _day_start(now)
+ today_ms = 0
+ for start, end in _merge(spans):
+ if end > today:
+ today_ms += int((end - max(start, today)) * 1000)
+ run = all_runs[-1] if all_runs else []
+ in_run = bool(run) and now - max(e for _s, e in run) <= grace
+ run_ms = int((min(now, max(e for _s, e in run)) - run[0][0]) * 1000) if run and in_run else 0
+ minutes = run_ms / 60000
+ index = economy.tier_index(minutes)
+ _start, mult, name = economy.FLOW_TIERS[index]
+ nxt = economy.FLOW_TIERS[index + 1] if index + 1 < len(economy.FLOW_TIERS) else None
+ return Flow(
+ active=active,
+ run_ms=run_ms,
+ multiplier=mult if in_run else 1.0,
+ tier=name if in_run else economy.FLOW_TIERS[0][2],
+ next_tier=nxt[2] if nxt else None,
+ next_in_ms=max(0, int(nxt[0] * 60000 - run_ms)) if nxt else 0,
+ today_focus_ms=today_ms,
+ )
+
+
+def _merge(spans: list[tuple[float, float]]) -> list[tuple[float, float]]:
+ out: list[tuple[float, float]] = []
+ for start, end in sorted(spans):
+ if out and start <= out[-1][1]:
+ out[-1] = (out[-1][0], max(out[-1][1], end))
+ else:
+ out.append((start, end))
+ return out
diff --git a/apptrackr/game/state.py b/apptrackr/game/state.py
index b2d6cbd..5e3ecd4 100644
--- a/apptrackr/game/state.py
+++ b/apptrackr/game/state.py
@@ -1,50 +1,90 @@
-"""Village: buildings, inventory and the credit market."""
+"""The focus village: buildings, production, harvests, the daily chest and the market.
+
+The village works while you focus: every focus point earned in a focus app
+produces resources at the rates its buildings set. Production waits in the
+harvest until you collect it, up to what storage can hold.
+"""
from __future__ import annotations
import json
+import time
+from datetime import date, datetime
from ..data import db
-from . import economy
+from . import economy, focus
+# cost: resources for level 1; each further level costs `growth` times more.
BUILDINGS = {
- "workshop": {
- "wood": 20,
- "stone": 10,
+ "lumberyard": {
+ "cost": {"wood": 15},
+ "growth": 1.55,
"unlock_level": 1,
- "max_level": 5,
- "desc": f"+{economy.WORKSHOP_XP_PCT}% XP from rewards per level",
+ "max_level": 30,
+ "desc": "Cuts wood while you focus",
+ },
+ "quarry": {
+ "cost": {"wood": 25},
+ "growth": 1.55,
+ "unlock_level": 1,
+ "max_level": 30,
+ "desc": "Breaks stone while you focus",
},
"storage": {
- "wood": 15,
- "stone": 15,
+ "cost": {"wood": 30, "stone": 20},
+ "growth": 1.6,
"unlock_level": 1,
- "max_level": 5,
- "desc": f"+{economy.STORAGE_CAP_PER_LEVEL} resource capacity per level",
+ "max_level": 20,
+ "desc": "Holds more of every resource",
},
- "house": {"wood": 25, "food": 10, "unlock_level": 2, "max_level": 5, "desc": "+1 villager per level"},
- "lab": {
- "stone": 20,
- "metal": 15,
- "blueprints": 1,
+ "farm": {
+ "cost": {"wood": 20, "stone": 10},
+ "growth": 1.55,
+ "unlock_level": 2,
+ "max_level": 30,
+ "desc": "Grows food while you focus",
+ },
+ "house": {
+ "cost": {"wood": 40, "food": 20},
+ "growth": 1.7,
+ "unlock_level": 2,
+ "max_level": 10,
+ "desc": f"Each villager adds {economy.VILLAGER_PCT}% to all production",
+ },
+ "workshop": {
+ "cost": {"wood": 30, "stone": 20},
+ "growth": 1.6,
+ "unlock_level": 2,
+ "max_level": 10,
+ "desc": f"+{economy.WORKSHOP_XP_PCT}% XP from focus per level",
+ },
+ "mine": {
+ "cost": {"wood": 40, "stone": 30},
+ "growth": 1.6,
"unlock_level": 3,
- "max_level": 3,
- "desc": f"+{economy.LAB_RESOURCE_PCT}% resources from rewards per level",
+ "max_level": 30,
+ "desc": "Digs metal while you focus",
},
- "tavern": {
- "wood": 30,
- "food": 20,
+ "lab": {
+ "cost": {"stone": 60, "metal": 25},
+ "growth": 1.8,
"unlock_level": 4,
- "max_level": 3,
- "desc": f"+{economy.TAVERN_STREAK_PCT}% streak rewards per level",
+ "max_level": 10,
+ "desc": "Draws blueprints while you focus",
},
- "monument": {
- "stone": 50,
- "metal": 30,
- "blueprints": 3,
+ "tavern": {
+ "cost": {"wood": 80, "food": 50},
+ "growth": 2.0,
"unlock_level": 5,
+ "max_level": 5,
+ "desc": f"Flow survives {economy.TAVERN_GRACE_SEC // 60} more minute away per level",
+ },
+ "monument": {
+ "cost": {"stone": 400, "metal": 200, "blueprints": 5},
+ "growth": 1.0,
+ "unlock_level": 10,
"max_level": 1,
- "desc": "Prestige crown on your profile",
+ "desc": f"A crown for your profile and +{economy.MONUMENT_PCT}% production",
},
}
@@ -54,6 +94,7 @@ def get_village() -> dict:
state = json.loads(row["state_json"]) if row else {}
state.setdefault("buildings", {})
state.setdefault("villagers", 0)
+ state.setdefault("chests", {})
inv = state.setdefault("inventory", {})
for r in economy.RESOURCES:
inv.setdefault(r, 0)
@@ -75,8 +116,8 @@ def resource_cap(village: dict | None = None) -> int:
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)}
+ factor = spec["growth"] ** current_level
+ return {r: int(round(amount * factor)) for r, amount in spec["cost"].items()}
def _player_level() -> int:
@@ -96,7 +137,11 @@ def can_build(name: str) -> tuple[bool, str]:
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]
+ cost = build_cost(name, level)
+ cap = resource_cap(village)
+ if any(need > cap for need in cost.values()):
+ return False, "Needs a bigger storage"
+ missing = [f"{need - inv.get(r, 0)} {r}" for r, need in cost.items() if inv.get(r, 0) < need]
if missing:
return False, "Need " + ", ".join(missing)
return True, "Ready"
@@ -115,8 +160,150 @@ def build_or_upgrade(name: str) -> tuple[bool, str]:
village["villagers"] = village.get("villagers", 0) + 1
save_village(village)
db.commit()
- verb = "built" if level == 0 else f"upgraded to level {level + 1}"
- return True, f"{name.title()} {verb}"
+ label = name.title() if name != "lumberyard" else "Lumberyard"
+ return True, f"{label} {'built' if level == 0 else f'upgraded to level {level + 1}'}"
+
+
+def get_bonuses(village: dict | None = None) -> dict:
+ village = village or get_village()
+ villagers = village.get("villagers", 0)
+ monument = building_level(village, "monument") >= 1
+ return {
+ "xp_bonus_pct": building_level(village, "workshop") * economy.WORKSHOP_XP_PCT,
+ "production_pct": villagers * economy.VILLAGER_PCT + (economy.MONUMENT_PCT if monument else 0),
+ "grace_sec": focus.grace_sec(building_level(village, "tavern")),
+ "resource_cap": resource_cap(village),
+ "villagers": villagers,
+ "has_monument": monument,
+ }
+
+
+def production_rates(village: dict | None = None) -> dict[str, float]:
+ """Resources produced per focus point."""
+ village = village or get_village()
+ boost = 1 + get_bonuses(village)["production_pct"] / 100
+ rates = {}
+ for res, (building, per_level, free) in economy.PRODUCTION.items():
+ level = building_level(village, building) + free
+ if level:
+ rates[res] = per_level * level * boost
+ return rates
+
+
+# ---------------------------------------------------------------------------
+# Harvest
+# ---------------------------------------------------------------------------
+
+
+def _start_of_today() -> float:
+ today = date.today()
+ return datetime(today.year, today.month, today.day).timestamp()
+
+
+def harvest(now: float | None = None, village: dict | None = None) -> dict:
+ """What collecting now would bring: focus since the last collection, turned into XP and resources."""
+ now = now or time.time()
+ village = village or get_village()
+ since = float(village.get("collected_until") or _start_of_today())
+ points, focus_ms = focus.points_between(since, now, building_level(village, "tavern"))
+ carry = village.get("carry", {})
+ cap = resource_cap(village)
+ resources, full = {}, []
+ for res, rate in production_rates(village).items():
+ made = points * rate + carry.get(res, 0.0)
+ room = max(0, cap - village["inventory"].get(res, 0))
+ amount = min(int(made), room)
+ if amount:
+ resources[res] = amount
+ if int(made) >= room and rate:
+ full.append(res)
+ xp = points * economy.XP_PER_POINT * (1 + get_bonuses(village)["xp_bonus_pct"] / 100)
+ return {
+ "since": since,
+ "until": now,
+ "focus_ms": focus_ms,
+ "points": points,
+ "xp": int(xp + carry.get("xp", 0.0)),
+ "resources": resources,
+ "full": full,
+ }
+
+
+def collect(now: float | None = None) -> dict:
+ """Bank the harvest. Returns what was applied (resources, xp, credits, level_up)."""
+ from ..rewards import engine
+
+ now = now or time.time()
+ village = get_village()
+ crop = harvest(now, village)
+ rates = production_rates(village)
+ carry = village.get("carry", {})
+ new_carry = {}
+ for res, rate in rates.items():
+ made = crop["points"] * rate + carry.get(res, 0.0)
+ if res not in crop["full"]:
+ new_carry[res] = made - int(made) # fractions roll over to the next harvest
+ for res, amount in crop["resources"].items():
+ village["inventory"][res] += amount
+ xp_made = crop["points"] * economy.XP_PER_POINT * (1 + get_bonuses(village)["xp_bonus_pct"] / 100)
+ new_carry["xp"] = xp_made + carry.get("xp", 0.0) - crop["xp"]
+ village["carry"] = new_carry
+ village["collected_until"] = now
+ save_village(village)
+ applied = dict(crop["resources"])
+ applied.update(engine.add_xp(crop["xp"]))
+ db.commit()
+ applied["points"] = crop["points"]
+ applied["focus_ms"] = crop["focus_ms"]
+ return applied
+
+
+# ---------------------------------------------------------------------------
+# Daily chest
+# ---------------------------------------------------------------------------
+
+
+def chest_state(day: str | None = None) -> str:
+ """'ready', 'claimed' or 'locked' for *day* (today by default)."""
+ day = day or date.today().isoformat()
+ return get_village().get("chests", {}).get(day, "locked")
+
+
+def unlock_chest(day: str) -> None:
+ village = get_village()
+ chests = village.setdefault("chests", {})
+ if chests.get(day) is None:
+ chests[day] = "ready"
+ # Keep a short history only.
+ for old in sorted(chests)[:-14]:
+ chests.pop(old, None)
+ save_village(village)
+ db.commit()
+
+
+def open_chest(day: str | None = None) -> dict | None:
+ """Open a ready chest. Returns what it held, or None."""
+ from ..rewards import engine
+
+ day = day or date.today().isoformat()
+ village = get_village()
+ if village.get("chests", {}).get(day) != "ready":
+ return None
+ reward = economy.chest_for(engine.get_profile()["streak"])
+ village["chests"][day] = "claimed"
+ save_village(village)
+ applied = engine.apply_reward(reward)
+ db.commit()
+ return applied
+
+
+def ready_chests() -> list[str]:
+ return sorted(day for day, status in get_village().get("chests", {}).items() if status == "ready")
+
+
+# ---------------------------------------------------------------------------
+# Market
+# ---------------------------------------------------------------------------
def buy(resource: str) -> tuple[bool, str]:
@@ -138,15 +325,3 @@ def buy(resource: str) -> tuple[bool, str]:
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:
- village = get_village()
- 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": building_level(village, "monument") >= 1,
- }
diff --git a/apptrackr/perspective.py b/apptrackr/perspective.py
index 8ef1054..77ae1b9 100644
--- a/apptrackr/perspective.py
+++ b/apptrackr/perspective.py
@@ -1,8 +1,10 @@
"""Tracked time, retold: "that's 2.4 Everest summit days".
Each yardstick is something people know, with the duration it takes and the
-basis for that number, which the UI shows next to the comparison. pick()
-chooses yardsticks that land in a readable range for a given total.
+basis for that number, which the UI shows next to the comparison. Only counts
+are shown (never "38% of a ..."), so a yardstick is a candidate only
+once the total covers at least one of it. pick() chooses yardsticks that land
+in a readable range for a given total.
"""
from __future__ import annotations
@@ -10,7 +12,13 @@
import math
from dataclasses import dataclass
+SECOND = 1 / 60
HOUR = 60 # yardsticks are in minutes
+DAY = 24 * HOUR
+
+BEST = (2, 30) # counts in this range read best
+SWEET = math.sqrt(BEST[0] * BEST[1]) # about 7.7, the middle of that range on a log scale
+VARIETY = 4 # places in line a pick gives up for each repeat of its group (twice that for its icon)
@dataclass(frozen=True)
@@ -18,150 +26,530 @@ class Yardstick:
key: str
minutes: float # one unit of the yardstick
many: str # label after a count: "4.2 Everest summit days"
- part: str # label after a percentage: "38% of the way to the Moon on Apollo 11"
basis: str # where the number comes from, shown under the comparison
icon: str
group: str # used to keep a set of picks varied
- max_count: float = 60 # above this the count stops meaning much
- one: str = "" # singular label when the count reads exactly 1
- times: bool = False # counts read as multiples: "2.5×"
+ max_count: float = 100_000 # from here on the count stops meaning much
+ one: str = "" # singular label when the count reads exactly 1; defaults to *many*
YARDSTICKS: tuple[Yardstick, ...] = (
+ # Everyday
+ Yardstick(
+ "typing",
+ 1.5 * SECOND,
+ "words typed",
+ "At an average 40 words a minute",
+ "keyboard",
+ "everyday",
+ max_count=10_000_000,
+ one="word typed",
+ ),
+ Yardstick(
+ "handwash",
+ 20 * SECOND,
+ "hand washes",
+ "The 20 s scrub health services advise",
+ "droplet",
+ "everyday",
+ one="hand wash",
+ ),
+ Yardstick(
+ "song",
+ 3.5,
+ "pop songs",
+ "An average hit runs about 3.5 min",
+ "music",
+ "everyday",
+ one="pop song",
+ ),
+ Yardstick(
+ "commute",
+ 27,
+ "commutes to work",
+ "The average US one-way trip: about 27 min",
+ "car",
+ "everyday",
+ one="commute to work",
+ ),
+ Yardstick(
+ "workday",
+ 8 * HOUR,
+ "working days",
+ "A standard 8-hour day",
+ "briefcase",
+ "everyday",
+ one="working day",
+ ),
+ Yardstick(
+ "workweek",
+ 40 * HOUR,
+ "work weeks",
+ "Five 8-hour days",
+ "calendar-days",
+ "everyday",
+ one="work week",
+ ),
+ Yardstick(
+ "workyear",
+ 46 * 40 * HOUR,
+ "working years",
+ "46 weeks of 40 h, after holidays",
+ "briefcase",
+ "everyday",
+ one="working year",
+ ),
+ # Food
+ Yardstick(
+ "espresso",
+ 27.5 * SECOND,
+ "espresso shots",
+ "Pulled in about 25 to 30 s",
+ "cup",
+ "food",
+ one="espresso shot",
+ ),
+ Yardstick(
+ "pizza",
+ 1.5,
+ "Neapolitan pizzas baked",
+ "About 90 s in a wood-fired oven",
+ "flame",
+ "food",
+ one="Neapolitan pizza baked",
+ ),
+ Yardstick(
+ "noodles",
+ 3,
+ "cups of instant noodles",
+ "The classic 3-minute wait",
+ "cup",
+ "food",
+ one="cup of instant noodles",
+ ),
+ Yardstick(
+ "tea",
+ 4,
+ "cups of tea brewed",
+ "Black tea steeps for about 4 min",
+ "cup",
+ "food",
+ one="cup of tea brewed",
+ ),
+ Yardstick(
+ "egg",
+ 6,
+ "soft-boiled eggs",
+ "About 6 min in boiling water",
+ "hourglass",
+ "food",
+ one="soft-boiled egg",
+ ),
+ Yardstick(
+ "bread",
+ 40,
+ "loaves of bread baked",
+ "About 40 min in a hot oven",
+ "wheat",
+ "food",
+ one="loaf of bread baked",
+ ),
+ # Culture
+ Yardstick(
+ "trailer",
+ 2.5,
+ "film trailers",
+ "Trailers usually run up to 2 min 30 s",
+ "play",
+ "culture",
+ one="film trailer",
+ ),
+ Yardstick(
+ "bohemian",
+ 5 + 55 / 60,
+ "plays of Bohemian Rhapsody",
+ "Queen, 1975: 5 min 55 s",
+ "music",
+ "culture",
+ one="play of Bohemian Rhapsody",
+ ),
+ Yardstick(
+ "ted",
+ 18,
+ "TED talks",
+ "Talks are capped at 18 min",
+ "languages",
+ "culture",
+ one="TED talk",
+ ),
+ Yardstick(
+ "sitcom",
+ 22,
+ "sitcom episodes",
+ "About 22 min without the ads",
+ "monitor",
+ "culture",
+ one="sitcom episode",
+ ),
+ Yardstick(
+ "beethoven",
+ 70,
+ "Beethoven's Ninths",
+ "His last symphony runs about 70 min",
+ "music",
+ "culture",
+ one="Beethoven's Ninth",
+ ),
+ Yardstick(
+ "film",
+ 2 * HOUR,
+ "feature films",
+ "About 2 h, a typical running time",
+ "clapperboard",
+ "culture",
+ one="feature film",
+ ),
+ Yardstick(
+ "titanic",
+ 3 * HOUR + 14,
+ "screenings of Titanic",
+ "James Cameron, 1997: 3 h 14 m",
+ "clapperboard",
+ "culture",
+ one="screening of Titanic",
+ ),
+ Yardstick(
+ "ring",
+ 15 * HOUR,
+ "Ring cycles",
+ "Wagner's four operas: about 15 h",
+ "castle",
+ "culture",
+ one="Ring cycle",
+ ),
+ Yardstick(
+ "friends",
+ 236 * 22,
+ "box sets of Friends",
+ "All 236 episodes at about 22 min",
+ "monitor",
+ "culture",
+ one="box set of Friends",
+ ),
+ Yardstick(
+ "fogg",
+ 80 * DAY,
+ "trips around the world with Phileas Fogg",
+ "Jules Verne's 80 days",
+ "globe",
+ "culture",
+ one="trip around the world with Phileas Fogg",
+ ),
+ # Sport
+ Yardstick(
+ "bolt",
+ 9.58 * SECOND,
+ "Usain Bolt 100 m sprints",
+ "The world record, Berlin 2009: 9.58 s",
+ "zap",
+ "sport",
+ max_count=10_000_000,
+ one="Usain Bolt 100 m sprint",
+ ),
+ Yardstick(
+ "boxing",
+ 3,
+ "boxing rounds",
+ "A professional round lasts 3 min",
+ "bell",
+ "sport",
+ one="boxing round",
+ ),
+ Yardstick(
+ "football",
+ 90,
+ "football matches",
+ "Two 45-minute halves",
+ "ball",
+ "sport",
+ one="football match",
+ ),
+ Yardstick(
+ "record",
+ 2 * HOUR + 35 / 60,
+ "world-record marathons",
+ "Kelvin Kiptum, Chicago 2023: 2:00:35",
+ "timer",
+ "sport",
+ one="world-record marathon",
+ ),
+ Yardstick(
+ "marathon",
+ 4 * HOUR + 30,
+ "marathons at an everyday pace",
+ "A typical finishing time: about 4 h 30 m",
+ "footprints",
+ "sport",
+ one="marathon at an everyday pace",
+ ),
+ Yardstick(
+ "tennis",
+ 11 * HOUR + 5,
+ "record tennis matches",
+ "Isner v Mahut, Wimbledon 2010: 11 h 5 m",
+ "tennis",
+ "sport",
+ one="record tennis match",
+ ),
+ Yardstick(
+ "lemans",
+ 24 * HOUR,
+ "Le Mans 24-hour races",
+ "Cars race nonstop for 24 h",
+ "car",
+ "sport",
+ one="Le Mans 24-hour race",
+ ),
+ Yardstick(
+ "tour",
+ 80 * HOUR,
+ "Tours de France at the winner's pace",
+ "Three weeks of racing: about 80 h in the saddle",
+ "bike",
+ "sport",
+ one="Tour de France at the winner's pace",
+ ),
+ # Travel and adventure
+ Yardstick(
+ "metres",
+ 12 / 1000,
+ "m walked",
+ "At an easy 5 km/h",
+ "footprints",
+ "travel",
+ max_count=1000, # from there on it reads as km walked
+ ),
+ Yardstick(
+ "walk",
+ 12,
+ "km walked",
+ "At an easy 5 km/h, without stopping",
+ "footprints",
+ "travel",
+ max_count=1_000_000,
+ ),
+ Yardstick(
+ "eurostar",
+ 2 * HOUR + 20,
+ "Eurostar trips from London to Paris",
+ "St Pancras to Gare du Nord: about 2 h 20 m",
+ "train",
+ "travel",
+ one="Eurostar trip from London to Paris",
+ ),
+ Yardstick(
+ "flight",
+ 8 * HOUR,
+ "flights from London to New York",
+ "About 8 h in the air",
+ "plane",
+ "travel",
+ one="flight from London to New York",
+ ),
Yardstick(
"everest",
14 * HOUR,
"Everest summit days",
- "of an Everest summit day",
"South Col to the summit and back down: about 14 h",
"mountain",
- "adventure",
+ "travel",
one="Everest summit day",
),
Yardstick(
- "apollo",
- 102 * HOUR + 45,
- "trips to the Moon on Apollo 11",
- "of the way to the Moon on Apollo 11",
- "Launch to lunar landing, July 1969: 102 h 45 m",
- "moon",
+ "drive",
+ 41 * HOUR,
+ "drives from New York to Los Angeles",
+ "About 2,800 miles: 41 h at the wheel",
+ "car",
+ "travel",
+ one="drive from New York to Los Angeles",
+ ),
+ Yardstick(
+ "siberia",
+ 6 * DAY,
+ "Trans-Siberian train journeys",
+ "Moscow to Vladivostok, 9,289 km: about 6 days",
+ "train",
+ "travel",
+ one="Trans-Siberian train journey",
+ ),
+ # Space
+ Yardstick(
+ "lightlap",
+ 40075 / 299792.458 * SECOND,
+ "laps of Earth at light speed",
+ "Light could circle the equator 7.5 times a second",
+ "globe",
"space",
- one="trip to the Moon on Apollo 11",
+ max_count=10_000_000,
+ one="lap of Earth at light speed",
+ ),
+ Yardstick(
+ "sunlight",
+ 8 + 19 / 60,
+ "trips by sunlight to Earth",
+ "Light from the Sun takes 8 min 19 s to reach us",
+ "sun",
+ "space",
+ one="trip by sunlight to Earth",
+ ),
+ Yardstick(
+ "shuttle",
+ 8.5,
+ "Space Shuttle climbs to orbit",
+ "Launch to main engine cutoff: about 8.5 min",
+ "rocket",
+ "space",
+ one="Space Shuttle climb to orbit",
),
Yardstick(
"iss",
92.9,
"laps of Earth by the ISS",
- "of a lap of Earth by the ISS",
- "The space station circles the planet every 93 minutes",
+ "The space station circles the planet every 93 min",
"orbit",
"space",
- max_count=200,
one="lap of Earth by the ISS",
),
Yardstick(
- "sunlight",
- 8 + 19 / 60,
- "trips by sunlight from the Sun to Earth",
- "of sunlight's trip to Earth",
- "Light from the Sun takes 8 min 19 s to reach us",
- "sun",
+ "mars",
+ 24 * HOUR + 39 + 35 / 60,
+ "days on Mars",
+ "A Martian day, or sol: 24 h 40 m",
+ "planet",
"space",
- max_count=400,
- one="trip by sunlight from the Sun to Earth",
+ one="day on Mars",
),
Yardstick(
- "marathon",
- 4 * HOUR + 30,
- "marathons at an everyday pace",
- "of a marathon at an everyday pace",
- "A typical finishing time: about 4 h 30 m",
- "footprints",
- "sport",
- one="marathon at an everyday pace",
+ "apollo",
+ 102 * HOUR + 45,
+ "trips to the Moon on Apollo 11",
+ "Launch to lunar landing, July 1969: 102 h 45 m",
+ "moon",
+ "space",
+ one="trip to the Moon on Apollo 11",
),
Yardstick(
- "record",
- 2 * HOUR + 35 / 60,
- "world-record marathons",
- "of the marathon world record",
- "Kelvin Kiptum, Chicago 2023: 2:00:35",
- "timer",
- "sport",
- one="world-record marathon",
+ "voyager",
+ 1e6 / (16.9 * 60),
+ "million km flown by Voyager 1",
+ "The probe leaves the Sun behind at about 16.9 km/s",
+ "rocket",
+ "space",
+ max_count=2000,
),
Yardstick(
- "walk",
- 12,
- "km walked",
- "of a kilometre on foot",
- "At an easy 5 km/h, without stopping",
- "footprints",
- "everyday",
- max_count=20000,
+ "mercury",
+ 88 * DAY,
+ "years on Mercury",
+ "Mercury circles the Sun every 88 days",
+ "planet",
+ "space",
+ one="year on Mercury",
+ ),
+ # Learning
+ Yardstick(
+ "pages",
+ 300 / 238,
+ "book pages read",
+ "About 300 words each at 238 words a minute",
+ "scroll",
+ "learning",
+ one="book page read",
+ ),
+ Yardstick(
+ "lecture",
+ 50,
+ "university lectures",
+ "A standard 50-minute class",
+ "landmark",
+ "learning",
+ one="university lecture",
),
Yardstick(
"novel",
90000 / 238,
"novels read",
- "of a novel",
"90,000 words at an average 238 words a minute",
"book",
"learning",
one="novel read",
),
Yardstick(
- "flight",
- 8 * HOUR,
- "flights from London to New York",
- "of a flight from London to New York",
- "About 8 h in the air",
- "plane",
- "travel",
- one="flight from London to New York",
+ "driving",
+ 45 * HOUR,
+ "driving courses",
+ "UK learners take about 45 h of lessons to pass",
+ "steering-wheel",
+ "learning",
+ one="driving course",
),
Yardstick(
"language",
600 * HOUR,
- "the class hours to learn French or Spanish",
- "of the class hours to learn French or Spanish",
- "The US Foreign Service Institute's estimate: about 600 h",
+ "French courses",
+ "US diplomats' training estimate: about 600 class hours",
"languages",
"learning",
- max_count=10,
- times=True,
+ one="French course",
),
Yardstick(
"mastery",
10000 * HOUR,
- "the 10,000 hours said to make an expert",
- "of the 10,000 hours said to make an expert",
- "The rule of thumb Malcolm Gladwell made famous",
+ "paths to mastery",
+ "The 10,000-hour rule Malcolm Gladwell made famous",
"trophy",
"learning",
- max_count=5,
- times=True,
+ one="path to mastery",
),
+ # Body
Yardstick(
- "moonwalk",
- 384400 * 12,
- "walks to the Moon",
- "of a walk to the Moon",
- "384,400 km at 5 km/h, no breaks",
+ "heartbeats",
+ 1 / 70,
+ "heartbeats",
+ "At a resting 70 beats a minute",
+ "activity",
+ "body",
+ max_count=10_000_000,
+ one="heartbeat",
+ ),
+ Yardstick(
+ "breaths",
+ 1 / 15,
+ "breaths",
+ "About 15 a minute at rest",
+ "wind",
+ "body",
+ max_count=10_000_000,
+ one="breath",
+ ),
+ Yardstick(
+ "nap",
+ 20,
+ "power naps",
+ "The classic 20-minute nap",
"moon",
- "adventure",
- max_count=5,
- one="walk to the Moon",
+ "body",
+ one="power nap",
),
Yardstick(
- "voyager",
- 1e6 / (16.9 * 60),
- "million km covered by Voyager 1",
- "covered at Voyager 1's speed",
- "The probe leaves the Sun behind at about 16.9 km/s",
- "rocket",
- "space",
- max_count=2000,
+ "sleep",
+ 8 * HOUR,
+ "nights of sleep",
+ "8 h, the middle of the advised 7 to 9",
+ "moon",
+ "body",
+ one="night of sleep",
),
)
@@ -169,76 +557,82 @@ class Yardstick:
@dataclass(frozen=True)
class Fact:
key: str
- value: str # "4.2" or "38%"
+ value: str # "4.2", "1,234" or "1.2 million"
label: str # "Everest summit days"
basis: str
icon: str
ratio: float
-def _count(ratio: float) -> str:
- if ratio < 10:
- text = f"{ratio:.1f}"
+def _number(x: float) -> str:
+ if x < 10:
+ text = f"{x:.1f}"
return text[:-2] if text.endswith(".0") else text
- return f"{ratio:,.0f}"
+ return f"{x:,.0f}"
-def _percent(ratio: float) -> str:
- pct = ratio * 100
- if pct < 0.1:
- return "<0.1%"
- return f"{pct:.1f}%" if pct < 10 else f"{pct:.0f}%"
+def _count(ratio: float) -> str:
+ """2.4, 12, 1,234, 1.2 million."""
+ if round(ratio) >= 1_000_000:
+ return _number(ratio / 1_000_000) + " million"
+ return _number(ratio)
def describe(minutes: float, stick: Yardstick) -> Fact:
"""*minutes* of tracked time measured against one yardstick."""
ratio = minutes / stick.minutes
- if stick.key == "walk" and ratio < 1:
- return Fact(stick.key, f"{ratio * 1000:,.0f} m", "walked", stick.basis, stick.icon, ratio)
- if stick.key == "voyager" and ratio < 1:
- km = ratio * 1e6
- km = round(km, -max(0, len(str(int(km))) - 3)) # three significant figures; the speed is approximate
- return Fact(stick.key, f"{km:,.0f} km", "covered at Voyager 1's speed", stick.basis, stick.icon, ratio)
- if ratio >= 1:
- value = _count(ratio)
- if stick.times:
- return Fact(stick.key, value + "×", stick.many, stick.basis, stick.icon, ratio)
- label = stick.one if value == "1" and stick.one else stick.many
- return Fact(stick.key, value, label, stick.basis, stick.icon, ratio)
- return Fact(stick.key, _percent(ratio), stick.part, stick.basis, stick.icon, ratio)
+ value = _count(ratio)
+ label = stick.one if value == "1" and stick.one else stick.many
+ return Fact(stick.key, value, label, stick.basis, stick.icon, ratio)
def _score(minutes: float, stick: Yardstick) -> float | None:
- """Lower reads better. None when the comparison would be too tiny or too large to mean much."""
+ """Lower reads better. None when the total is under one of the thing, or too many to mean much."""
ratio = minutes / stick.minutes
- if ratio > stick.max_count or ratio < 0.02:
+ if ratio < 1 or ratio >= stick.max_count:
return None
- if ratio >= 1:
- return abs(math.log10(ratio) - math.log10(4)) # small whole-ish counts read best
- return abs(math.log10(ratio) - math.log10(0.4)) + 0.35 # "40% of the way" is fun, but counts first
+ score = 0.5 * abs(math.log10(ratio / SWEET)) # a gentle lean towards the middle of the range
+ score += max(0.0, math.log10(BEST[0] / ratio)) # "1.1 Ring cycles" is fine, just less fun
+ score += max(0.0, math.log10(ratio / BEST[1])) # big counts mostly turn up on shuffle
+ return score
+
+
+def _ranked(minutes: float) -> list[Yardstick]:
+ scored = [(s, stick) for stick in YARDSTICKS if (s := _score(minutes, stick)) is not None]
+ scored.sort(key=lambda item: (item[0], item[1].key))
+ return [stick for _, stick in scored]
def pick(minutes: float, count: int = 3, offset: int = 0) -> list[Fact]:
- """Up to *count* comparisons for *minutes*, varied across groups.
+ """Up to *count* comparisons for *minutes*, best first and varied across groups.
*offset* rotates through the readable candidates (the Shuffle button).
"""
- if minutes <= 0:
+ if minutes <= 0 or count <= 0:
return []
- scored = [(s, stick) for stick in YARDSTICKS if (s := _score(minutes, stick)) is not None]
- scored.sort(key=lambda item: (item[0], item[1].key))
- ranked = [stick for _, stick in scored]
+ ranked = _ranked(minutes)
if not ranked:
return []
- start = (offset * count) % len(ranked)
- ranked = ranked[start:] + ranked[:start]
+ # Each press moves on by about *count*; a stride with no factor in common with the number of
+ # candidates lets each of them lead a set (leaders are always shown) within that many presses.
+ n = len(ranked)
+ step = min((s for s in range(1, count + n) if math.gcd(s, n) == 1), key=lambda s: (abs(s - count), -s))
+ start = (offset * step) % n
+ order = ranked[start:] + ranked[:start]
+ # For variety a set may borrow from the next one in line, but never from the one before it
+ # (the end of the rotation), so every shuffle brings something new.
+ window = order[: max(count, min(count * 2, n - step))]
chosen: list[Yardstick] = []
- for stick in ranked: # first pass: one per group
- if len(chosen) < count and all(stick.group != c.group for c in chosen):
- chosen.append(stick)
- for stick in ranked: # then fill from what is left
- if len(chosen) < count and stick not in chosen:
- chosen.append(stick)
+
+ def cost(item: tuple[int, Yardstick]) -> float:
+ # Place in line, plus a few places for repeating a group and more for repeating an icon.
+ place, stick = item
+ repeats = sum(stick.group == c.group for c in chosen)
+ return place + VARIETY * repeats + 2 * VARIETY * any(stick.icon == c.icon for c in chosen)
+
+ while len(chosen) < min(count, len(window)):
+ chosen.append(min(((i, s) for i, s in enumerate(window) if s not in chosen), key=cost)[1])
+ chosen.sort(key=order.index)
return [describe(minutes, stick) for stick in chosen]
diff --git a/apptrackr/rewards/engine.py b/apptrackr/rewards/engine.py
index 0726b23..eb4da85 100644
--- a/apptrackr/rewards/engine.py
+++ b/apptrackr/rewards/engine.py
@@ -1,10 +1,14 @@
-"""Reward evaluation: milestones per app, claiming, levels and streaks."""
+"""Progress: XP and levels, the daily focus goal and streak, and rewards from 1.x.
+
+Focus points are earned in game.focus and banked by game.state.collect; this
+module owns the profile they feed. Milestone rewards granted by AppTrackr 1.0
+and 1.1 stay claimable here; no new ones are created.
+"""
from __future__ import annotations
import json
import logging
-import time
from datetime import date, timedelta
from ..data import catalog, db
@@ -18,172 +22,76 @@ def enabled() -> bool:
return db.get_bool("rewards_enabled", True)
-def evaluate(day: str | None = None) -> list[dict]:
- """Grant rewards for milestones reached on *day*. Returns the new grants."""
- if not enabled():
- return []
- 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:
- metric = rule["metric"]
- if metric not in ("focused_ms", "opens_count", "clicks_count"):
- continue
- row = db.fetchone(
- f"SELECT {metric} AS val FROM daily_rollup WHERE day = ? AND app_id = ?",
- (day, rule["app_id"]),
- )
- value = row["val"] if row else 0
- if value < rule["threshold"]:
- continue
- if rule["repeatable"]:
- earned = value // rule["threshold"]
- done = db.fetchone(
- "SELECT COUNT(*) AS n FROM reward_events WHERE rule_id = ? AND day = ?",
- (rule["rule_id"], day),
- )["n"]
- count = earned - done
- else:
- 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(), 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"])}
- )
- 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, 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"
- )
- 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
+# ---------------------------------------------------------------------------
+# Profile, XP and levels
+# ---------------------------------------------------------------------------
-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 = {}
+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
- 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)
+def add_xp(xp: int, credits: int = 0) -> dict:
+ """Add XP (and credits); level-ups pay credits too. Returns what was applied. Caller commits."""
profile = get_profile()
- credits = int(reward.get("credits", 0))
- new_xp = profile["xp"] + xp
+ new_xp = profile["xp"] + max(0, int(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),
)
+ applied: dict = {}
+ if xp:
+ applied["xp"] = int(xp)
+ if credits:
+ applied["credits"] = credits
+ if new_level > profile["level"]:
+ applied["level_up"] = new_level
return applied
-def claim_reward(event_id: int) -> dict | None:
- row = db.fetchone("SELECT * FROM reward_events WHERE event_id = ? AND claimed = 0", (event_id,))
- if not row:
- return None
- applied = _apply(json.loads(row["granted_json"]))
- db.execute("UPDATE reward_events SET claimed = 1 WHERE event_id = ?", (event_id,))
- db.commit()
+def apply_reward(reward: dict) -> dict:
+ """Add a reward of XP, credits and resources (resources up to storage). Caller commits."""
+ village = game_state.get_village()
+ cap = game_state.resource_cap(village)
+ applied: dict = {}
+ for res in economy.RESOURCES:
+ amount = int(reward.get(res, 0))
+ if not amount:
+ continue
+ before = village["inventory"].get(res, 0)
+ village["inventory"][res] = max(before, min(cap, before + amount))
+ if village["inventory"][res] > before:
+ applied[res] = village["inventory"][res] - before
+ game_state.save_village(village)
+ applied.update(add_xp(int(reward.get("xp", 0)), int(reward.get("credits", 0))))
return applied
-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
-
-
# ---------------------------------------------------------------------------
-# Profile and streaks
+# Daily focus goal and streak
# ---------------------------------------------------------------------------
-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 goal_ms() -> int:
+ minutes = db.get_int("focus_goal_min", economy.DEFAULT_GOAL_MIN)
+ return max(5, minutes) * 60_000
+
+
+def focus_ms(day: str) -> int:
+ """Time in focus apps on *day* (from the daily totals)."""
+ row = db.fetchone(
+ "SELECT COALESCE(SUM(d.focused_ms), 0) AS total FROM daily_rollup d "
+ "WHERE d.day = ? AND d.app_id IN (SELECT DISTINCT r.app_id FROM reward_rules r "
+ "JOIN apps a ON a.app_id = r.app_id WHERE r.enabled = 1 AND a.is_hidden = 0)",
+ (day,),
+ )
+ return row["total"] if row else 0
def current_streak(profile: dict) -> int:
@@ -197,80 +105,84 @@ def current_streak(profile: dict) -> int:
return 0
-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 AND a.is_hidden = 0",
- (day,),
- )
- return row["total"] if row else 0
-
-
def update_streak(extra_ms: int = 0) -> dict | None:
- """Extend the streak once today's favorite-app goal is met.
+ """Count today toward the streak once the focus goal is met, and unlock today's chest.
- Returns {"streak": n, "reward": {...}} when the streak grew, else None.
+ *extra_ms* is live focus time not yet saved. Returns {"streak": n} 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:
+ if focus_ms(today) + extra_ms < goal_ms():
return None
streak = profile["streak"] + 1
db.execute(
"UPDATE player_profile SET streak_days = ?, last_streak_day = ? WHERE profile_id = 1",
(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 result
+ if enabled():
+ game_state.unlock_chest(today)
+ return {"streak": streak}
# ---------------------------------------------------------------------------
-# Progress toward the next milestone
+# Rewards granted by 1.0 and 1.1 (milestones); claimable, never created again
# ---------------------------------------------------------------------------
-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()
+def unclaimed_rewards() -> list[dict]:
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,),
+ "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"
)
- by_app: dict[int, dict] = {}
+ out = []
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())
+ item = dict(r)
+ item["name"] = catalog.display_name(item)
+ item["reward"] = json.loads(item["granted_json"])
+ out.append(item)
+ return out
+
+
+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 claim_reward(event_id: int) -> dict | None:
+ row = db.fetchone("SELECT * FROM reward_events WHERE event_id = ? AND claimed = 0", (event_id,))
+ if not row:
+ return None
+ applied = apply_reward(json.loads(row["granted_json"]))
+ db.execute("UPDATE reward_events SET claimed = 1 WHERE event_id = ?", (event_id,))
+ db.commit()
+ return applied
+
+
+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 attention_count() -> int:
+ """Things waiting for the player: a chest to open, a harvest to collect, old rewards."""
+ if not enabled():
+ return 0
+ count = len(game_state.ready_chests()) + unclaimed_count()
+ if sum(game_state.harvest()["resources"].values()) >= 10:
+ count += 1
+ return count
diff --git a/apptrackr/rewards/rules.py b/apptrackr/rewards/rules.py
index 5efd698..590eca8 100644
--- a/apptrackr/rewards/rules.py
+++ b/apptrackr/rewards/rules.py
@@ -1,4 +1,4 @@
-"""Per-app reward rules."""
+"""Per-app reward rules. An app with enabled rules is a focus app."""
from __future__ import annotations
@@ -47,3 +47,21 @@ def app_rewards_enabled(app_id: int) -> bool:
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")}
+
+
+def adopt_favorites_once() -> int:
+ """On the first start of 1.2: with no focus apps chosen yet, favorites become focus apps.
+
+ Favorites drove the streak before 1.2; this keeps a streak growing after the
+ update. Runs once; returns how many apps were adopted.
+ """
+ if db.get_bool("focus_apps_adopted"):
+ return 0
+ adopted = 0
+ if not earning_app_ids():
+ rows = db.fetchall("SELECT app_id FROM apps WHERE is_favorite = 1 AND is_hidden = 0")
+ for row in rows:
+ enable_app_rewards(row["app_id"], True)
+ adopted = len(rows)
+ db.set_setting("focus_apps_adopted", True)
+ return adopted
diff --git a/apptrackr/ui/fmt.py b/apptrackr/ui/fmt.py
index 00aa90c..e3495e8 100644
--- a/apptrackr/ui/fmt.py
+++ b/apptrackr/ui/fmt.py
@@ -83,11 +83,19 @@ def time_of_day(ts: float) -> str:
return dt.strftime("%H:%M")
+def amount(n: int, key: str) -> str:
+ """'1 blueprint', '25 wood', '3 credits'."""
+ name = RESOURCE_LABELS.get(key, key)
+ if n == 1 and name.endswith("s"):
+ name = name[:-1]
+ return f"{n:,} {name}"
+
+
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]}")
+ parts.append(f"+{amount(reward[key], key)}")
if reward.get("level_up"):
parts.append(f"Level {reward['level_up']}")
return sep.join(parts)
diff --git a/apptrackr/ui/main.py b/apptrackr/ui/main.py
index ac3df34..4a284ab 100644
--- a/apptrackr/ui/main.py
+++ b/apptrackr/ui/main.py
@@ -31,9 +31,12 @@
from ..core import tracker as trk
from ..core.limits import LimitMonitor
from ..data import db, queries
+from ..game import focus
+from ..game import state as game_state
from ..rewards import engine as rewards
from ..updater import check as updater
from . import fmt, fonts, icons, motion, theme
+from .overlay import FloatingTimer
from .signals import bus, run_async
from .widgets.components import Badge, IconBinding, StatusModule, Toast, label
@@ -44,7 +47,7 @@
("dashboard", "Dashboard", "layout-dashboard"),
("calendar", "Calendar", "calendar-days"),
("apps", "Apps", "layout-grid"),
- ("rewards", "Rewards", "gift"),
+ ("rewards", "Focus", "zap"),
("village", "Village", "castle"),
)
@@ -96,6 +99,11 @@ def __init__(self, tracker, clicks=None, demo: bool = False):
self._build()
self._setup_tray()
self._setup_shortcuts()
+ self._overlay = FloatingTimer()
+ self._overlay.open_requested.connect(self.bring_to_front)
+ self._overlay.hide_requested.connect(lambda: self.set_overlay_enabled(False))
+ self._overlay_enabled = db.get_bool("overlay_enabled", True)
+ self.destroyed.connect(self._overlay.deleteLater) # a separate top-level window, not a child
self.toast = Toast(self.centralWidget())
bus.toast.connect(lambda text, tone: self.toast.show_message(text, tone))
bus.rewards_changed.connect(self._update_badges)
@@ -352,7 +360,7 @@ def apply_rewards_visibility(self) -> None:
self._update_badges()
def _update_badges(self) -> None:
- self._badges["rewards"].set_count(rewards.unclaimed_count() if rewards.enabled() else 0)
+ self._badges["rewards"].set_count(rewards.attention_count())
self._place_nav_extras("rewards", self._nav_buttons["rewards"])
# ------------------------------------------------------------------
@@ -451,27 +459,56 @@ def _refresh_status(self) -> None:
def _tick(self) -> None:
self._refresh_status()
+ self._update_overlay()
if self.isVisible() and not self.isMinimized():
view = self._views[self._current]
if hasattr(view, "tick"):
view.tick()
+ # ------------------------------------------------------------------
+ # Floating timer
+ # ------------------------------------------------------------------
+
+ def set_overlay_enabled(self, on: bool) -> None:
+ db.set_setting("overlay_enabled", on)
+ self._overlay_enabled = on
+ self._update_overlay()
+
+ def _app_in_front(self) -> bool:
+ return QApplication.activeWindow() is not None
+
+ def _update_overlay(self) -> None:
+ """Show the floating timer while another app is being tracked, hide it otherwise."""
+ if self._quitting:
+ return
+ snap = self._tracker.snapshot()
+ tracking = snap.status == trk.STATUS_TRACKING and snap.app_id is not None
+ if not (self._overlay_enabled and tracking) or self._app_in_front() or self._tracker.foreground_fullscreen():
+ self._overlay.disappear()
+ return
+ app = queries.get_app(snap.app_id)
+ flow = None
+ if rewards.enabled() and snap.app_id in focus.focus_app_ids():
+ tavern = game_state.building_level(game_state.get_village(), "tavern")
+ flow = focus.current(live_app_id=snap.app_id, live_since=snap.session_start, tavern_level=tavern)
+ today = queries.app_usage_on(queries.today_str(), snap.app_id) + snap.uncommitted_ms
+ self._overlay.set_state(app["name"] if app else snap.exe_name, snap.session_ms, today, flow)
+ self._overlay.appear()
+
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)
+ focus_live = snap.uncommitted_ms if snap.app_id in focus.focus_app_ids() else 0
+ streak = rewards.update_streak(extra_ms=focus_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, kind="streaks")
+ days = streak["streak"]
+ msg = f"Daily focus goal reached. Streak: {days} day{'s' if days != 1 else ''}."
+ if rewards.enabled():
+ msg += " Your chest is ready."
+ self.notify("Focus goal", msg, kind="streaks")
bus.rewards_changed.emit()
+ else:
+ self._update_badges()
for app in self._limits.check(snap.app_id, snap.uncommitted_ms):
self.notify(
"Daily limit reached",
@@ -541,6 +578,7 @@ def bring_to_front(self) -> None:
def quit(self) -> None:
self._quitting = True
+ self._overlay.hide()
if self._tray:
self._tray.hide()
QApplication.quit()
diff --git a/apptrackr/ui/overlay.py b/apptrackr/ui/overlay.py
new file mode 100644
index 0000000..d1882ad
--- /dev/null
+++ b/apptrackr/ui/overlay.py
@@ -0,0 +1,206 @@
+"""Floating timer: a small always-on-top clock for the app in front.
+
+It never takes focus, so the app being timed stays the foreground app. Drag it
+anywhere (the spot is remembered), double-click it to open AppTrackr, or
+right-click to hide it.
+"""
+
+from __future__ import annotations
+
+from PySide6.QtCore import QPoint, QPointF, QRectF, Qt, Signal
+from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPainterPath, QPen
+from PySide6.QtWidgets import QMenu, QWidget
+
+from .. import APP_NAME
+from ..data import db
+from ..game import economy
+from . import fmt, fonts, motion, theme
+
+OPACITY = 0.94
+MARGIN = 24
+
+
+class FloatingTimer(QWidget):
+ open_requested = Signal()
+ hide_requested = Signal()
+
+ W, H = 224, 52
+
+ def __init__(self, parent=None):
+ flags = (
+ Qt.WindowType.Tool
+ | Qt.WindowType.FramelessWindowHint
+ | Qt.WindowType.WindowStaysOnTopHint
+ | Qt.WindowType.WindowDoesNotAcceptFocus
+ )
+ super().__init__(parent, flags)
+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
+ self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
+ self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
+ self.setFixedSize(self.W, self.H)
+ self.setCursor(Qt.CursorShape.OpenHandCursor)
+ self.setWindowTitle(f"{APP_NAME} timer")
+ self.setToolTip("Drag to move. Double-click to open AppTrackr.")
+ self._name = ""
+ self._session_ms = 0
+ self._detail = ""
+ self._progress: float | None = None # toward the next flow tier, focus apps only
+ self._focus = False
+ self._drag: QPoint | None = None
+ self._leaving = False
+ self._placed = False
+ self._multiplier: float | None = None
+ self._glow = 0.0 # accent ring after reaching a new flow tier
+
+ # -- state ---------------------------------------------------------------
+
+ def set_state(self, name: str, session_ms: int, today_ms: int, flow=None) -> None:
+ """Show *name* and how long it has been in front. *flow* is a game.focus.Flow for focus apps."""
+ self._name = name
+ self._session_ms = session_ms
+ self._focus = flow is not None and flow.active
+ if self._focus:
+ if self._multiplier is not None and flow.multiplier > self._multiplier:
+ motion.tween(self, 1.0, 0.0, 1600, self._set_glow, motion.DECELERATE, key="glow")
+ self._multiplier = flow.multiplier
+ self._detail = f"×{flow.multiplier:g} {flow.tier.upper()}"
+ self._progress = _tier_progress(flow.run_ms) if flow.next_tier else 1.0
+ else:
+ self._multiplier = None
+ self._detail = f"TODAY {fmt.duration(today_ms, short=True).upper()}"
+ self._progress = None
+ self.update()
+
+ def _set_glow(self, value: float) -> None:
+ self._glow = value
+ self.update()
+
+ def appear(self) -> None:
+ if not self._placed:
+ self.place()
+ if self.isVisible() and not self._leaving:
+ return
+ self._leaving = False
+ start = self.windowOpacity() if self.isVisible() else 0.0
+ self.setWindowOpacity(start)
+ self.show()
+ motion.tween(self, start, OPACITY, motion.GENTLE, self.setWindowOpacity, motion.DECELERATE, key="fade")
+
+ def disappear(self) -> None:
+ if not self.isVisible() or self._leaving:
+ return
+ self._leaving = True
+
+ def done():
+ if self._leaving:
+ self.hide()
+ self._leaving = False
+
+ motion.tween(
+ self, self.windowOpacity(), 0.0, motion.FAST, self.setWindowOpacity, motion.ACCELERATE, done, key="fade"
+ )
+
+ # -- position ------------------------------------------------------------
+
+ def place(self) -> None:
+ """Move to the remembered spot, or the top-right corner of the main screen."""
+ self._placed = True
+ saved = db.get_setting("overlay_pos") or ""
+ try:
+ x, y = (int(v) for v in saved.split(","))
+ point = QPoint(x, y)
+ except ValueError:
+ point = None
+ if point is not None and QGuiApplication.screenAt(point + QPoint(self.W // 2, self.H // 2)):
+ self.move(point)
+ return
+ screen = QGuiApplication.primaryScreen()
+ if screen is None:
+ return
+ geo = screen.availableGeometry()
+ self.move(geo.right() - self.W - MARGIN, geo.top() + MARGIN)
+
+ def save_position(self) -> None:
+ db.set_setting("overlay_pos", f"{self.x()},{self.y()}")
+
+ # -- input ---------------------------------------------------------------
+
+ def mousePressEvent(self, event):
+ if event.button() == Qt.MouseButton.LeftButton:
+ self._drag = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
+ self.setCursor(Qt.CursorShape.ClosedHandCursor)
+
+ def mouseMoveEvent(self, event):
+ if self._drag is not None:
+ self.move(event.globalPosition().toPoint() - self._drag)
+
+ def mouseReleaseEvent(self, event):
+ if self._drag is not None:
+ self._drag = None
+ self.setCursor(Qt.CursorShape.OpenHandCursor)
+ self.save_position()
+
+ def mouseDoubleClickEvent(self, event):
+ self.open_requested.emit()
+
+ def contextMenuEvent(self, event):
+ menu = QMenu(self)
+ menu.addAction(f"Open {APP_NAME}", self.open_requested.emit)
+ menu.addAction("Hide floating timer", self.hide_requested.emit)
+ menu.exec(event.globalPos())
+
+ # -- paint ---------------------------------------------------------------
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ box = QRectF(0.5, 0.5, self.W - 1, self.H - 1)
+ path = QPainterPath()
+ path.addRoundedRect(box, 12, 12)
+ p.fillPath(path, QColor(t.surface))
+ p.setPen(QPen(QColor(t.border_strong), 1))
+ p.drawPath(path)
+ if self._glow > 0:
+ ring = QColor(t.accent)
+ ring.setAlphaF(self._glow)
+ p.setPen(QPen(ring, 2))
+ p.drawPath(path)
+
+ # Status dot: accent while a focus app is building flow.
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(t.accent if self._focus else t.text_muted))
+ p.drawEllipse(QPointF(16, 20), 3.5, 3.5)
+
+ clock = fmt.clock(self._session_ms)
+ p.setFont(fonts.sans(16, 600, tabular=True))
+ clock_w = p.fontMetrics().horizontalAdvance(clock)
+ p.setPen(QColor(t.text))
+ p.drawText(QPointF(self.W - 14 - clock_w, 26), clock)
+
+ p.setFont(fonts.sans(12, 600))
+ name = p.fontMetrics().elidedText(self._name, Qt.TextElideMode.ElideRight, self.W - 28 - 14 - clock_w - 10)
+ p.drawText(QPointF(28, 25), name)
+
+ p.setFont(fonts.mono(9, 500, 4))
+ p.setPen(QColor(t.accent_text if self._focus else t.text_muted))
+ p.drawText(QPointF(28, 41), self._detail)
+
+ if self._progress is not None:
+ x0, x1, y = self.W - 14 - 64, self.W - 14, 38
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(t.track))
+ p.drawRoundedRect(QRectF(x0, y - 1.5, x1 - x0, 3), 1.5, 1.5)
+ if self._progress > 0:
+ p.setBrush(QColor(t.accent))
+ p.drawRoundedRect(QRectF(x0, y - 1.5, max(3.0, (x1 - x0) * self._progress), 3), 1.5, 1.5)
+
+
+def _tier_progress(run_ms: int) -> float:
+ minutes = run_ms / 60000
+ index = economy.tier_index(minutes)
+ tiers = economy.FLOW_TIERS
+ if index + 1 >= len(tiers):
+ return 1.0
+ start, end = tiers[index][0], tiers[index + 1][0]
+ return max(0.0, min(1.0, (minutes - start) / (end - start)))
diff --git a/apptrackr/ui/views/app_detail.py b/apptrackr/ui/views/app_detail.py
index 1d8e256..dac8e35 100644
--- a/apptrackr/ui/views/app_detail.py
+++ b/apptrackr/ui/views/app_detail.py
@@ -1,4 +1,4 @@
-"""App detail: totals, 30-day history, limit, rewards and recent sessions for one app."""
+"""App detail: totals, 30-day history, limit, focus and recent sessions for one app."""
from __future__ import annotations
@@ -131,7 +131,7 @@ def __init__(self, ctx, parent=None):
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
+ "Focus app", "Time here builds flow and powers your village.", self.rewards_toggle
)
self.settings_card.body.addWidget(self.rewards_row)
self.reward_hint = label("", "caption", wrap=True)
@@ -260,8 +260,8 @@ def _fill_facts(self, app: dict) -> None:
val = label(value)
val.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.facts_grid.addWidget(val, row, 1)
- # The all-time total retold: a different yardstick for each app.
- retold = perspective.pick(summary["total_ms"] / 60000, 1, offset=self.app_id or 0)
+ # The all-time total retold: one of the best few yardsticks, a different one from app to app.
+ retold = perspective.pick(summary["total_ms"] / 60000, 1, offset=(self.app_id or 0) % 3)
if retold:
fact = retold[0]
row = len(facts)
@@ -312,15 +312,10 @@ def _update_reward_hint(self) -> None:
self.reward_hint.setText("")
self.reward_hint.hide()
return
- 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.")
+ used = queries.app_usage_on(queries.today_str(), self.app_id)
+ goal = fmt.duration(rewards.goal_ms(), short=True)
+ today = f"{fmt.duration(used, short=True)} here today" if used else "Nothing here yet today"
+ self.reward_hint.setText(f"{today}. Counts toward flow and your {goal} daily focus goal.")
self.reward_hint.setVisible(rewards.enabled())
# ------------------------------------------------------------------
diff --git a/apptrackr/ui/views/dashboard.py b/apptrackr/ui/views/dashboard.py
index b0dc720..b3bcfce 100644
--- a/apptrackr/ui/views/dashboard.py
+++ b/apptrackr/ui/views/dashboard.py
@@ -9,7 +9,7 @@
from ...core import tracker as trk
from ...data import db, queries
-from ...game import economy
+from ...game import focus
from ...rewards import engine as rewards
from .. import fmt, fonts, icons, motion, theme
from ..signals import bus
@@ -299,18 +299,17 @@ def _refresh_totals(self, snap: trk.Snapshot) -> None:
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"
+ focus_ids = focus.focus_app_ids()
+ focus_today = rewards.focus_ms(today) + (live if snap.app_id in focus_ids else 0)
+ goal = rewards.goal_ms()
+ if not focus_ids:
+ sub = "Add a focus app to start a streak"
+ elif profile.get("last_streak_day") == today or focus_today >= goal:
+ sub = "Today's focus 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.")
+ sub = f"{fmt.duration(goal - focus_today, short=True)} of focus to go today"
+ tip = f"A streak day needs {fmt.duration(goal, short=True)} in your focus apps."
+ self.t_streak.set_number(streak, _days, sub, tooltip=tip)
def _refresh_charts(self, snap: trk.Snapshot) -> None:
today = date.today()
diff --git a/apptrackr/ui/views/rewards_view.py b/apptrackr/ui/views/rewards_view.py
index c54e632..f5f8146 100644
--- a/apptrackr/ui/views/rewards_view.py
+++ b/apptrackr/ui/views/rewards_view.py
@@ -1,12 +1,16 @@
-"""Rewards: level progress, pending rewards, earning apps and how milestones work."""
+"""Focus: live flow, today's goal and chest, level, and the apps that count as focus."""
from __future__ import annotations
-from PySide6.QtCore import Qt
-from PySide6.QtWidgets import QComboBox, QGridLayout, QHBoxLayout, QProgressBar, QPushButton, QVBoxLayout, QWidget
+from datetime import date
+from PySide6.QtCore import QPointF, QRectF, QSize, Qt
+from PySide6.QtGui import QColor, QPainter, QPen
+from PySide6.QtWidgets import QComboBox, QGridLayout, QHBoxLayout, QProgressBar, QSizePolicy, QVBoxLayout, QWidget
+
+from ...core import tracker as trk
from ...data import queries
-from ...game import economy
+from ...game import economy, focus
from ...game import state as game_state
from ...rewards import engine as rewards
from ...rewards import rules
@@ -15,13 +19,11 @@
from ..widgets.components import (
AppAvatar,
Card,
- EmptyState,
Page,
PageHeader,
animate_progress,
button,
clear_layout,
- count_to,
eyebrow,
icon_label,
label,
@@ -30,7 +32,65 @@
)
from ..widgets.rolling import RollingLabel
-METRIC_TEXT = {"focused_ms": "focused", "opens_count": "launches", "clicks_count": "clicks"}
+LADDER_END_MIN = 90 # the ladder's right edge, a little past the top tier
+
+
+class FlowLadder(QWidget):
+ """The flow tiers as a ruler, filled up to how far the current run has come."""
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ self._minutes = 0.0
+ self._shown = 0.0
+ self._active = False
+
+ def sizeHint(self) -> QSize:
+ return QSize(400, 46)
+
+ def set_run(self, minutes: float, active: bool) -> None:
+ self._active = active
+ target = min(minutes, LADDER_END_MIN)
+ if abs(target - self._minutes) > 0.01:
+ start = self._shown
+ self._minutes = target
+ jump = abs(target - start) > 2 # a new run or a break eases; live seconds just move
+ motion.tween(
+ self, start, target, motion.SLOW if jump else 0, self._set_shown, motion.DECELERATE, key="fill"
+ )
+ self.update()
+
+ def _set_shown(self, value: float) -> None:
+ self._shown = value
+ self.update()
+
+ def paintEvent(self, _event):
+ t = theme.current()
+ p = QPainter(self)
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
+ w = self.width() - 2
+ x_of = lambda m: 1 + w * min(m, LADDER_END_MIN) / LADDER_END_MIN # noqa: E731
+ y = 10
+ p.setPen(Qt.PenStyle.NoPen)
+ p.setBrush(QColor(t.track))
+ p.drawRoundedRect(QRectF(1, y - 3, w, 6), 3, 3)
+ if self._shown > 0:
+ p.setBrush(QColor(t.accent if self._active else t.text_dim))
+ p.drawRoundedRect(QRectF(1, y - 3, x_of(self._shown) - 1, 6), 3, 3)
+ current = economy.tier_index(self._shown)
+ p.setFont(fonts.mono(9, 500, 4))
+ for i, (start, mult, name) in enumerate(economy.FLOW_TIERS):
+ x = x_of(start)
+ reached = self._shown >= start and (self._shown > 0 or i == 0)
+ p.setPen(QPen(QColor(t.text if reached else t.border_strong), 1.5))
+ p.drawLine(QPointF(x, y - 7), QPointF(x, y + 7))
+ color = t.accent_text if i == current and self._active else (t.text_dim if reached else t.text_muted)
+ p.setPen(QColor(color))
+ tiers = economy.FLOW_TIERS
+ room = (x_of(tiers[i + 1][0]) if i + 1 < len(tiers) else self.width()) - x - 10
+ full = f"×{mult:g} {name.upper()}"
+ show_name = i in (current, len(tiers) - 1) and p.fontMetrics().horizontalAdvance(full) <= room
+ p.drawText(QPointF(x + 4, y + 24), full if show_name else f"×{mult:g}")
class RewardsView(Page):
@@ -40,68 +100,111 @@ def __init__(self, ctx, parent=None):
self.ctx = ctx
self.header = PageHeader(
- "Rewards", "Time in the apps you choose earns XP and resources for your village.", kicker="Progress"
+ "Focus",
+ "Stay in your focus apps to build flow. Flow multiplies what your village makes.",
+ 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)
- self.profile = Card(padding=20)
+ # 01 Flow -------------------------------------------------------------
+ self.flow_card = Card("Flow", index=1, padding=20)
top = QHBoxLayout()
- top.setSpacing(28)
- level_col = QVBoxLayout()
- level_col.setSpacing(2)
+ top.setSpacing(24)
+ left = QVBoxLayout()
+ left.setSpacing(2)
+ self.multiplier = RollingLabel("×1")
+ set_role(self.multiplier, "hero")
+ left.addWidget(self.multiplier)
+ self.tier = label("", "heading")
+ left.addWidget(self.tier)
+ top.addLayout(left)
+ top.addWidget(vdivider())
+ facts = QGridLayout()
+ facts.setHorizontalSpacing(28)
+ facts.setVerticalSpacing(4)
+ self.facts: dict[str, RollingLabel] = {}
+ for col, (key, caption) in enumerate((("run", "This run"), ("next", "Next tier"), ("today", "Focus today"))):
+ facts.addWidget(eyebrow(caption), 0, col)
+ value = RollingLabel("–")
+ value.setFont(fonts.sans(20, 600, tabular=True))
+ facts.addWidget(value, 1, col)
+ self.facts[key] = value
+ top.addLayout(facts, 1)
+ self.flow_card.body.addLayout(top)
+ self.ladder = FlowLadder()
+ self.flow_card.body.addWidget(self.ladder)
+ self.flow_hint = label("", "caption", wrap=True)
+ self.flow_card.body.addWidget(self.flow_hint)
+ self.add(self.flow_card)
+
+ # 02 Today and 03 Level -----------------------------------------------
+ row = self.stack_when_narrow(QHBoxLayout())
+ row.setSpacing(16)
+ self.today_card = Card("Today", index=2)
+ goal_head = QHBoxLayout()
+ self.goal_text = label("", "dim")
+ goal_head.addWidget(self.goal_text, 1)
+ self.streak_text = label("", "caption")
+ goal_head.addWidget(self.streak_text)
+ self.today_card.body.addLayout(goal_head)
+ self.goal_bar = QProgressBar()
+ self.goal_bar.setTextVisible(False)
+ self.goal_bar.setMaximum(1000)
+ self.goal_bar.setProperty("tone", "accent")
+ self.today_card.body.addWidget(self.goal_bar)
+ chest_row = QHBoxLayout()
+ chest_row.setSpacing(12)
+ self.chest_icon = icon_label("gift", "text_dim", 20)
+ chest_row.addWidget(self.chest_icon)
+ self.chest_text = label("", "dim", wrap=True)
+ chest_row.addWidget(self.chest_text, 1)
+ self.chest_btn = button("Open chest", kind="primary", icon="gift", on_click=self._open_chest)
+ chest_row.addWidget(self.chest_btn)
+ self.today_card.body.addLayout(chest_row)
+ self.today_card.body.addStretch(1)
+ row.addWidget(self.today_card, 3)
+
+ self.level_card = Card("Level", index=3)
+ lvl_row = QHBoxLayout()
+ lvl_row.setSpacing(20)
+ lvl_col = QVBoxLayout()
+ lvl_col.setSpacing(0)
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)
+ lvl_col.addLayout(cap)
self.level = RollingLabel("")
set_role(self.level, "hero")
- level_col.addWidget(self.level)
- top.addLayout(level_col)
- progress_col = QVBoxLayout()
- progress_col.setSpacing(8)
- progress_col.addStretch(1)
+ lvl_col.addWidget(self.level)
+ lvl_row.addLayout(lvl_col)
+ stats = QVBoxLayout()
+ stats.setSpacing(6)
+ stats.addStretch(1)
self.progress_text = label("", "caption")
- progress_col.addWidget(self.progress_text)
+ stats.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 = RollingLabel("–")
- 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)
-
+ stats.addWidget(self.progress)
+ self.credits_text = label("", "caption")
+ stats.addWidget(self.credits_text)
+ lvl_row.addLayout(stats, 1)
+ self.level_card.body.addLayout(lvl_row)
+ self.level_card.body.addStretch(1)
+ row.addWidget(self.level_card, 2)
+ self.add(row)
+
+ # 04 Focus apps -------------------------------------------------------
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)
+ left_col = QVBoxLayout()
+ left_col.setSpacing(16)
+ self.apps_card = Card("Focus apps", "Time in these apps builds flow and powers the village", index=4)
+ self.apps_list = QVBoxLayout()
+ self.apps_list.setSpacing(4)
+ self.apps_card.body.addLayout(self.apps_list)
add_row = QHBoxLayout()
self.add_combo = QComboBox()
self.add_combo.setAccessibleName("App to add")
@@ -109,71 +212,64 @@ def __init__(self, ctx, parent=None):
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.apps_card.body.addLayout(add_row)
+ left_col.addWidget(self.apps_card)
- self.rules_card = Card("How it works", index=3)
+ # 05 Rewards saved from 1.x (only while some are pending)
+ self.legacy = Card("Rewards from before", "Earned with the old milestones. Claim them any time.", index=5)
+ self.claim_all = button("Claim all", kind="primary", icon="sparkles", on_click=self._claim_all)
+ self.legacy.header_actions.addWidget(self.claim_all)
+ self.legacy_text = label("", "dim", wrap=True)
+ self.legacy.body.addWidget(self.legacy_text)
+ left_col.addWidget(self.legacy)
+ left_col.addStretch(1)
+ cols.addLayout(left_col, 3)
+
+ self.rules_card = Card("How it works", index=6)
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
+ self._ticks = 0
+ self._last_mult: float | 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.",
+ "Every minute in a focus app earns focus points. Stay with it and the run climbs the flow tiers, "
+ "multiplying what each minute is worth:",
"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
+ grid.setVerticalSpacing(3)
+ for i, (start, mult, name) in enumerate(economy.FLOW_TIERS):
+ grid.addWidget(label(f"×{mult:g}"), i, 0)
+ grid.addWidget(label(name, "dim"), i, 1)
+ grid.addWidget(label(f"from {start} min" if start else "from the start", "caption"), i, 2)
+ grid.setColumnStretch(1, 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",
+ f"A run survives {economy.FLOW_GRACE_SEC // 60} minutes away (a quick look at chat or docs). "
+ "Taverns add more. Time outside focus apps never earns points.",
+ "caption",
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(eyebrow("Every day"))
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.",
+ "Reach your daily focus goal to open a chest with credits and a blueprint and to grow your streak. "
+ "Longer streaks fill bigger chests. The village turns focus points into resources; collect them "
+ "on the Village page.",
"caption",
wrap=True,
)
@@ -182,148 +278,159 @@ def _build_rules(self, card: Card) -> None:
# ------------------------------------------------------------------
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.roll_to(str(profile["level"]))
into, need = economy.level_progress(profile["xp"])
self.progress.setMaximum(need)
self.progress_text.setText(f"{into} / {need} XP to level {profile['level'] + 1}")
- self._animate_profile(profile, into)
- streak = profile["streak"]
- self.stat_values["streak"].roll_to(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.")
+ self.credits_text.setText(f"{fmt.count(profile['credits'])} credits · {fmt.count(profile['xp'])} XP in total")
+ self._animate_level(profile, into)
+ self._fill_today(profile)
+ self._fill_apps()
+ legacy = rewards.unclaimed_rewards()
+ self.legacy.setVisible(bool(legacy))
+ if legacy:
+ total: dict = {}
+ for item in legacy:
+ for k, v in item["reward"].items():
+ total[k] = total.get(k, 0) + v
+ self.legacy_text.setText(f"{len(legacy)} pending: {fmt.reward(total, ', ')}")
+ self.tick()
+
+ def tick(self) -> None:
+ snap = self.ctx.snapshot()
+ live = snap.app_id if snap.status == trk.STATUS_TRACKING else None
+ village = game_state.get_village()
+ flow = focus.current(
+ live_app_id=live,
+ live_since=snap.session_start if live else None,
+ tavern_level=game_state.building_level(village, "tavern"),
+ )
+ self.multiplier.roll_to(f"×{flow.multiplier:g}")
+ if flow.active and self._last_mult is not None and flow.multiplier > self._last_mult:
+ motion.flash(self.multiplier, theme.current().accent, radius=6)
+ motion.burst(self.multiplier, theme.current().accent, radius=44, ticks=16) # a new flow tier
+ self._last_mult = flow.multiplier
+ self.tier.setText(flow.tier if flow.run_ms else "Not in a run")
+ self.facts["run"].roll_to(fmt.clock(flow.run_ms) if flow.run_ms else "–")
+ if flow.next_tier and flow.run_ms:
+ self.facts["next"].roll_to(
+ fmt.duration(flow.next_in_ms, short=True) if flow.next_in_ms >= 60_000 else "<1m"
)
- 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."
- )
+ else:
+ self.facts["next"].roll_to("Top tier" if flow.run_ms else "–")
+ self.facts["today"].roll_to(fmt.duration(flow.today_focus_ms, short=True) if flow.today_focus_ms else "0m")
+ self.ladder.set_run(flow.run_ms / 60000, flow.active)
+ if flow.active:
+ pts = f"{flow.multiplier:g} focus point{'s' if flow.multiplier != 1 else ''}"
+ if flow.next_tier:
+ soon = fmt.duration(flow.next_in_ms, short=True) if flow.next_in_ms >= 60_000 else "under a minute"
+ self.flow_hint.setText(f"Every minute here earns {pts}. {flow.next_tier} starts in {soon}.")
+ else:
+ self.flow_hint.setText(f"Top tier. Every minute here earns {pts}.")
+ elif flow.run_ms:
+ self.flow_hint.setText("Run paused. Come back to a focus app within the grace period to keep it.")
+ elif not focus.focus_app_ids():
+ self.flow_hint.setText("Add a focus app below to start building flow.")
+ else:
+ self.flow_hint.setText("Open one of your focus apps to start a run.")
+ self._ticks += 1
+
+ def _fill_today(self, profile: dict) -> None:
+ today = date.today().isoformat()
+ goal = rewards.goal_ms()
+ snap = self.ctx.snapshot()
+ live = snap.uncommitted_ms if snap.app_id in focus.focus_app_ids() else 0
+ done = rewards.focus_ms(today) + live
+ self.goal_text.setText(
+ f"{fmt.duration(done, short=True)} of your {fmt.duration(goal, short=True)} focus goal"
+ if done < goal
+ else f"Goal reached: {fmt.duration(done, short=True)} of focus"
+ )
+ if done >= goal and game_state.chest_state(today) == "locked" and rewards.update_streak(extra_ms=live):
+ profile = rewards.get_profile() # the goal was just reached: count the day and unlock the chest
+ self.ctx.toast("Daily focus goal reached. Your chest is ready.")
+ streak = profile["streak"]
+ self.streak_text.setText(f"Streak {streak} day{'s' if streak != 1 else ''}" if streak else "No streak yet")
+ animate_progress(self.goal_bar, self.goal_bar.value(), int(1000 * min(1.0, done / goal)))
+ status = game_state.chest_state(today)
+ ready = game_state.ready_chests()
+ self.chest_btn.setVisible(bool(ready))
+ reward = economy.chest_for(max(1, streak))
+ contents = fmt.reward(reward, ", ")
+ if ready:
+ self.chest_text.setText(f"Your chest is ready: {contents}.")
+ set_role(self.chest_icon, None)
+ elif status == "claimed":
+ self.chest_text.setText("Today's chest is open. Come back tomorrow for the next one.")
+ else:
+ self.chest_text.setText(f"Reach the goal to open today's chest ({contents}).")
+
+ def _fill_apps(self) -> None:
+ clear_layout(self.apps_list)
+ today = date.today().isoformat()
+ ids = rules.earning_app_ids()
+ apps = [queries.get_app(i) for i in ids]
+ apps = [a for a in apps if a and not a.get("is_hidden")]
+ apps.sort(key=lambda a: -queries.app_usage_on(today, a["app_id"]))
+ if not apps:
+ self.apps_list.addWidget(
+ label("No focus apps yet. Add the apps you want to spend your time in.", "dim", wrap=True)
)
- 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()
+ goal = rewards.goal_ms()
+ for app in apps:
+ self.apps_list.addWidget(self._app_row(app, queries.app_usage_on(today, app["app_id"]), goal))
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:
+ for app in queries.top_apps(queries.days_ago(13), today, limit=40):
+ if app["app_id"] not in ids:
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")
+ self.add_combo.addItem("All recent apps are focus apps")
- 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)
- # Items keep together (non-breaking spaces) and wrap between each other on narrow windows.
- parts = [part.replace(" ", "\u00a0") for part in fmt.reward(group["reward"], "|").split("|")]
- amounts = label(
- "\u00a0· ".join(parts),
- "tick",
- wrap=True,
- align=Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
- )
- amounts.setFont(fonts.mono(10, 500, 2))
- lay.addWidget(amounts, 2)
- lay.addWidget(button("Claim", on_click=lambda ids=group["event_ids"]: self._claim(ids, row)))
- return row
-
- def _earning_row(self, item: dict) -> QWidget:
+ def _app_row(self, app: dict, used_ms: int, goal_ms: int) -> 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))
+ lay.addWidget(AppAvatar(app["name"], app.get("icon_path"), 28))
col = QVBoxLayout()
col.setSpacing(4)
top = QHBoxLayout()
- name = label(item["name"])
- name.setStyleSheet("font-weight: 600;")
+ name = label(app["name"])
+ name.setFont(fonts.sans(13, 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",
- )
- )
+ top.addWidget(label(f"{fmt.duration(used_ms, short=True)} today" if used_ms else "Not yet today", "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
+ animate_progress(bar, 0, int(1000 * min(1.0, used_ms / max(1, goal_ms))))
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", wrap=True))
- 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),
+ tooltip=f"Stop counting {app['name']} as focus",
+ on_click=lambda: self._remove_app(app["app_id"], app["name"], row),
)
lay.addWidget(remove, 0, Qt.AlignmentFlag.AlignTop)
+ if app["app_id"] == self._added_app:
+ motion.fade(row, 0.0, 1.0, motion.NORMAL)
+ self._added_app = None
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)."""
+ def _animate_level(self, profile: dict, into: int) -> None:
shown = self._shown
- self._shown = {"xp": profile["xp"], "credits": profile["credits"], "level": profile["level"], "into": into}
+ self._shown = {"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
@@ -342,37 +449,30 @@ def restart():
key="progress",
)
motion.flash(self.level, theme.current().gold, radius=6)
+ motion.burst(self.level, theme.current().gold, radius=46, ticks=18)
elif shown["into"] != into:
animate_progress(self.progress, shown["into"], into)
- def _claim(self, event_ids: list[int], row: QWidget) -> None:
- applied = rewards.claim_many(event_ids) # claim first; the animation only presents it
- motion.burst(row.findChild(QPushButton))
- motion.collapse(row, lambda: self._report(applied))
+ # ------------------------------------------------------------------
- def _claim_all(self) -> None:
- rows = [r for r in self._pending_rows if r is not None]
- if not rows:
+ def _open_chest(self) -> None:
+ days = game_state.ready_chests()
+ if not days:
return
- self.claim_all.setEnabled(False)
+ applied = game_state.open_chest(days[-1]) or {}
+ motion.burst(self.chest_btn, radius=44, ticks=18)
+ msg = "Chest opened: " + 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)
+ self._changed()
+
+ def _claim_all(self) -> None:
applied = rewards.claim_many()
motion.burst(self.claim_all, radius=40, ticks=16)
- for row in rows[1:]:
- motion.collapse(row, lambda: None)
- motion.collapse(rows[0], lambda: self._report(applied))
-
- 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)
- if applied.get("level_up"):
- motion.burst(self.level, theme.current().gold, radius=46, ticks=18)
- msg = "Claimed " + fmt.reward({k: v for k, v in applied.items() if k != "level_up"}, ", ")
- if applied.get("level_up"):
- msg += f". Level {applied['level_up']} reached!"
- self.ctx.toast(msg)
+ self.ctx.toast("Claimed " + fmt.reward({k: v for k, v in applied.items() if k != "level_up"}, ", "))
+ self._changed()
def _changed(self) -> None:
bus.rewards_changed.emit()
@@ -385,7 +485,7 @@ def _add_app(self) -> 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.ctx.toast(f"{self.add_combo.currentText()} now counts as focus")
self._changed()
def _remove_app(self, app_id: int, name: str, row: QWidget) -> None:
@@ -397,4 +497,4 @@ def undo():
self._changed()
motion.collapse(row, self._changed)
- self.ctx.toast(f"{name} no longer earns rewards", "info", "Undo", undo)
+ self.ctx.toast(f"{name} no longer counts as focus", "info", "Undo", undo)
diff --git a/apptrackr/ui/views/settings_view.py b/apptrackr/ui/views/settings_view.py
index 114eff6..19d0cc8 100644
--- a/apptrackr/ui/views/settings_view.py
+++ b/apptrackr/ui/views/settings_view.py
@@ -25,6 +25,7 @@
from ... import APP_NAME, REPO_URL, __version__
from ...core import autostart
from ...data import db, export, queries
+from ...game import economy
from ...updater import apply as updater_apply
from ...updater import check as updater
from .. import fmt, fonts, motion, theme
@@ -283,6 +284,17 @@ def _build_general(self) -> None:
)
)
card.body.addWidget(divider())
+ self.overlay = Toggle()
+ self.overlay.toggled.connect(self._set_overlay)
+ card.body.addWidget(
+ SettingRow(
+ "Floating timer",
+ "A small clock over other apps showing how long you have been in them. "
+ "Drag it anywhere; double-click it to open AppTrackr.",
+ self.overlay,
+ )
+ )
+ card.body.addWidget(divider())
self.notifications = Toggle()
self.notifications.toggled.connect(self._set_notifications)
card.body.addWidget(
@@ -306,11 +318,22 @@ def _build_general(self) -> None:
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.",
+ "Focus game",
+ "Flow, levels and the village. Turning this off hides both pages; nothing is deleted.",
self.rewards,
)
)
+ card.body.addWidget(divider())
+ self.goal = TickSlider([(fmt.duration(m * 60_000, short=True), m) for m in economy.GOAL_CHOICES])
+ self.goal.setAccessibleName("Daily focus goal")
+ self.goal.committed.connect(self._set_goal)
+ card.body.addWidget(
+ SettingRow(
+ "Daily focus goal",
+ "Time in your focus apps that counts as a streak day and opens the daily chest.",
+ self.goal,
+ )
+ )
self.add(card)
def _build_tracking(self) -> None:
@@ -480,8 +503,14 @@ def _build_about(self) -> None:
def refresh(self) -> None:
self.autostart.set_silently(autostart.is_enabled())
self.tray.set_silently(db.get_bool("minimize_to_tray", True))
+ self.overlay.set_silently(db.get_bool("overlay_enabled", True))
self.notifications.set_silently(db.get_bool("notifications_enabled", True))
self.rewards.set_silently(db.get_bool("rewards_enabled", True))
+ goal = db.get_int("focus_goal_min", economy.DEFAULT_GOAL_MIN)
+ if self.goal.index_of(goal) < 0: # a value set outside the slider keeps its own stop
+ stops = sorted({*economy.GOAL_CHOICES, goal})
+ self.goal.set_stops([(fmt.duration(m * 60_000, short=True), m) for m in stops])
+ self.goal.set_stop_value(goal)
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", ""))
@@ -542,7 +571,16 @@ def _set_autostart(self, on: bool) -> None:
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")
+ self.ctx.toast("Focus game turned on" if on else "Focus game turned off")
+
+ def _set_overlay(self, on: bool) -> None:
+ self.ctx.window.set_overlay_enabled(on)
+ self.ctx.toast("Floating timer on" if on else "Floating timer off")
+
+ def _set_goal(self, minutes: int) -> None:
+ db.set_setting("focus_goal_min", minutes)
+ bus.rewards_changed.emit()
+ self.ctx.toast(f"Daily focus goal set to {fmt.duration(minutes * 60_000)}")
def _set_idle(self, sec: int) -> None:
db.set_setting("idle_threshold_sec", sec)
diff --git a/apptrackr/ui/views/village_view.py b/apptrackr/ui/views/village_view.py
index 155abf8..236f3d8 100644
--- a/apptrackr/ui/views/village_view.py
+++ b/apptrackr/ui/views/village_view.py
@@ -1,7 +1,10 @@
-"""Village: inventory, market and buildings that boost future rewards."""
+"""Village: the harvest your focus produced, production rates, buildings and the market."""
from __future__ import annotations
+import time
+from datetime import date
+
from PySide6.QtCore import QPointF, QRectF, Qt, QTimer
from PySide6.QtGui import QColor, QPainter, QPen
from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QProgressBar, QVBoxLayout, QWidget
@@ -9,7 +12,7 @@
from ...game import economy
from ...game import state as game_state
from ...rewards import engine as rewards
-from .. import fmt, icons, motion, theme
+from .. import fmt, fonts, icons, motion, theme
from ..signals import bus
from ..widgets.components import (
PAGE_MARGIN,
@@ -28,6 +31,10 @@
)
BUILDING_ICONS = {
+ "lumberyard": "tree-pine",
+ "quarry": "mountain",
+ "farm": "wheat",
+ "mine": "cog",
"workshop": "hammer",
"storage": "warehouse",
"house": "house",
@@ -94,6 +101,12 @@ def paintEvent(self, _event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
+ if self._max > 12: # long ladders read better as one bar
+ p.setBrush(QColor(t.track))
+ p.drawRoundedRect(QRectF(0, 0, self.width(), self.height()), 3, 3)
+ p.setBrush(QColor(t.text_dim))
+ p.drawRoundedRect(QRectF(0, 0, self.width() * min(1.0, self._level / self._max), self.height()), 3, 3)
+ return
gap = 4
w = (self.width() - gap * (self._max - 1)) / self._max
for i in range(self._max):
@@ -113,19 +126,41 @@ def __init__(self, ctx, parent=None):
self.ctx = ctx
self.header = PageHeader(
- "Village", "Spend resources from rewards on buildings that boost future rewards.", kicker="Progress"
+ "Village", "Your village works while you focus. Collect what it made and build it up.", kicker="Progress"
)
+ self.collect_btn = button("Collect", kind="primary", icon="sparkles", on_click=self._collect)
+ self.header.actions.addWidget(self.collect_btn)
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.t_bonus = StatTile("Production bonus", framed=False)
self.add(MetricGrid([self.t_level, self.t_villagers, self.t_credits, self.t_bonus], columns=4))
- row = QHBoxLayout()
+ top = self.stack_when_narrow(QHBoxLayout())
+ top.setSpacing(16)
+ self.harvest_card = Card("Harvest", "–", index=1)
+ self.harvest_grid = QGridLayout()
+ self.harvest_grid.setHorizontalSpacing(18)
+ self.harvest_grid.setVerticalSpacing(8)
+ self.harvest_card.body.addLayout(self.harvest_grid)
+ self.harvest_note = label("", "caption", wrap=True)
+ self.harvest_card.body.addWidget(self.harvest_note)
+ self.harvest_card.body.addStretch(1)
+ top.addWidget(self.harvest_card, 3)
+ self.production = Card("Production", "Per hour of focus at ×1. Flow multiplies it up to ×3.", index=2)
+ self.prod_grid = QGridLayout()
+ self.prod_grid.setHorizontalSpacing(12)
+ self.prod_grid.setVerticalSpacing(6)
+ self.production.body.addLayout(self.prod_grid)
+ self.production.body.addStretch(1)
+ top.addWidget(self.production, 2)
+ self.add(top)
+
+ row = self.stack_when_narrow(QHBoxLayout())
row.setSpacing(16)
- self.inventory = Card("Inventory", index=1)
+ self.inventory = Card("Inventory", index=3)
self.inv_grid = QGridLayout()
self.inv_grid.setHorizontalSpacing(12)
self.inv_grid.setVerticalSpacing(10)
@@ -133,14 +168,14 @@ def __init__(self, ctx, parent=None):
self.inventory.body.addStretch(1)
row.addWidget(self.inventory, 3)
- self.market = Card("Market", "Trade credits for resources", index=2)
+ self.market = Card("Market", "Trade credits for resources", index=4)
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.add(eyebrow("Buildings", 5))
self.buildings = QGridLayout()
self.buildings.setSpacing(16)
self.add(self.buildings)
@@ -151,6 +186,7 @@ def __init__(self, ctx, parent=None):
self._cards: dict[str, Card] = {}
self._columns = 0
self._just_built: str | None = None
+ self._ticks = 0
bus.rewards_changed.connect(lambda: self.isVisible() and self.refresh())
def refresh(self) -> None:
@@ -162,14 +198,12 @@ def refresh(self) -> None:
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")
+ self.t_credits.set_number(profile["credits"], lambda v: fmt.count(int(round(v))), "From levels and chests")
+ extras = [f"+{bonuses['xp_bonus_pct']}% XP" if bonuses["xp_bonus_pct"] else ""]
+ extras.append(f"flow grace {int(bonuses['grace_sec'] // 60)} min")
+ self.t_bonus.set(f"+{bonuses['production_pct']}%", ", ".join(e for e in extras if e))
+ self._fill_harvest(village)
+ self._fill_production(village)
clear_layout(self.inv_grid)
inv = village["inventory"]
@@ -201,7 +235,7 @@ def refresh(self) -> None:
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)
+ self.market_grid.addWidget(label(fmt.amount(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:
@@ -226,6 +260,87 @@ def celebrate() -> None: # after layout, so the card has its final geometry
QTimer.singleShot(0, card, celebrate)
self._just_built = None
+ def tick(self) -> None:
+ self._ticks += 1
+ if self._ticks % 5 == 0: # the harvest grows while you focus
+ self._fill_harvest(game_state.get_village())
+
+ def _fill_harvest(self, village: dict) -> None:
+ crop = game_state.harvest(village=village)
+ clear_layout(self.harvest_grid)
+ rates = game_state.production_rates(village)
+ items = [(res, crop["resources"].get(res, 0)) for res in economy.RESOURCES if res in rates]
+ items = [item for item in items if item[1]] or items[:3] # skip what has not made a whole unit yet
+ items.append(("xp", crop["xp"]))
+ for i, (res, amount) in enumerate(items):
+ cell = QHBoxLayout()
+ cell.setSpacing(8)
+ cell.addWidget(icon_label(RESOURCE_ICONS.get(res, "sparkles"), "text_dim", 16))
+ value = label(f"+{fmt.count(amount)}")
+ value.setFont(fonts.sans(17, 600, tabular=True))
+ cell.addWidget(value)
+ cell.addWidget(label(fmt.amount(amount, res).split(" ", 1)[1], "caption"))
+ cell.addStretch(1)
+ host = QWidget()
+ host.setLayout(cell)
+ self.harvest_grid.addWidget(host, i // 3, i % 3)
+ since = (
+ fmt.time_of_day(crop["since"])
+ if crop["since"] > time.time() - 86400
+ else fmt.short_date(date.fromtimestamp(crop["since"]).isoformat())
+ )
+ if crop["focus_ms"]:
+ self.harvest_card.set_caption(
+ f"{fmt.duration(crop['focus_ms'], short=True)} of focus since {since}, "
+ f"{fmt.count(int(crop['points']))} focus points"
+ )
+ else:
+ self.harvest_card.set_caption(f"No focus since {since}. Work in a focus app and your village gets busy.")
+ if crop["full"]:
+ self.harvest_note.setText(
+ "Storage is full for " + ", ".join(crop["full"]) + ". Collect, spend or build storage to keep the rest."
+ )
+ else:
+ self.harvest_note.setText("")
+ ready = any(crop["resources"].values()) or crop["xp"] > 0
+ self.collect_btn.setEnabled(ready)
+ self._harvest_ready = ready
+
+ def _fill_production(self, village: dict) -> None:
+ clear_layout(self.prod_grid)
+ rates = game_state.production_rates(village)
+ for i, res in enumerate(economy.RESOURCES):
+ if res not in rates:
+ continue
+ per_hour = rates[res] * 60
+ self.prod_grid.addWidget(icon_label(RESOURCE_ICONS[res], "text_dim", 15), i, 0)
+ self.prod_grid.addWidget(label(res.title()), i, 1)
+ text = f"{per_hour:,.0f}" if per_hour >= 10 else f"{per_hour:.1f}"
+ value = label(text)
+ value.setFont(fonts.sans(13, 600, tabular=True))
+ self.prod_grid.addWidget(value, i, 2, Qt.AlignmentFlag.AlignRight)
+ xp_hour = 60 * economy.XP_PER_POINT * (1 + game_state.get_bonuses(village)["xp_bonus_pct"] / 100)
+ row = len(economy.RESOURCES)
+ self.prod_grid.addWidget(icon_label("sparkles", "text_dim", 15), row, 0)
+ self.prod_grid.addWidget(label("XP"), row, 1)
+ value = label(f"{xp_hour:.0f}")
+ value.setFont(fonts.sans(13, 600, tabular=True))
+ self.prod_grid.addWidget(value, row, 2, Qt.AlignmentFlag.AlignRight)
+ self.prod_grid.setColumnStretch(1, 1)
+
+ def _collect(self) -> None:
+ applied = game_state.collect()
+ gained = {k: v for k, v in applied.items() if k in economy.RESOURCES or k in ("xp", "credits")}
+ motion.burst(self.collect_btn, radius=40, ticks=16)
+ if applied.get("level_up"):
+ msg = f"Level {applied['level_up']} reached! "
+ else:
+ msg = ""
+ self.ctx.toast(msg + ("Collected " + fmt.reward(gained, ", ") if gained else "Nothing to collect yet"))
+ bus.rewards_changed.emit()
+ if not self.isVisible():
+ self.refresh()
+
def resizeEvent(self, event):
super().resizeEvent(event)
self._place_buildings()
@@ -272,6 +387,9 @@ def _building_card(self, name: str, village: dict, player_level: int) -> Card:
card.body.addWidget(LevelPips(level, spec["max_level"], self._levels.get(name)))
card.body.addWidget(label(spec["desc"], "dim", wrap=True))
+ effect = _effect(name, level, maxed, village)
+ if effect:
+ card.body.addWidget(label(effect, "caption", wrap=True))
if locked:
status = f"Unlocks at player level {spec['unlock_level']}"
@@ -318,3 +436,35 @@ def _buy(self, resource: str) -> None:
def _count(n: float) -> str:
return str(int(round(n)))
+
+
+def _effect(name: str, level: int, maxed: bool, village: dict) -> str:
+ """What the building does now, and at the next level."""
+
+ def at(lvl: int) -> dict:
+ trial = {**village, "buildings": {**village.get("buildings", {}), name: {"level": lvl}}}
+ if name == "house":
+ trial["villagers"] = village.get("villagers", 0) + (lvl - level)
+ return trial
+
+ def show(lvl: int) -> str:
+ v = at(lvl)
+ for res, (building, _rate, _free) in economy.PRODUCTION.items():
+ if building == name:
+ per_hour = game_state.production_rates(v).get(res, 0) * 60
+ return f"{per_hour:,.0f} {res}/h" if per_hour >= 10 else f"{per_hour:.1f} {res}/h"
+ bonuses = game_state.get_bonuses(v)
+ return {
+ "storage": f"holds {fmt.count(game_state.resource_cap(v))}",
+ "house": f"+{bonuses['production_pct']}% production",
+ "workshop": f"+{bonuses['xp_bonus_pct']}% XP",
+ "tavern": f"{int(bonuses['grace_sec'] // 60)} min grace",
+ "monument": f"+{economy.MONUMENT_PCT}% production and a crown",
+ }.get(name, "")
+
+ now = show(level)
+ if name == "monument":
+ return "Standing" if level else f"Adds {now}"
+ if maxed or not now:
+ return f"Now {now}" if now else ""
+ return f"Now {now}, next {show(level + 1)}"
diff --git a/apptrackr/ui/widgets/other_terms.py b/apptrackr/ui/widgets/other_terms.py
index 62dfa96..91a17bb 100644
--- a/apptrackr/ui/widgets/other_terms.py
+++ b/apptrackr/ui/widgets/other_terms.py
@@ -2,19 +2,18 @@
from __future__ import annotations
-from datetime import date
-
from PySide6.QtCore import QSize, Qt, QTimer
from PySide6.QtGui import QPainter
-from PySide6.QtWidgets import QFrame, QHBoxLayout, QSizePolicy, QVBoxLayout, QWidget
+from PySide6.QtWidgets import QFrame, QGridLayout, QHBoxLayout, QSizePolicy, QVBoxLayout, QWidget
from ... import perspective
from ...data import db
from .. import fmt, fonts, icons, motion, theme
-from .components import Card, SegmentedControl, button, label, vdivider
+from .components import Card, SegmentedControl, button, divider, label, vdivider
from .rolling import RollingLabel
PERIODS = (("today", "Today"), ("week", "This week"), ("all", "All time"))
+ROWS, COLUMNS = 2, 3
class _Glyph(QWidget):
@@ -87,7 +86,7 @@ def show_fact(self, fact: perspective.Fact | None, animate: bool) -> None:
class OtherTermsCard(Card):
- """Three comparisons for the chosen period, with a shuffle."""
+ """Six comparisons for the chosen period, two rows of three, with a shuffle."""
def __init__(self, index: int | None = None, parent=None):
super().__init__("In other terms", "–", parent=parent, index=index)
@@ -97,23 +96,28 @@ def __init__(self, index: int | None = None, parent=None):
self.shuffle = button("Shuffle", kind="ghost", icon="refresh-cw", on_click=self._shuffle)
self.shuffle.setToolTip("Show other comparisons")
self.header_actions.addWidget(self.shuffle)
- row = QFrame()
- row.setProperty("cell", True)
- lay = QHBoxLayout(row)
- lay.setContentsMargins(0, 0, 0, 0)
- lay.setSpacing(0)
+ panel = QFrame()
+ panel.setProperty("cell", True)
+ grid = QGridLayout(panel)
+ grid.setContentsMargins(0, 0, 0, 0)
+ grid.setSpacing(0)
self.tiles: list[FactTile] = []
- for i in range(3):
- if i:
- lay.addWidget(vdivider())
+ for i in range(ROWS * COLUMNS): # tiles on even rows and columns, hairlines between
+ r, c = divmod(i, COLUMNS)
+ if c:
+ grid.addWidget(vdivider(), r * 2, c * 2 - 1)
+ if r:
+ grid.addWidget(divider(), r * 2 - 1, c * 2, 1, 2 if c < COLUMNS - 1 else 1)
tile = FactTile()
self.tiles.append(tile)
- lay.addWidget(tile, 1)
- self.body.addWidget(row)
+ grid.addWidget(tile, r * 2, c * 2)
+ for c in range(COLUMNS):
+ grid.setColumnStretch(c * 2, 1)
+ self.body.addWidget(panel)
stored = db.get_setting("perspective_period", "week")
self._period = stored if stored in dict(PERIODS) else "week"
self.period.set_current([key for key, _ in PERIODS].index(self._period))
- self._offset = date.today().toordinal() # a different set each day
+ self._offset = 0 # the best set first; Shuffle steps through the rest
self._totals: dict[str, float] = {}
self._shown_offset: int | None = None
self._shown_period: str | None = None
@@ -153,7 +157,7 @@ def _render(self) -> None:
for i, tile in enumerate(self.tiles):
fact = facts[i] if i < len(facts) else None
delay = (
- i * 70 if animate and (self._shown_offset != self._offset or self._shown_period != self._period) else 0
+ i * 50 if animate and (self._shown_offset != self._offset or self._shown_period != self._period) else 0
)
if delay:
QTimer.singleShot(int(delay * motion.time_scale), tile, lambda t=tile, f=fact: t.show_fact(f, True))
diff --git a/docs/releases/1.2.0.md b/docs/releases/1.2.0.md
new file mode 100644
index 0000000..9624d71
--- /dev/null
+++ b/docs/releases/1.2.0.md
@@ -0,0 +1,31 @@
+AppTrackr 1.2.0 turns the rewards into an idle game that pays you for staying focused, adds a floating timer over other apps, and rewrites "In other terms". Your history, village, level, streak and settings all carry over.
+
+## How to update
+
+**If you have AppTrackr 1.1.0**
+
+Open **Settings** and click **Download and install**. AppTrackr closes, updates and starts again.
+
+**If you have AppTrackr 1.0.x, or the button does not show up**
+
+1. Download **AppTrackr_Setup.exe** below.
+2. Run it. If Windows shows "Windows protected your PC", click **More info**, then **Run anyway**.
+3. Click through the installer. It replaces the old version in the same place and keeps your data.
+
+**If you use the portable zip**
+
+Download **AppTrackr_Portable.zip**, extract it over the old folder (or anywhere) and run `AppTrackr.exe`. Your data is shared with the installed version.
+
+## What's new
+
+- **Focus game.** Pick your focus apps (an editor, a design tool, docs). Unbroken time in them builds flow: each minute is worth more the longer you stay, from x1 up to x3 after 75 minutes. A quick look at chat does not break it.
+- **Village that works while you do.** Lumberyards, quarries, farms, mines and labs turn focus into resources. Collect the harvest, then build and upgrade.
+- **Daily focus goal.** Reach it (2 h by default, change it in Settings) to grow your streak and open a chest.
+- **Floating timer.** A small clock in the corner shows how long you have been in the current app, and your flow tier in focus apps. Drag it anywhere, double-click to open AppTrackr, right-click to hide it, or turn it off in Settings. It stays out of the way of full-screen games and videos.
+- **In other terms, rewritten.** Six plain counts you can picture, picked from 56 yardsticks (films, football matches, loaves of bread, flights to New York, novels), instead of percentages. Shuffle for more.
+
+## Notes for existing players
+
+- Apps that earned rewards before are your focus apps now. If you had none, your favorites become focus apps once.
+- Rewards you had not claimed yet are still on the Focus page.
+- Buildings, resources, level, XP, credits and your streak are kept. Storage now holds more.
diff --git a/docs/screenshots/app-detail.png b/docs/screenshots/app-detail.png
index 4a3d328..4015326 100644
Binary files a/docs/screenshots/app-detail.png and b/docs/screenshots/app-detail.png differ
diff --git a/docs/screenshots/apps.png b/docs/screenshots/apps.png
index e408837..4aa8fce 100644
Binary files a/docs/screenshots/apps.png and b/docs/screenshots/apps.png differ
diff --git a/docs/screenshots/calendar.png b/docs/screenshots/calendar.png
index fc86bb0..308eb9a 100644
Binary files a/docs/screenshots/calendar.png and b/docs/screenshots/calendar.png differ
diff --git a/docs/screenshots/dashboard-light.png b/docs/screenshots/dashboard-light.png
index a069596..7695585 100644
Binary files a/docs/screenshots/dashboard-light.png and b/docs/screenshots/dashboard-light.png differ
diff --git a/docs/screenshots/dashboard-perspective.png b/docs/screenshots/dashboard-perspective.png
index acb030a..cea585f 100644
Binary files a/docs/screenshots/dashboard-perspective.png and b/docs/screenshots/dashboard-perspective.png differ
diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png
index 2d659ac..79f2991 100644
Binary files a/docs/screenshots/dashboard.png and b/docs/screenshots/dashboard.png differ
diff --git a/docs/screenshots/demo.gif b/docs/screenshots/demo.gif
index 0a0502f..5fdc661 100644
Binary files a/docs/screenshots/demo.gif and b/docs/screenshots/demo.gif differ
diff --git a/docs/screenshots/rewards.png b/docs/screenshots/rewards.png
index 4abbd87..a043501 100644
Binary files a/docs/screenshots/rewards.png and b/docs/screenshots/rewards.png differ
diff --git a/docs/screenshots/settings-appearance.png b/docs/screenshots/settings-appearance.png
index bac1738..46d2828 100644
Binary files a/docs/screenshots/settings-appearance.png and b/docs/screenshots/settings-appearance.png differ
diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png
index 6b5200d..404ca5e 100644
Binary files a/docs/screenshots/settings.png and b/docs/screenshots/settings.png differ
diff --git a/docs/screenshots/themes.png b/docs/screenshots/themes.png
index 9de3180..ef42359 100644
Binary files a/docs/screenshots/themes.png and b/docs/screenshots/themes.png differ
diff --git a/docs/screenshots/village.png b/docs/screenshots/village.png
index 41b598f..76ec73c 100644
Binary files a/docs/screenshots/village.png and b/docs/screenshots/village.png differ
diff --git a/packaging/installer.iss b/packaging/installer.iss
index 652c659..d315d41 100644
--- a/packaging/installer.iss
+++ b/packaging/installer.iss
@@ -1,8 +1,8 @@
; Inno Setup script for AppTrackr. Build after PyInstaller from the repository root:
-; iscc /DAppVersion=1.1.0 packaging\installer.iss
+; iscc /DAppVersion=1.2.0 packaging\installer.iss
#ifndef AppVersion
- #define AppVersion "1.1.0"
+ #define AppVersion "1.2.0"
#endif
[Setup]
diff --git a/scripts/record_demo.py b/scripts/record_demo.py
index e0fbbd4..316433a 100644
--- a/scripts/record_demo.py
+++ b/scripts/record_demo.py
@@ -152,8 +152,10 @@ def scroll_to(view, widget, offset: int = 24) -> None:
detail.limit.setValue(detail.limit.index_of(60)) # the fader glides to the new stop
wait(1100)
window.show_page("rewards")
- wait(700)
- window._views["rewards"]._claim_all()
+ wait(1400)
+ window.show_page("village")
+ wait(900)
+ window._views["village"]._collect()
wait(1600)
settings = window._views["settings"]
window.show_page("settings")
diff --git a/tests/test_game.py b/tests/test_game.py
new file mode 100644
index 0000000..6a6c88a
--- /dev/null
+++ b/tests/test_game.py
@@ -0,0 +1,233 @@
+import json
+import time
+from datetime import date, timedelta
+
+import pytest
+
+from apptrackr.data import db, queries
+from apptrackr.game import economy, focus, state
+from apptrackr.rewards import engine, rules
+
+MIN = 60.0
+
+
+def _session(app_id, start, minutes):
+ sid = queries.start_session(app_id, start)
+ queries.update_session_end(sid, start + minutes * MIN)
+ queries.add_focus_span(app_id, start, start + minutes * MIN)
+ db.commit()
+
+
+def _focus_app(exe="code.exe"):
+ app_id = queries.get_or_create_app(exe)
+ rules.enable_app_rewards(app_id)
+ return app_id
+
+
+def _set_collected(ts):
+ village = state.get_village()
+ village["collected_until"] = ts
+ state.save_village(village)
+ 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() == focus.focus_app_ids() == {app_id}
+
+
+def test_flow_tiers_multiply_later_minutes():
+ # 30 straight minutes: 10 at x1, 15 at x1.5, 5 at x2
+ fp, ms = focus.points([(0, 30 * MIN)], 180, 0, 30 * MIN)
+ assert fp == pytest.approx(10 + 22.5 + 10)
+ assert ms == 30 * 60_000
+ assert focus.multiplier_at(0) == 1.0
+ assert focus.multiplier_at(80) == 3.0
+
+
+def test_short_breaks_keep_a_run_and_long_ones_end_it():
+ spans = [(0, 20 * MIN), (22 * MIN, 30 * MIN)] # 2 minutes away
+ assert len(focus.runs(spans, 180)) == 1
+ spans = [(0, 20 * MIN), (30 * MIN, 40 * MIN)] # 10 minutes away
+ assert len(focus.runs(spans, 180)) == 2
+ assert len(focus.runs(spans, focus.grace_sec(tavern_level=10))) == 1
+ # The second run starts over at x1.
+ fp, _ = focus.points(spans, 180, 0, 40 * MIN)
+ assert fp == pytest.approx(10 + 10 * 1.5 + 10)
+
+
+def test_points_inside_a_window_keep_the_runs_tier():
+ fp, ms = focus.points([(0, 60 * MIN)], 180, 50 * MIN, 60 * MIN)
+ assert fp == pytest.approx(10 * 2.5)
+ assert ms == 10 * 60_000
+
+
+def test_harvest_turns_focus_into_xp_and_resources_with_carry():
+ app_id = _focus_app()
+ other = queries.get_or_create_app("game.exe")
+ now = time.time()
+ _set_collected(now - 3600)
+ _session(app_id, now - 40 * MIN, 30)
+ _session(other, now - 9 * MIN, 8) # not a focus app: earns nothing
+ crop = state.harvest(now)
+ assert crop["points"] == pytest.approx(42.5)
+ assert crop["focus_ms"] == 30 * 60_000
+ assert crop["resources"] == {"wood": 10, "stone": 6, "food": 8}
+ assert crop["xp"] == 10
+ applied = state.collect(now)
+ assert applied["wood"] == 10 and applied["xp"] == 10
+ village = state.get_village()
+ assert village["inventory"]["wood"] == 10
+ assert village["carry"]["wood"] == pytest.approx(0.625)
+ assert engine.get_profile()["xp"] == 10
+ assert state.harvest(now)["points"] == 0 # nothing new since collecting
+
+
+def test_harvest_respects_storage():
+ app_id = _focus_app()
+ now = time.time()
+ _set_collected(now - 7200)
+ village = state.get_village()
+ village["inventory"]["wood"] = economy.resource_cap(0) - 3
+ state.save_village(village)
+ db.commit()
+ _session(app_id, now - 100 * MIN, 90)
+ crop = state.harvest(now)
+ assert crop["resources"]["wood"] == 3
+ assert "wood" in crop["full"]
+ state.collect(now)
+ assert state.get_village()["inventory"]["wood"] == economy.resource_cap(0)
+
+
+def test_buildings_raise_production():
+ village = state.get_village()
+ base = state.production_rates(village)
+ assert set(base) == {"wood", "stone", "food"}
+ village["buildings"] = {"lumberyard": {"level": 3}, "mine": {"level": 1}}
+ village["villagers"] = 5
+ rates = state.production_rates(village)
+ assert rates["wood"] == pytest.approx(0.25 * 4 * 1.2)
+ assert rates["metal"] == pytest.approx(0.08 * 1.2)
+
+
+def test_live_flow_includes_the_session_in_progress():
+ app_id = _focus_app()
+ now = time.time()
+ flow = focus.current(now, live_app_id=app_id, live_since=now - 26 * MIN)
+ assert flow.active
+ assert flow.multiplier == 2.0 and flow.tier == "In the zone"
+ assert flow.next_tier == "Deep work"
+ assert flow.next_in_ms == pytest.approx(19 * 60_000, abs=1000)
+ idle = focus.current(now, live_app_id=None)
+ assert not idle.active and idle.run_ms == 0 and idle.multiplier == 1.0
+
+
+def test_goal_grows_streak_once_a_day_and_unlocks_the_chest():
+ _focus_app()
+ yesterday = (date.today() - timedelta(days=1)).isoformat()
+ db.execute("UPDATE player_profile SET streak_days = 6, last_streak_day = ? WHERE profile_id = 1", (yesterday,))
+ db.set_setting("focus_goal_min", 60)
+ assert engine.goal_ms() == 60 * 60_000
+ assert engine.update_streak(extra_ms=59 * 60_000) is None
+ assert state.chest_state() == "locked"
+ assert engine.update_streak(extra_ms=60 * 60_000) == {"streak": 7}
+ assert engine.update_streak(extra_ms=60 * 60_000) is None
+ assert state.ready_chests() == [date.today().isoformat()]
+ applied = state.open_chest()
+ week = economy.chest_for(7)
+ assert applied["blueprints"] == week["blueprints"] == 2
+ assert applied["credits"] == week["credits"]
+ assert state.chest_state() == "claimed"
+ assert state.open_chest() 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_rewards_from_1x_can_still_be_claimed():
+ app_id = _focus_app()
+ rule = db.fetchone("SELECT rule_id FROM reward_rules WHERE app_id = ?", (app_id,))["rule_id"]
+ village = state.get_village()
+ village["buildings"]["workshop"] = {"level": 2}
+ state.save_village(village)
+ db.execute("UPDATE player_profile SET xp = 95 WHERE profile_id = 1")
+ db.execute(
+ "INSERT INTO reward_events (ts, app_id, rule_id, day, granted_json) VALUES (?, ?, ?, ?, ?)",
+ (time.time(), app_id, rule, queries.today_str(), json.dumps({"xp": 10, "wood": 4})),
+ )
+ db.commit()
+ assert engine.unclaimed_count() == 1
+ applied = engine.claim_many()
+ assert applied["xp"] == 10 and applied["wood"] == 4
+ assert applied["level_up"] == 2
+ assert applied["credits"] == economy.CREDITS_PER_LEVEL * 2
+ assert engine.unclaimed_count() == 0
+
+
+def test_building_unlocks_costs_and_market():
+ ok, reason = state.can_build("lumberyard")
+ assert not ok and reason.startswith("Need")
+ village = state.get_village()
+ village["inventory"].update({"wood": 15})
+ state.save_village(village)
+ assert state.build_or_upgrade("lumberyard") == (True, "Lumberyard built")
+ assert state.build_cost("lumberyard", 1) == {"wood": 23}
+ assert state.can_build("mine")[1] == "Unlocks at level 3"
+ assert state.can_build("monument")[1] == "Unlocks at level 10"
+
+ db.execute("UPDATE player_profile SET level = 2 WHERE profile_id = 1")
+ village = state.get_village()
+ village["inventory"].update({"wood": 400, "food": 400})
+ state.save_village(village)
+ assert state.build_or_upgrade("house")[0]
+ assert state.get_village()["villagers"] == 1
+
+ db.execute("UPDATE player_profile SET credits = 4 WHERE profile_id = 1")
+ assert not state.buy("stone")[0]
+ db.execute("UPDATE player_profile SET credits = 20 WHERE profile_id = 1")
+ amount, price = economy.MARKET["stone"]
+ assert state.buy("stone") == (True, f"Bought {amount} stone")
+ assert engine.get_profile()["credits"] == 20 - price
+
+
+def test_storage_gates_expensive_buildings():
+ db.execute("UPDATE player_profile SET level = 10 WHERE profile_id = 1")
+ village = state.get_village()
+ village["inventory"].update({"stone": 200, "metal": 200, "blueprints": 5})
+ state.save_village(village)
+ assert state.can_build("monument") == (False, "Needs a bigger storage")
+
+
+def test_attention_counts_chests_harvests_and_old_rewards():
+ app_id = _focus_app()
+ assert engine.attention_count() == 0
+ now = time.time()
+ _set_collected(now - 7200)
+ _session(app_id, now - 70 * MIN, 60)
+ assert engine.attention_count() == 1
+ state.unlock_chest(date.today().isoformat())
+ assert engine.attention_count() == 2
+ db.set_setting("rewards_enabled", False)
+ assert engine.attention_count() == 0
+
+
+def test_favorites_become_focus_apps_once_after_updating():
+ fav = queries.get_or_create_app("figma.exe")
+ queries.set_favorite(fav, True)
+ assert rules.adopt_favorites_once() == 1
+ assert focus.focus_app_ids() == {fav}
+ rules.enable_app_rewards(fav, False)
+ assert rules.adopt_favorites_once() == 0 # only once: removing it later sticks
+
+
+def test_chosen_focus_apps_are_not_overridden_by_favorites():
+ chosen = _focus_app()
+ queries.set_favorite(queries.get_or_create_app("game.exe"), True)
+ assert rules.adopt_favorites_once() == 0
+ assert focus.focus_app_ids() == {chosen}
diff --git a/tests/test_perspective.py b/tests/test_perspective.py
index 6f05b91..9ae6ed2 100644
--- a/tests/test_perspective.py
+++ b/tests/test_perspective.py
@@ -1,46 +1,124 @@
-"""'In other terms' comparisons: readable picks, honest labels."""
+"""'In other terms' comparisons: whole counts only, readable picks, honest labels."""
from apptrackr import perspective as pv
from apptrackr.paths import assets_dir
+UNIT = pv.Yardstick("unit", 1, "things", "One minute each", "clock", "test", max_count=1e9, one="thing")
+
def _stick(key: str) -> pv.Yardstick:
return next(s for s in pv.YARDSTICKS if s.key == key)
-def test_counts_and_percentages():
+def _totals(low: float = 1, high: float = 20_000 * 60, step: float = 1.13):
+ """Totals in minutes from *low* to *high*, spaced evenly on a log scale."""
+ minutes = low
+ while minutes <= high:
+ yield minutes
+ minutes *= step
+ yield high
+
+
+def _keys(minutes: float, offset: int = 0) -> set[str]:
+ return {f.key for f in pv.pick(minutes, 6, offset)}
+
+
+def test_number_formatting():
+ def value(ratio: float) -> str:
+ return pv.describe(ratio, UNIT).value
+
+ assert value(1) == "1"
+ assert value(2) == "2" # a trailing .0 is dropped
+ assert value(2.4) == "2.4"
+ assert value(9.94) == "9.9"
+ assert value(9.96) == "10"
+ assert value(12.4) == "12"
+ assert value(1234) == "1,234"
+ assert value(999_999) == "999,999"
+ assert value(999_999.6) == "1 million"
+ assert value(1_234_567) == "1.2 million"
+ assert value(12_345_678) == "12 million"
+
+
+def test_singular_when_the_count_reads_one():
everest = _stick("everest")
- assert pv.describe(28 * 60, everest).value == "2"
+ assert (pv.describe(14 * 60, everest).value, pv.describe(14 * 60, everest).label) == ("1", "Everest summit day")
+ assert pv.describe(14 * 60 * 1.04, everest).label == "Everest summit day" # still reads "1"
+ assert pv.describe(14 * 60 * 1.06, everest).label == "Everest summit days" # reads "1.1"
assert pv.describe(28 * 60, everest).label == "Everest summit days"
- assert pv.describe(14 * 60, everest).label == "Everest summit day" # singular at exactly one
- half = pv.describe(7 * 60, everest)
- assert half.value == "50%" and half.label.startswith("of an Everest")
- assert pv.describe(14 * 60 * 2.4, everest).value == "2.4"
- assert pv.describe(14 * 60 * 1234, everest).value == "1,234"
+ assert pv.describe(600 * 60, _stick("language")).label == "French course"
+ assert pv.describe(10_000 * 60, _stick("mastery")).label == "path to mastery"
+ assert pv.describe(1_000_000, UNIT).label == "things" # "1 million things"
+ walk = pv.describe(12, _stick("walk"))
+ assert (walk.value, walk.label) == ("1", "km walked") # units read the same either way
-def test_special_phrasings():
- assert pv.describe(5, _stick("walk")).value == "417 m" # short walks read in metres
- assert pv.describe(600 * 60 * 2.5, _stick("language")).value == "2.5×"
+def test_walking_reads_in_metres_then_km():
+ metres = pv.describe(5, _stick("metres"))
+ assert (metres.value, metres.label) == ("417", "m walked")
+ for minutes in _totals():
+ ranked = {s.key for s in pv._ranked(minutes)}
+ assert ranked & {"metres", "walk"}, minutes
+ assert not {"metres", "walk"} <= ranked, minutes # never both at once
-def test_pick_is_varied_and_readable():
- for minutes in (5, 90, 283, 3000, 36000, 300000):
- facts = pv.pick(minutes, 3)
- assert 1 <= len(facts) <= 3
- assert len({f.key for f in facts}) == len(facts)
- for f in facts:
- assert 0.02 <= f.ratio <= _stick(f.key).max_count
- assert pv.pick(0, 3) == []
+def test_no_percentages_only_counts():
+ for minutes in _totals():
+ for offset in range(3):
+ for fact in pv.pick(minutes, 6, offset):
+ assert "%" not in fact.value + fact.label + fact.basis, (minutes, fact)
+ assert fact.ratio >= 1, (minutes, fact)
+ number = fact.value.removesuffix(" million").replace(",", "")
+ assert float(number) >= 1, (minutes, fact)
+
+
+def test_every_total_has_six_readable_picks():
+ for minutes in _totals(high=100_000 * 60):
+ assert pv.readable_count(minutes) >= 6, minutes
+ for offset in range(3):
+ facts = pv.pick(minutes, 6, offset)
+ assert len(facts) == 6, (minutes, offset)
+ assert len({f.key for f in facts}) == 6, (minutes, offset)
+ assert pv.pick(0, 6) == [] and pv.pick(-5, 6) == []
+
+
+def test_first_picks_read_well_and_vary():
+ for minutes in (30, 90, 283, 3000, 36000, 600000):
+ facts = pv.pick(minutes, 6)
+ assert all(f.ratio < 100 for f in facts), minutes
+ assert sum(2 <= f.ratio <= 30 for f in facts) >= 4, minutes
+ sticks = [_stick(f.key) for f in facts]
+ assert len({s.group for s in sticks}) >= 4, minutes
+ assert len({s.icon for s in sticks}) == 6, minutes
+
+
+def test_big_counts_wait_for_shuffle():
+ for minutes in (30, 283, 3000):
+ assert "heartbeats" not in _keys(minutes), minutes
+ assert any("heartbeats" in _keys(minutes, k) for k in range(1, 20)), minutes
def test_shuffle_rotates():
- first = [f.key for f in pv.pick(3000, 3, offset=0)]
- second = [f.key for f in pv.pick(3000, 3, offset=1)]
- assert first != second
+ for minutes in (1, 5, 30, 3000, 600000):
+ sets = [_keys(minutes, k) for k in range(5)]
+ assert all(a != b for a, b in zip(sets, sets[1:], strict=False)), minutes # every press brings something new
+ assert pv.pick(3000, 6, 4) == pv.pick(3000, 6, 4) # deterministic
+ seen: set[str] = set()
+ for k in range(pv.readable_count(3000)):
+ seen |= _keys(3000, k)
+ assert len(seen) == pv.readable_count(3000) # keep pressing and everything turns up
+
+
+def test_yardsticks_span_seconds_to_thousands_of_hours():
+ assert len(pv.YARDSTICKS) >= 35
+ assert len({s.key for s in pv.YARDSTICKS}) == len(pv.YARDSTICKS)
+ assert min(s.minutes for s in pv.YARDSTICKS) < 1
+ assert max(s.minutes for s in pv.YARDSTICKS) >= 1000 * 60
+ assert len({s.group for s in pv.YARDSTICKS}) >= 6
-def test_every_yardstick_has_an_icon():
+def test_every_yardstick_has_an_icon_and_a_basis():
for stick in pv.YARDSTICKS:
assert (assets_dir() / "icons" / f"{stick.icon}.svg").exists(), stick.icon
- assert stick.basis and stick.many and stick.part
+ assert stick.many and stick.basis
+ assert "—" not in stick.many + stick.one + stick.basis # no em dashes
diff --git a/tests/test_rewards.py b/tests/test_rewards.py
deleted file mode 100644
index 91b2907..0000000
--- a/tests/test_rewards.py
+++ /dev/null
@@ -1,107 +0,0 @@
-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_ui.py b/tests/test_ui.py
index b6ec485..6beb9d3 100644
--- a/tests/test_ui.py
+++ b/tests/test_ui.py
@@ -96,14 +96,35 @@ def test_exclude_with_undo(window, qapp):
assert queries.get_app(app_id)["is_hidden"] == 0
-def test_claim_from_rewards_page(window, qapp):
+def test_focus_page_chest_and_village_harvest(window, qapp):
+ from datetime import date
+
+ from apptrackr.game import state as game_state
+ from apptrackr.rewards import engine
+
view = window._views["rewards"]
window.show_page("rewards")
+ assert view.flow_card.isVisible() and not view.chest_btn.isVisible()
+ game_state.unlock_chest(date.today().isoformat())
+ view.refresh()
+ assert view.chest_btn.isVisible()
+ credits = engine.get_profile()["credits"]
+ view._open_chest()
+ assert engine.get_profile()["credits"] > credits
+ assert game_state.ready_chests() == []
view._claim_all()
- from apptrackr.rewards import engine
-
assert engine.unclaimed_count() == 0
+ village = window._views["village"]
+ window.show_page("village")
+ before = game_state.get_village()["inventory"]
+ crop = game_state.harvest()
+ assert crop["points"] > 0 # the demo village has focus time waiting
+ village._collect()
+ after = game_state.get_village()["inventory"]
+ assert all(after[r] == before[r] + n for r, n in crop["resources"].items())
+ assert game_state.harvest()["points"] < 1
+
def test_unsupported_platform_shows_state(qapp):
from apptrackr.ui.main import MainWindow
@@ -215,3 +236,41 @@ def test_other_terms_card(window, qapp):
card.period._group.button(2).click()
qapp.processEvents()
assert card.current_period == "all" and db.get_setting("perspective_period") == "all"
+
+
+def test_floating_timer_follows_the_app_in_front(window, qapp, monkeypatch):
+ from apptrackr.game import focus
+ from apptrackr.ui import motion
+
+ motion.force(False) # fades finish at once
+ overlay = window._overlay
+ monkeypatch.setattr(window, "_app_in_front", lambda: False)
+ window._update_overlay()
+ qapp.processEvents()
+ assert overlay.isVisible()
+ snap = window._tracker.snapshot()
+ assert overlay._name == queries.get_app(snap.app_id)["name"]
+ assert overlay._focus == (snap.app_id in focus.focus_app_ids())
+ assert not overlay.grab().isNull()
+
+ monkeypatch.setattr(window, "_app_in_front", lambda: True) # AppTrackr itself is in front
+ window._update_overlay()
+ qapp.processEvents()
+ assert not overlay.isVisible()
+
+ monkeypatch.setattr(window, "_app_in_front", lambda: False)
+ monkeypatch.setattr(window._tracker, "foreground_fullscreen", lambda: True)
+ window._update_overlay()
+ assert not overlay.isVisible()
+ monkeypatch.setattr(window._tracker, "foreground_fullscreen", lambda: False)
+
+ window.set_overlay_enabled(False)
+ assert not overlay.isVisible() and not db.get_bool("overlay_enabled", True)
+ window.set_overlay_enabled(True)
+ assert overlay.isVisible()
+
+ overlay.move(120, 140)
+ overlay.save_position()
+ assert db.get_setting("overlay_pos") == "120,140"
+ overlay.hide_requested.emit()
+ assert not overlay.isVisible() and not window._overlay_enabled
diff --git a/tests/test_upgrade.py b/tests/test_upgrade.py
index 6a6f616..c04615f 100644
--- a/tests/test_upgrade.py
+++ b/tests/test_upgrade.py
@@ -155,6 +155,17 @@ def test_upgraded_data_works_in_this_version(upgraded):
xp = engine.get_profile()["xp"]
applied = engine.claim_reward(pending[0]["event_id"])
assert engine.get_profile()["xp"] == xp + applied.get("xp", 0)
+ # 1.x earning apps are the focus apps now, and the old village keeps working.
+ from apptrackr.game import focus
+ from apptrackr.rewards import rules
+
+ assert focus.focus_app_ids() == {queries.find_app_id("code.exe")}
+ assert rules.adopt_favorites_once() == 0
+ inventory = dict(game_state.get_village()["inventory"])
+ game_state.collect()
+ village = game_state.get_village()
+ assert all(village["inventory"][r] >= n for r, n in inventory.items())
+ assert game_state.building_level(village, "workshop") == 1
assert theme.configure(accent=db.get_setting("ui_theme")).accent == theme.build("Graphite", "Purple").accent
assert db.get_int("idle_threshold_sec") == 600 and db.get_bool("minimize_to_tray", True) is False
theme.configure("dark", theme.DEFAULT_ACCENT)