diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..d068c71
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,43 @@
+name: Bug report
+description: Something in Foci isn't working the way it should
+labels: [bug]
+body:
+ - type: textarea
+ id: what
+ attributes:
+ label: What happened?
+ description: What did you expect, and what happened instead?
+ validations:
+ required: true
+ - type: textarea
+ id: steps
+ attributes:
+ label: Steps to reproduce
+ placeholder: |
+ 1. Open Foci
+ 2. Right-click a to-do → Schedule for Tomorrow
+ 3. ...
+ validations:
+ required: true
+ - type: dropdown
+ id: how
+ attributes:
+ label: How do you run Foci?
+ options:
+ - From source (python main.py)
+ - Packaged .exe / app
+ validations:
+ required: true
+ - type: input
+ id: os
+ attributes:
+ label: OS and Python version
+ placeholder: Windows 11, Python 3.12
+ validations:
+ required: true
+ - type: textarea
+ id: logs
+ attributes:
+ label: Console output or screenshot
+ description: Anything printed in the terminal, or a screenshot of the problem. Remove anything personal.
+ render: text
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..0086358
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1 @@
+blank_issues_enabled: true
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..5bf984a
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,22 @@
+name: Feature request
+description: Suggest an idea for Foci
+labels: [enhancement]
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: What would this help you do?
+ description: Describe the situation or frustration, not just the solution.
+ validations:
+ required: true
+ - type: textarea
+ id: idea
+ attributes:
+ label: What would you like to see?
+ validations:
+ required: true
+ - type: textarea
+ id: calm
+ attributes:
+ label: How does it keep Foci calm?
+ description: Foci tries to avoid noisy, guilt-inducing UI. Any thoughts on how this fits?
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..fe5fb1d
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,13 @@
+## What does this change?
+
+
+
+## How did you test it?
+
+- [ ] `pytest -q` passes
+- [ ] `ruff check .` passes
+- [ ] Ran the app and tried the change by hand
+
+## Screenshots / GIF
+
+
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..eb9ddaa
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,55 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ lint:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - run: pip install ruff
+ - run: ruff check .
+
+ test:
+ name: test (${{ matrix.os }}, py${{ matrix.python-version }})
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ python-version: ["3.10", "3.13"]
+ env:
+ SDL_VIDEODRIVER: dummy
+ SDL_AUDIODRIVER: dummy
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ cache: pip
+ - run: pip install -r requirements.txt pytest
+ - run: pytest -q
+ - name: Smoke test (app starts headless)
+ shell: bash
+ run: |
+ python - <<'PY'
+ import os, subprocess, sys, tempfile
+ env = dict(os.environ, FOCI_DATA_DIR=tempfile.mkdtemp())
+ p = subprocess.Popen([sys.executable, "main.py"], env=env)
+ try:
+ code = p.wait(timeout=8)
+ except subprocess.TimeoutExpired:
+ p.kill()
+ print("main.py is running after 8s - OK")
+ else:
+ sys.exit(f"main.py exited early with code {code}")
+ PY
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..d7a5cae
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,34 @@
+# Changelog
+
+All notable changes to Foci are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+
+## [Unreleased]
+
+### Fixed
+- **Packaged app lost all data on restart.** The one-file `.exe` wrote events, to-dos, settings and coins into PyInstaller's temporary extraction folder, which is deleted on exit. User data now lives in the OS app-data folder for packaged builds (`%APPDATA%\Foci` etc.) and stays in `assets/` when running from source.
+- Launching `python path/to/main.py` from a different directory couldn't find fonts, icons or the coin sprite sheet. Resources now resolve relative to the app, not the working directory.
+- "Schedule for Tomorrow" set the `tmr` tag and then immediately deleted it.
+- Date tags didn't roll over for to-dos inside folders.
+- "Delete completed" ignored completed to-dos inside folders.
+- Google Calendar: fixed an import that always failed (`google.auth_oauthlib` → `google_auth_oauthlib`), the day window being computed in UTC instead of local time, event times not being converted to local time, and all-day events being imported as 24-hour blocks.
+- `format_time` wrapped around for durations of 24 hours or more.
+- An unreadable data file (e.g. wrong text encoding) no longer crashes startup.
+- Packaged builds call `multiprocessing.freeze_support()` so the lofi player subprocess starts correctly.
+
+### Added
+- To-dos show a date pill (*Today*, *Tomorrow*, *on Mon*), red when overdue.
+- `FOCI_DATA_DIR` environment variable to choose where data is stored.
+- `foci_store.py`: persistence and validation split out of `main.py` so it can be tested.
+- Test suite (`pytest`) and GitHub Actions CI on Windows, macOS and Linux.
+- Contributor guide, issue templates and pull request template.
+
+### Changed
+- The built executable is named `Foci.exe` instead of `main.exe`.
+
+## [1.0.0] - initial release
+
+- Day timeline with drag-to-create, move and resize events
+- Nested to-do list with folders
+- Focus timer, lofi music player with Windows media-key integration
+- 8 themes, font picker, confetti, coin rewards, stats and weekly view
+- Local-first JSON storage, PyInstaller build
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..e0d6832
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,59 @@
+# Contributing to Foci
+
+Thanks for your interest! Foci is a small, calm desktop planner, and contributions of any size are welcome: bug reports, typo fixes, new themes, or bigger features.
+
+## Getting set up
+
+```bash
+git clone https://github.com/akshit-python-programmer/Foci.git
+cd Foci
+python -m venv .venv
+source .venv/bin/activate # Windows: .venv\Scripts\activate
+pip install -r requirements.txt pytest ruff
+python main.py
+```
+
+While you're developing, you can keep your real planner data out of the way by pointing Foci at a scratch folder:
+
+```bash
+FOCI_DATA_DIR=/tmp/foci-dev python main.py
+```
+
+## Before you open a pull request
+
+```bash
+ruff check .
+pytest -q
+```
+
+CI runs both on Windows, macOS and Linux, and also checks that `main.py` starts in a headless window.
+
+## Project layout
+
+| File | What's in it |
+|---|---|
+| `main.py` | The app: theme table, game loop, all drawing and input handling |
+| `foci_store.py` | Loading, saving and validating settings / events / to-dos. No pygame, fully unit-tested. **Put new data logic here.** |
+| `utility.py` | Drawing and math helpers shared by the UI |
+| `google_calendar.py` | Experimental Google Calendar sync |
+| `progress.py` | Standalone focus-timer demo |
+| `tests/` | pytest suite |
+| `assets/` | Fonts, icons, music, and `*.example.json` data templates |
+
+`main.py` opens a window as soon as it's imported, so it can't be unit-tested directly. If you're adding logic that doesn't need to draw anything (date math, data cleanup, sorting), put it in `foci_store.py` with a test and call it from `main.py`.
+
+## Guidelines
+
+- **Keep it calm.** Foci is meant for people who find most productivity apps overwhelming. New UI should be quiet: soft colours, gentle animation, nothing that nags or punishes.
+- **Don't break people's data.** Anything that changes the JSON format must still load old files. `foci_store.sanitize_*` is where to add defaults for new fields.
+- **Small PRs are easier to review.** One fix or feature per PR, with a short description of what changed and how you tested it.
+- **Include a screenshot or GIF** for visual changes.
+- For bugs, add a regression test in `tests/` when you can.
+
+## Reporting bugs
+
+Please open an issue using the bug report template and include your OS, Python version, and steps to reproduce. If the bug involves your data, attach a trimmed copy of the relevant JSON file (remove anything personal).
+
+## Licence
+
+By contributing you agree that your contributions are licensed under the [MIT License](LICENSE).
diff --git a/README.md b/README.md
index a51f1d6..a3d01ab 100644
--- a/README.md
+++ b/README.md
@@ -6,6 +6,8 @@



+[](https://github.com/akshit-python-programmer/Foci/actions/workflows/ci.yml)
+[](CONTRIBUTING.md)
@@ -62,22 +64,31 @@ To try just the standalone focus timer:
python progress.py
```
+### Run the tests
+
+```bash
+pip install pytest
+pytest -q
+```
+
### Build a standalone .exe
```bash
pip install pyinstaller
pyinstaller main.spec
-# output in dist/
+# output: dist/Foci.exe
```
### Optional: Google Calendar sync
1. In [Google Cloud Console](https://console.cloud.google.com/), create an OAuth 2.0 Desktop client and enable the Calendar API.
-2. Download `credentials.json` → place in `assets/`.
-3. First run opens a browser to authorize; token stored locally as `assets/token.json`.
+2. Download `credentials.json` → place it in your [data folder](#your-data) (`assets/` when running from source).
+3. First run opens a browser to authorize; the token is stored next to it as `token.json`.
Both files are git-ignored and must never be committed.
+> **Status: experimental.** `google_calendar.py` can pull a day's events from Google, but it isn't wired into the app's UI yet and pushing local changes back to Google isn't implemented. See the open issues if you'd like to help.
+
---
## Tech stack
@@ -112,10 +123,10 @@ Both files are git-ignored and must never be committed.
### Nested to-do list
- Flat tasks and collapsible folders (e.g. Physics → Kinematics → today's problems)
-- Date tags: *today*, *tomorrow*, *someday* — tags roll forward automatically at midnight
-- Drag-and-drop reordering within the list
+- Date tags: *Today*, *Tomorrow*, *on Mon*. Shown as a pill on each to-do (red when overdue) and rolled forward automatically each day, including to-dos inside folders
+- Drag a to-do onto the timeline to turn it into an event (drag-to-reorder within the list is not implemented yet)
- Right-click context menu to schedule a task (Today / Tomorrow / Someday)
-- Delete completed tasks in bulk with one button
+- Delete completed tasks in bulk with one button (including ones inside folders)
### Focus timer
- Click the ▶ button on any currently-active event to open a standalone focus timer popup
@@ -151,11 +162,11 @@ Both files are git-ignored and must never be committed.
- Scrollable modal: theme picker (shows each theme's actual colors as a preview), font picker, day start/end hour sliders, calendar zoom slider (30–80 px/hr), sound effects toggle, confetti toggle, lofi toggle
### Local-first & privacy
-- All data lives in plain JSON files in `assets/`: `events.json`, `todos.json`, `settings.json`, `player_data.json`
+- All data lives in plain JSON files on your machine: `events.json`, `todos.json`, `settings.json`, `player_data.json`
- Personal files are git-ignored; `*.example.json` templates are included
- Nothing is uploaded anywhere
-### Optional: Google Calendar sync
+### Optional: Google Calendar sync (experimental)
- `google_calendar.py` — standalone OAuth2 flow using `google-api-python-client`
- Bring your own `credentials.json` from Google Cloud Console; token is stored locally and never committed
@@ -165,12 +176,28 @@ Both files are git-ignored and must never be committed.
| File | Contents |
|---|---|
-| `assets/settings.json` | Theme, day hours, zoom, toggles |
-| `assets/todos.json` | To-do list and folder tree |
-| `assets/events.json` | Scheduled calendar events |
-| `assets/player_data.json` | Coin count |
+| `settings.json` | Theme, day hours, zoom, toggles |
+| `todos.json` | To-do list and folder tree |
+| `events.json` | Scheduled calendar events |
+| `player_data.json` | Coin count |
+
+Where they live:
+
+| How you run Foci | Data folder |
+|---|---|
+| From source (`python main.py`) | `assets/` in the repo |
+| Packaged app on Windows | `%APPDATA%\Foci` |
+| Packaged app on macOS | `~/Library/Application Support/Foci` |
+| Packaged app on Linux | `$XDG_DATA_HOME/Foci` (default `~/.local/share/Foci`) |
+| Any, with `FOCI_DATA_DIR` set | that folder |
+
+The files in `assets/` are git-ignored. Copy an `*.example.json` to get started, or just run the app and it creates fresh files. Corrupt or hand-edited files are repaired field by field on load instead of crashing the app.
+
+---
+
+## Contributing
-These are git-ignored. Copy an `*.example.json` to get started, or just run the app — it creates fresh files automatically.
+Bug reports, ideas and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, the project layout and how to run the tests. Changes are tracked in [CHANGELOG.md](CHANGELOG.md).
---
diff --git a/docs/README.md b/docs/README.md
index 33e195e..626e823 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,7 +1,5 @@
# docs
-Put screenshots and demo media here.
+- [TECHNICAL.md](TECHNICAL.md): architecture and engineering notes.
-The main README references `docs/demo.png` — drop a screenshot or short GIF of Foci
-(e.g. dragging an event onto the timeline and checking off a task) at that path to make
-the repo's landing page pop.
+Screenshots and demo GIFs used by the main README live in [`../demo`](../demo).
diff --git a/docs/TECHNICAL.md b/docs/TECHNICAL.md
index 8442a7a..e2f6c23 100644
--- a/docs/TECHNICAL.md
+++ b/docs/TECHNICAL.md
@@ -13,15 +13,18 @@ Foci is a single-process desktop app with one deliberate exception: the lofi mus
```
main.py (main process, 60 fps game loop)
│
+├── foci_store.py persistence + validation (pure Python, no pygame, unit-tested)
├── utility.py helper functions (math, color, font cache, drawing primitives)
-├── google_calendar.py optional OAuth2 calendar sync (self-contained)
+├── google_calendar.py optional OAuth2 calendar sync (experimental, self-contained)
├── progress.py standalone focus-timer demo
│
└── subprocess: simple_music_player_process()
└── SMTCController WinRT media-key / tray integration
```
-Data is stored in four plain JSON files in `assets/`. No database, no cloud, no framework.
+Data is stored in four plain JSON files. No database, no cloud, no framework.
+
+Bundled resources (fonts, icons, music) and user data are kept apart on purpose. `foci_store.app_root()` points at the read-only resources, which in a PyInstaller one-file build are unpacked to a temporary `sys._MEIPASS` folder that's deleted on exit. `foci_store.user_data_dir()` points at a writable per-user folder (`assets/` from source, the OS app-data folder when packaged, or `FOCI_DATA_DIR`). Every JSON write goes to a temp file first and then `os.replace()`s it, so a crash mid-save can't leave a half-written file.
---
diff --git a/foci_store.py b/foci_store.py
new file mode 100644
index 0000000..cb47b35
--- /dev/null
+++ b/foci_store.py
@@ -0,0 +1,320 @@
+"""Persistence and data-validation helpers for Foci.
+
+Everything in this module is plain Python with no pygame dependency, so it can
+be imported and unit-tested without opening a window. ``main.py`` wraps these
+functions with the app's live defaults (theme list, day hours, font paths).
+"""
+
+import datetime
+import json
+import os
+import sys
+
+APP_NAME = "Foci"
+DATE_FORMAT = "%Y-%m-%d"
+
+DEFAULT_EVENT_COLOR = [181, 234, 215]
+MIN_EVENT_MINUTES = 15
+MAX_EVENT_MINUTES = 24 * 60
+
+
+# --- Paths -----------------------------------------------------------------
+
+def app_root():
+ """Directory that holds the bundled read-only resources (fonts, icons, music).
+
+ In a PyInstaller build this is the temporary extraction folder; when running
+ from source it is the folder containing this file (not the current working
+ directory, so ``python path/to/main.py`` works from anywhere).
+ """
+ bundle_dir = getattr(sys, "_MEIPASS", None)
+ if bundle_dir:
+ return bundle_dir
+ return os.path.dirname(os.path.abspath(__file__))
+
+
+def is_frozen():
+ return bool(getattr(sys, "frozen", False) or getattr(sys, "_MEIPASS", None))
+
+
+def platform_data_dir(app_name=APP_NAME, platform=None, environ=None):
+ """Per-user writable directory for app data on the current OS."""
+ platform = platform or sys.platform
+ environ = os.environ if environ is None else environ
+ home = os.path.expanduser("~")
+
+ if platform.startswith("win"):
+ base = environ.get("APPDATA") or os.path.join(home, "AppData", "Roaming")
+ elif platform == "darwin":
+ base = os.path.join(home, "Library", "Application Support")
+ else:
+ base = environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share")
+ return os.path.join(base, app_name)
+
+
+def user_data_dir(environ=None):
+ """Where user files (events, todos, settings, coins, OAuth token) live.
+
+ Resolution order:
+ 1. ``FOCI_DATA_DIR`` environment variable, if set.
+ 2. The platform data directory when running as a packaged executable
+ (the PyInstaller temp folder is deleted on exit, so data must not be
+ written there).
+ 3. ``assets/`` next to the source when running from a checkout, which is
+ where Foci has always kept its JSON files.
+ """
+ environ = os.environ if environ is None else environ
+ override = environ.get("FOCI_DATA_DIR")
+ if override:
+ return os.path.abspath(os.path.expanduser(override))
+ if is_frozen():
+ return platform_data_dir(environ=environ)
+ return os.path.join(app_root(), "assets")
+
+
+# --- JSON I/O ----------------------------------------------------------------
+
+def write_json_file(path, data, *, indent=2, ensure_ascii=True):
+ """Atomically write ``data`` as JSON (write to a temp file, then rename)."""
+ directory = os.path.dirname(path)
+ if directory:
+ os.makedirs(directory, exist_ok=True)
+ temp_path = f"{path}.tmp"
+ with open(temp_path, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=indent, ensure_ascii=ensure_ascii)
+ os.replace(temp_path, path)
+
+
+def read_json_file(path, default=None):
+ """Read JSON from ``path``; return ``default`` if missing or unreadable."""
+ try:
+ with open(path, "r", encoding="utf-8") as f:
+ return json.load(f)
+ except FileNotFoundError:
+ return default
+ except (OSError, ValueError) as e: # JSONDecodeError and UnicodeDecodeError are ValueErrors
+ print(f"Warning: could not read {os.path.basename(path)} ({e}). Using defaults.")
+ return default
+
+
+# --- Small helpers -----------------------------------------------------------
+
+def safe_int(value, default):
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return default
+
+
+def _clamp(val, lo, hi):
+ return max(lo, min(val, hi))
+
+
+# --- Settings ----------------------------------------------------------------
+
+def sanitize_settings(loaded_settings, defaults, theme_names, resolve_font=None):
+ """Merge ``loaded_settings`` over ``defaults`` and coerce every field to a valid value."""
+ sanitized = dict(defaults)
+ if isinstance(loaded_settings, dict):
+ sanitized.update(loaded_settings)
+
+ theme = sanitized.get("theme")
+ if theme not in theme_names:
+ theme = defaults["theme"]
+
+ start_hour = _clamp(safe_int(sanitized.get("start_hour"), defaults["start_hour"]), 0, 12)
+ end_hour = _clamp(safe_int(sanitized.get("end_hour"), defaults["end_hour"]), 13, 23)
+ if end_hour <= start_hour:
+ start_hour, end_hour = defaults["start_hour"], defaults["end_hour"]
+
+ hour_height = _clamp(safe_int(sanitized.get("hour_height"), defaults["hour_height"]), 30, 80)
+ font_path = sanitized.get("font_path")
+ if resolve_font is not None:
+ font_path = resolve_font(font_path)
+
+ return {
+ "theme": theme,
+ "start_hour": start_hour,
+ "end_hour": end_hour,
+ "sounds_on": bool(sanitized.get("sounds_on", defaults["sounds_on"])),
+ "hour_height": hour_height,
+ "confetti_on": bool(sanitized.get("confetti_on", defaults["confetti_on"])),
+ "font_path": font_path,
+ }
+
+
+# --- Events ------------------------------------------------------------------
+
+def sanitize_event(raw_event, default_hour=5):
+ """Return a cleaned copy of a calendar event dict, or ``None`` if it is unusable."""
+ if not isinstance(raw_event, dict):
+ return None
+
+ event = dict(raw_event)
+ event["title"] = str(event.get("title") or "Untitled")
+ event["hour"] = _clamp(safe_int(event.get("hour", default_hour), default_hour), 0, 23)
+ event["minute"] = _clamp(safe_int(event.get("minute", 0), 0), 0, 59)
+ event["duration"] = _clamp(
+ safe_int(event.get("duration", 60), 60), MIN_EVENT_MINUTES, MAX_EVENT_MINUTES
+ )
+ event["done"] = bool(event.get("done", False))
+
+ color = event.get("color")
+ if not (
+ isinstance(color, (list, tuple))
+ and len(color) == 3
+ and all(isinstance(c, int) and not isinstance(c, bool) and 0 <= c <= 255 for c in color)
+ ):
+ color = DEFAULT_EVENT_COLOR
+ event["color"] = list(color)
+
+ event["icon"] = max(0, safe_int(event.get("icon", 0), 0))
+
+ google_id = event.get("google_id")
+ if google_id is not None and not isinstance(google_id, str):
+ event.pop("google_id", None)
+
+ return event
+
+
+def sanitize_events_by_date(raw_events, default_hour=5):
+ """Clean the ``{"YYYY-MM-DD": [event, ...]}`` mapping stored in events.json."""
+ if not isinstance(raw_events, dict):
+ return {}
+ cleaned = {}
+ for date_key, date_events in raw_events.items():
+ if not isinstance(date_key, str):
+ continue
+ day = []
+ if isinstance(date_events, list):
+ for raw_event in date_events:
+ event = sanitize_event(raw_event, default_hour)
+ if event is not None:
+ day.append(event)
+ cleaned[date_key] = day
+ return cleaned
+
+
+# --- To-dos ------------------------------------------------------------------
+
+def sanitize_todos(items):
+ """Clean the nested to-do tree (todos and folders with ``children``)."""
+ if not isinstance(items, list):
+ return []
+
+ cleaned = []
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ if item.get("type") == "folder":
+ cleaned.append({
+ "type": "folder",
+ "name": str(item.get("name") or "Untitled Folder"),
+ "is_open": bool(item.get("is_open", False)),
+ "children": sanitize_todos(item.get("children", [])),
+ })
+ else:
+ todo_item = {
+ "type": "todo",
+ "title": str(item.get("title") or "Untitled To-do"),
+ "done": bool(item.get("done", False)),
+ }
+ if isinstance(item.get("tag"), str):
+ todo_item["tag"] = item["tag"]
+ if isinstance(item.get("date"), str):
+ todo_item["date"] = item["date"]
+ cleaned.append(todo_item)
+ return cleaned
+
+
+def schedule_todo(todo, when, today=None):
+ """Apply a context-menu choice ("today", "tomorrow" or "someday") to a to-do in place."""
+ today = today or datetime.date.today()
+ if when == "today":
+ todo["date"] = today.strftime(DATE_FORMAT)
+ todo["tag"] = "today"
+ elif when == "tomorrow":
+ todo["date"] = (today + datetime.timedelta(days=1)).strftime(DATE_FORMAT)
+ todo["tag"] = "tmr"
+ elif when == "someday":
+ todo.pop("date", None)
+ todo.pop("tag", None)
+ else:
+ raise ValueError(f"unknown schedule option: {when!r}")
+ return todo
+
+
+def roll_todo_tags(items, today=None):
+ """Advance relative date tags so they stay truthful as days pass.
+
+ * a "tmr" to-do whose date has arrived becomes "today"
+ * a "today"/"tmr" to-do whose date is in the past becomes "on "
+
+ Folders are walked recursively, so to-dos filed inside folders roll over too.
+ """
+ today = today or datetime.date.today()
+ for item in items:
+ if item.get("type") == "folder":
+ roll_todo_tags(item.get("children", []), today)
+ continue
+
+ tag = item.get("tag")
+ if tag not in ("today", "tmr") or "date" not in item:
+ continue
+ try:
+ todo_date = datetime.datetime.strptime(item["date"], DATE_FORMAT).date()
+ except (TypeError, ValueError):
+ continue # malformed date: leave the item alone
+
+ if todo_date < today:
+ item["tag"] = f"on {todo_date.strftime('%a')}"
+ elif tag == "tmr" and todo_date == today:
+ item["tag"] = "today"
+ return items
+
+
+def has_completed_todos(items):
+ """True if any to-do in the tree (folders included) is checked off."""
+ for item in items:
+ if item.get("type") == "folder":
+ if has_completed_todos(item.get("children", [])):
+ return True
+ elif item.get("done"):
+ return True
+ return False
+
+
+def remove_completed_todos(items):
+ """Return a copy of the tree without checked-off to-dos; folders are kept."""
+ kept = []
+ for item in items:
+ if item.get("type") == "folder":
+ folder = dict(item)
+ folder["children"] = remove_completed_todos(item.get("children", []))
+ kept.append(folder)
+ elif not item.get("done"):
+ kept.append(item)
+ return kept
+
+
+def todo_tag_label(item, today=None):
+ """Short label shown on a to-do's date pill, or ``None`` if it has no tag.
+
+ Returns ``(label, is_overdue)``.
+ """
+ tag = item.get("tag")
+ if not isinstance(tag, str) or not tag:
+ return None
+ today = today or datetime.date.today()
+ overdue = False
+ date_str = item.get("date")
+ if isinstance(date_str, str):
+ try:
+ overdue = (
+ datetime.datetime.strptime(date_str, DATE_FORMAT).date() < today
+ and not item.get("done")
+ )
+ except ValueError:
+ pass
+ labels = {"today": "Today", "tmr": "Tomorrow"}
+ return labels.get(tag, tag), overdue
diff --git a/google_calendar.py b/google_calendar.py
index 91fdf32..706f64c 100644
--- a/google_calendar.py
+++ b/google_calendar.py
@@ -1,32 +1,97 @@
+"""Optional Google Calendar sync for Foci (experimental, not yet wired into the UI).
+
+Needs the extra dependencies from requirements.txt and a ``credentials.json``
+OAuth client file in the Foci data directory (``assets/`` when running from
+source). The pure conversion helpers at the top of this module work without
+the Google libraries installed, which keeps them unit-testable.
+"""
+
import datetime
import os.path
-import sys
-from google.auth.transport.requests import Request
-from google.oauth2.credentials import Credentials
-from google.auth_oauthlib.flow import InstalledAppFlow
-from googleapiclient.discovery import build
-from googleapiclient.errors import HttpError
+try:
+ from google.auth.transport.requests import Request
+ from google.oauth2.credentials import Credentials
+ from google_auth_oauthlib.flow import InstalledAppFlow
+ from googleapiclient.discovery import build
+ from googleapiclient.errors import HttpError
+ GOOGLE_LIBS_AVAILABLE = True
+except ImportError: # optional dependency
+ GOOGLE_LIBS_AVAILABLE = False
+
+ class HttpError(Exception):
+ pass
# If modifying these scopes, delete token.json.
SCOPES = ["https://www.googleapis.com/auth/calendar"]
-def resource_path(relative_path):
- """Get absolute path to resource (works for dev and .exe)"""
+from foci_store import user_data_dir
+
+# Both files are per-user secrets, so they live in the writable data directory
+# (assets/ when running from source) rather than inside the bundled app.
+CREDENTIALS_FILE = os.path.join(user_data_dir(), "credentials.json")
+TOKEN_FILE = os.path.join(user_data_dir(), "token.json")
+
+SYNCED_EVENT_COLOR = [135, 206, 250]
+
+
+def local_day_bounds(date, tz=None):
+ """RFC 3339 start/end of ``date`` in the user's local timezone.
+
+ The previous version appended "Z" to a naive local midnight, which told
+ Google the day started at 00:00 UTC and returned the wrong events for
+ anyone not in UTC.
+ """
+ tz = tz or datetime.datetime.now().astimezone().tzinfo
+ start = datetime.datetime.combine(date, datetime.time.min, tzinfo=tz)
+ end = start + datetime.timedelta(days=1)
+ return start.isoformat(), end.isoformat()
+
+
+def _parse_rfc3339(value):
+ # Python < 3.11 fromisoformat() does not accept a trailing "Z".
+ return datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
+
+
+def gcal_event_to_local(gcal_event, tz=None):
+ """Convert a Google Calendar API event into a Foci event dict.
+
+ Returns ``None`` for all-day events (they have no time slot on the
+ timeline) and for events without usable start/end times.
+ Times are converted to the local timezone before taking hour/minute.
+ """
+ start = (gcal_event.get("start") or {}).get("dateTime")
+ end = (gcal_event.get("end") or {}).get("dateTime")
+ if not start or not end:
+ return None # all-day ("date") or malformed event
+
+ tz = tz or datetime.datetime.now().astimezone().tzinfo
try:
- base_path = sys._MEIPASS
- except Exception:
- base_path = os.path.abspath(".")
- return os.path.join(base_path, relative_path)
+ start_dt = _parse_rfc3339(start).astimezone(tz)
+ end_dt = _parse_rfc3339(end).astimezone(tz)
+ except ValueError:
+ return None
-CREDENTIALS_FILE = resource_path(os.path.join("assets", "credentials.json"))
-TOKEN_FILE = resource_path(os.path.join("assets", "token.json"))
+ duration = max(15, int((end_dt - start_dt).total_seconds() // 60))
+ return {
+ "title": gcal_event.get("summary") or "No Title",
+ "hour": start_dt.hour,
+ "minute": start_dt.minute,
+ "duration": duration,
+ "done": False,
+ "color": list(SYNCED_EVENT_COLOR),
+ "icon": 0,
+ "google_id": gcal_event.get("id"),
+ }
def get_service():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
+ if not GOOGLE_LIBS_AVAILABLE:
+ print("Google Calendar sync needs: pip install google-api-python-client google-auth-oauthlib")
+ return None
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
@@ -56,6 +121,7 @@ def get_service():
print(f"An error occurred during authentication: {e}")
return None
# Save the credentials for the next run
+ os.makedirs(os.path.dirname(TOKEN_FILE), exist_ok=True)
with open(TOKEN_FILE, "w") as token:
token.write(creds.to_json())
@@ -78,8 +144,7 @@ def sync_events(date, local_events):
return local_events # Return local events if sync fails
# --- 1. Fetch Google Calendar events for the day ---
- start_of_day = datetime.datetime.combine(date, datetime.time.min).isoformat() + "Z"
- end_of_day = datetime.datetime.combine(date, datetime.time.max).isoformat() + "Z"
+ start_of_day, end_of_day = local_day_bounds(date)
try:
gcal_events_result = (
@@ -127,29 +192,10 @@ def sync_events(date, local_events):
# --- 4. Sync from Google to Local (Add new events from Google) ---
for gcal_id, gcal_event in gcal_map.items():
if gcal_id not in local_map:
- # New event from Google, add it locally
- try:
- start = gcal_event["start"].get("dateTime", gcal_event["start"].get("date"))
- end = gcal_event["end"].get("dateTime", gcal_event["end"].get("date"))
-
- start_dt = datetime.datetime.fromisoformat(start.replace("Z", "+00:00"))
- end_dt = datetime.datetime.fromisoformat(end.replace("Z", "+00:00"))
-
- duration = int((end_dt - start_dt).total_seconds() / 60)
-
- new_local_event = {
- "title": gcal_event.get("summary", "No Title"),
- "hour": start_dt.hour,
- "minute": start_dt.minute,
- "duration": duration,
- "done": False,
- "color": [135, 206, 250], # Default color for synced events
- "icon": 0,
- "google_id": gcal_id,
- }
+ # New event from Google, add it locally (all-day events are skipped)
+ new_local_event = gcal_event_to_local(gcal_event)
+ if new_local_event is not None:
synced_events.append(new_local_event)
- except Exception as e:
- print(f"Error parsing Google event '{gcal_event.get('summary')}': {e}")
# --- 5. Handle Deletions ---
# If a local event with a google_id is no longer in gcal_map, it was deleted on Google.
diff --git a/main.py b/main.py
index 0321208..c28c503 100644
--- a/main.py
+++ b/main.py
@@ -6,13 +6,24 @@
import os
import random
import glob
-import json
import time
import multiprocessing
-from multiprocessing import Queue
from pygame import gfxdraw
import math
from utility import * # Import all helper functions
+import foci_store
+from foci_store import (
+ read_json_file,
+ roll_todo_tags,
+ safe_int,
+ sanitize_events_by_date,
+ sanitize_todos,
+ schedule_todo,
+ write_json_file,
+ has_completed_todos,
+ remove_completed_todos,
+ todo_tag_label,
+)
pygame.mixer.pre_init(44100, -16, 2, 2048) # Ensure high quality audio
pygame.init()
AUDIO_AVAILABLE = True
@@ -35,7 +46,9 @@
lofi_on = False
-ASSETS_DIR = resource_path("assets")
+ASSETS_DIR = resource_path("assets") # bundled, read-only resources
+# Writable user data. Must NOT be the PyInstaller temp dir, which is wiped on exit.
+DATA_DIR = foci_store.user_data_dir()
DEFAULT_FONT_PATH = os.path.join(ASSETS_DIR, "Domine.ttf")
try:
@@ -382,10 +395,10 @@ def set_theme(name):
set_theme(current_theme)
-SETTINGS_FILE = f"{ASSETS_DIR}/settings.json"
+SETTINGS_FILE = os.path.join(DATA_DIR, "settings.json")
# Default settings
-settings = {
+DEFAULT_SETTINGS = {
"theme": "Serene Morning",
"start_hour": 5,
"end_hour": 23,
@@ -394,23 +407,7 @@ def set_theme(name):
"confetti_on": True,
"font_path": DEFAULT_FONT_PATH,
}
-
-
-def write_json_file(path, data, *, indent=2, ensure_ascii=True):
- directory = os.path.dirname(path)
- if directory:
- os.makedirs(directory, exist_ok=True)
- temp_path = f"{path}.tmp"
- with open(temp_path, "w", encoding="utf-8") as f:
- json.dump(data, f, indent=indent, ensure_ascii=ensure_ascii)
- os.replace(temp_path, path)
-
-
-def safe_int(value, default):
- try:
- return int(value)
- except (TypeError, ValueError):
- return default
+settings = dict(DEFAULT_SETTINGS)
def normalize_font_path(font_path):
@@ -426,76 +423,13 @@ def normalize_font_path(font_path):
def sanitize_settings(loaded_settings):
- sanitized = settings.copy()
- if isinstance(loaded_settings, dict):
- sanitized.update(loaded_settings)
-
- theme = sanitized.get("theme")
- if theme not in THEMES:
- theme = settings["theme"]
-
- start_hour = clamp(safe_int(sanitized.get("start_hour"), settings["start_hour"]), 0, 12)
- end_hour = clamp(safe_int(sanitized.get("end_hour"), settings["end_hour"]), 13, 23)
- if end_hour <= start_hour:
- start_hour, end_hour = settings["start_hour"], settings["end_hour"]
-
- hour_height = clamp(safe_int(sanitized.get("hour_height"), settings["hour_height"]), 30, 80)
- font_path = normalize_font_path(sanitized.get("font_path"))
-
- return {
- "theme": theme,
- "start_hour": start_hour,
- "end_hour": end_hour,
- "sounds_on": bool(sanitized.get("sounds_on", settings["sounds_on"])),
- "hour_height": hour_height,
- "confetti_on": bool(sanitized.get("confetti_on", settings["confetti_on"])),
- "font_path": font_path,
- }
+ return foci_store.sanitize_settings(
+ loaded_settings, DEFAULT_SETTINGS, THEMES, resolve_font=normalize_font_path
+ )
def sanitize_event(raw_event):
- if not isinstance(raw_event, dict):
- return None
-
- event = dict(raw_event)
- event["title"] = str(event.get("title") or "Untitled")
-
- try:
- event["hour"] = clamp(int(event.get("hour", START_HOUR)), 0, 23)
- except (TypeError, ValueError):
- event["hour"] = START_HOUR
-
- try:
- event["minute"] = clamp(int(event.get("minute", 0)), 0, 59)
- except (TypeError, ValueError):
- event["minute"] = 0
-
- try:
- event["duration"] = clamp(int(event.get("duration", 60)), 15, 24 * 60)
- except (TypeError, ValueError):
- event["duration"] = 60
-
- event["done"] = bool(event.get("done", False))
-
- color = event.get("color")
- if not (
- isinstance(color, (list, tuple))
- and len(color) == 3
- and all(isinstance(c, int) and 0 <= c <= 255 for c in color)
- ):
- color = [181, 234, 215]
- event["color"] = list(color)
-
- try:
- event["icon"] = max(0, int(event.get("icon", 0)))
- except (TypeError, ValueError):
- event["icon"] = 0
-
- google_id = event.get("google_id")
- if google_id is not None and not isinstance(google_id, str):
- event.pop("google_id", None)
-
- return event
+ return foci_store.sanitize_event(raw_event, default_hour=START_HOUR)
def get_coin_frame_surface():
@@ -519,52 +453,16 @@ def get_coin_frame_surface():
return coin_sprite_sheet.subsurface(frame_rect)
-PLAYER_DATA_FILE = resource_path(os.path.join(ASSETS_DIR, "player_data.json"))
+PLAYER_DATA_FILE = os.path.join(DATA_DIR, "player_data.json")
def save_player_data():
write_json_file(PLAYER_DATA_FILE, {"coins": max(0, safe_int(user_coins, 0))})
-def sanitize_todos(items):
- if not isinstance(items, list):
- return []
-
- cleaned = []
- for item in items:
- if not isinstance(item, dict):
- continue
- item_type = item.get("type")
- if item_type == "folder":
- cleaned.append({
- "type": "folder",
- "name": str(item.get("name") or "Untitled Folder"),
- "is_open": bool(item.get("is_open", False)),
- "children": sanitize_todos(item.get("children", [])),
- })
- else:
- todo_item = {
- "type": "todo",
- "title": str(item.get("title") or "Untitled To-do"),
- "done": bool(item.get("done", False)),
- }
- if isinstance(item.get("tag"), str):
- todo_item["tag"] = item["tag"]
- if isinstance(item.get("date"), str):
- todo_item["date"] = item["date"]
- cleaned.append(todo_item)
- return cleaned
-
-
def load_settings():
global settings, START_HOUR, END_HOUR, current_theme, HOUR_HEIGHT
- settings = sanitize_settings({})
- if os.path.exists(SETTINGS_FILE):
- try:
- with open(SETTINGS_FILE, "r") as f:
- settings = sanitize_settings(json.load(f))
- except (json.JSONDecodeError, TypeError, ValueError):
- print("Warning: Could not read settings.json. Using defaults.")
+ settings = sanitize_settings(read_json_file(SETTINGS_FILE, {}))
set_theme(settings["theme"])
START_HOUR = settings["start_hour"]
@@ -576,8 +474,8 @@ def save_settings():
write_json_file(SETTINGS_FILE, settings)
-DATA_FILE = resource_path(os.path.join(ASSETS_DIR, "events.json"))
-TODO_FILE = resource_path(os.path.join(ASSETS_DIR, "todos.json"))
+DATA_FILE = os.path.join(DATA_DIR, "events.json")
+TODO_FILE = os.path.join(DATA_DIR, "todos.json")
all_events = {}
events = []
todos = []
@@ -603,35 +501,9 @@ def save_settings():
def load_todos():
global todos
- if os.path.exists(TODO_FILE):
- try:
- with open(TODO_FILE, "r", encoding="utf-8") as f:
- todos = sanitize_todos(json.load(f))
- except (json.JSONDecodeError, TypeError):
- todos = []
- else:
- todos = []
-
- # Update tags for items scheduled on previous days
- today = datetime.date.today()
- for todo in todos:
- if todo.get("tag") == "today" and "date" in todo:
- try:
- todo_date = datetime.datetime.strptime(todo["date"], "%Y-%m-%d").date()
- if todo_date < today:
- todo["tag"] = f"on {todo_date.strftime('%a')}"
- except (ValueError, TypeError):
- continue # Ignore if date is malformed
- elif todo.get("tag") == "tmr" and "date" in todo:
- try:
- todo_date = datetime.datetime.strptime(todo["date"], "%Y-%m-%d").date()
- if todo_date < today:
- todo["tag"] = f"on {todo_date.strftime('%a')}"
- except (ValueError, TypeError):
- continue # Ignore if date is malformed
-
- if todo_date == today:
- todo["tag"] = "today"
+ todos = sanitize_todos(read_json_file(TODO_FILE, []))
+ # Roll "today"/"tmr" tags forward (including to-dos nested in folders)
+ roll_todo_tags(todos)
def save_todos():
@@ -642,30 +514,10 @@ def save_todos():
def load_events():
global all_events, events, user_coins
- if os.path.exists(DATA_FILE):
- try:
- with open(DATA_FILE, "r", encoding="utf-8") as f:
- raw_events = json.load(f)
- if isinstance(raw_events, dict):
- all_events = {}
- for date_key, date_events in raw_events.items():
- if not isinstance(date_key, str):
- continue
- cleaned_events = []
- if isinstance(date_events, list):
- for raw_event in date_events:
- event = sanitize_event(raw_event)
- if event is not None:
- cleaned_events.append(event)
- all_events[date_key] = cleaned_events
- else:
- all_events = {}
- except (json.JSONDecodeError, TypeError):
- print("Warning: Could not read events.json. Starting with empty events.")
- all_events = {}
- else:
- all_events = {}
-
+ all_events = sanitize_events_by_date(
+ read_json_file(DATA_FILE, {}), default_hour=START_HOUR
+ )
+
date_str = selected_date.strftime("%Y-%m-%d")
events.clear()
@@ -673,12 +525,10 @@ def load_events():
events.extend(all_events[date_str])
# Load coins from a separate simple file
- try:
- with open(PLAYER_DATA_FILE, "r", encoding="utf-8") as f:
- player_data = json.load(f)
- user_coins = max(0, safe_int(player_data.get("coins", 0), 0))
- except (FileNotFoundError, json.JSONDecodeError, TypeError, ValueError):
- user_coins = 0
+ player_data = read_json_file(PLAYER_DATA_FILE, {})
+ if not isinstance(player_data, dict):
+ player_data = {}
+ user_coins = max(0, safe_int(player_data.get("coins", 0), 0))
def load_coin_animation():
@@ -1024,6 +874,24 @@ def draw_todo_items_recursive(items, y, level, mouse_pos, dragging_index_path, s
text_color = (150, 150, 150) if is_done else THEME["text"]
max_text_width = item_rect.width - (text_x - item_rect.x) - 35
+
+ # Date tag pill ("Today", "Tomorrow", "on Mon"), right-aligned;
+ # hidden while hovered so it doesn't sit under the delete button.
+ tag_info = todo_tag_label(item)
+ if tag_info and not is_hovered:
+ tag_label, is_overdue = tag_info
+ font11 = get_font_wrapper(11)
+ if is_overdue:
+ pill_bg, pill_fg = (255, 214, 214), (150, 40, 40)
+ else:
+ pill_bg, pill_fg = THEME["button_bg"], THEME["text"]
+ tag_surf = font11.render(tag_label, True, pill_fg)
+ pill = pygame.Rect(0, 0, tag_surf.get_width() + 12, tag_surf.get_height() + 4)
+ pill.midright = (item_rect.right - 8, item_rect.centery)
+ pygame.draw.rect(screen, pill_bg, pill, border_radius=pill.height // 2)
+ screen.blit(tag_surf, tag_surf.get_rect(center=pill.center))
+ max_text_width = max(20, pill.left - 6 - text_x)
+
display_title = truncate_text(item.get("title", "Untitled To-do"), font16, max_text_width)
if is_done:
@@ -1091,7 +959,7 @@ def draw_todo_list(
# --- Delete Completed Button ---
delete_completed_btn = pygame.Rect(add_btn.right + 10, add_btn.y, 40, 40)
- has_completed = any(t.get("done") for t in todos)
+ has_completed = has_completed_todos(todos)
if has_completed:
del_base_color = (255, 180, 180)
del_hover_color = (255, 200, 200)
@@ -3132,23 +3000,7 @@ def show_todo_context_menu(todo_index, pos, scroll_offset=0):
for i, rect in enumerate(option_rects):
if rect.collidepoint(mx, my):
todo = todos[todo_index]
- if i == 0: # Today
- # Add the "today" tag as requested
- todo["date"] = datetime.date.today().strftime("%Y-%m-%d")
- todo["tag"] = "today"
- elif i == 1: # Tomorrow
- todo["date"] = (
- datetime.date.today() + datetime.timedelta(days=1)
- ).strftime("%Y-%m-%d")
- todo["tag"] = "tmr"
- if "tag" in todo:
- del todo["tag"]
- elif i == 2: # Someday
- if "date" in todo:
- del todo["date"]
- if "tag" in todo:
- # Remove all tags as requested
- del todo["tag"]
+ schedule_todo(todo, ("today", "tomorrow", "someday")[i])
save_todos()
return
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
@@ -3229,11 +3081,6 @@ def edit_or_delete_event_at_pos(pos, current_scroll, queue):
return False
-def event_add_window(pos=None, edit_event=None):
- # --- Animation & Style Setup ---
- start_time = time.time() # noqa
-
-
def show_coin_counter_popup(event):
"""Displays a small 200x200 popup showing coins earned per minute."""
win_w, win_h = 200, 200
@@ -5129,9 +4976,9 @@ def main_loop():
save_todos()
continue
if todo_btns and todo_btns["delete_completed_btn"].collidepoint(pe.pos):
- if any(t.get("done") for t in todos):
+ if has_completed_todos(todos):
if show_confirmation_dialog("Delete all completed tasks?"):
- todos = [t for t in todos if not t.get("done")]
+ todos = remove_completed_todos(todos)
save_todos()
continue
@@ -5574,6 +5421,8 @@ def main_loop():
if __name__ == "__main__":
+ # Required for the lofi player subprocess in PyInstaller builds; no-op otherwise.
+ multiprocessing.freeze_support()
dragging_divider = False
# This is important for multiprocessing to work correctly on all platforms
main_loop()
\ No newline at end of file
diff --git a/main.spec b/main.spec
index d229f49..b15cfcb 100644
--- a/main.spec
+++ b/main.spec
@@ -22,7 +22,7 @@ exe = EXE(
a.binaries,
a.datas,
[],
- name='main',
+ name='Foci',
debug=False,
bootloader_ignore_signals=False,
strip=False,
diff --git a/progress.py b/progress.py
index 86636a7..ef36486 100644
--- a/progress.py
+++ b/progress.py
@@ -6,8 +6,6 @@
import sys
import math
import random
-from pygame import gfxdraw
-from datetime import timedelta
pygame.init()
@@ -184,8 +182,7 @@ def draw_center_glass(surface, radius):
def format_time(seconds):
- td = timedelta(seconds=int(max(0, seconds)))
- m, s = divmod(td.seconds, 60)
+ m, s = divmod(int(max(0, seconds)), 60)
return f"{m:02d}:{s:02d}"
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..945fef0
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,19 @@
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+
+[tool.ruff]
+line-length = 120
+target-version = "py310"
+
+[tool.ruff.lint]
+# Real-bug checks only: undefined names, syntax errors, unused imports, redefinitions.
+select = ["F", "E9"]
+ignore = [
+ "F403", # `from utility import *` in main.py
+ "F405",
+ "F841", # unused locals in the large GUI functions; tracked separately
+]
+
+[tool.ruff.lint.per-file-ignores]
+# ctypes.wintypes is imported inside a Windows-only try block
+"main.py" = ["F401"]
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..d708680
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,5 @@
+import os
+import sys
+
+# Make the project root importable when running `pytest` from anywhere.
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
diff --git a/tests/test_google_calendar.py b/tests/test_google_calendar.py
new file mode 100644
index 0000000..80399e6
--- /dev/null
+++ b/tests/test_google_calendar.py
@@ -0,0 +1,56 @@
+import datetime
+
+import google_calendar as gcal
+
+IST = datetime.timezone(datetime.timedelta(hours=5, minutes=30))
+PST = datetime.timezone(datetime.timedelta(hours=-8))
+
+
+def test_day_bounds_use_local_offset_not_utc():
+ start, end = gcal.local_day_bounds(datetime.date(2026, 3, 11), tz=IST)
+ assert start == "2026-03-11T00:00:00+05:30"
+ assert end == "2026-03-12T00:00:00+05:30"
+
+
+def test_event_time_is_converted_to_local_timezone():
+ ev = gcal.gcal_event_to_local(
+ {
+ "id": "abc",
+ "summary": "Standup",
+ "start": {"dateTime": "2026-03-11T17:00:00Z"},
+ "end": {"dateTime": "2026-03-11T17:45:00Z"},
+ },
+ tz=PST,
+ )
+ assert (ev["hour"], ev["minute"], ev["duration"]) == (9, 0, 45)
+ assert ev["google_id"] == "abc"
+ assert ev["title"] == "Standup"
+
+
+def test_offset_timestamps_are_handled():
+ ev = gcal.gcal_event_to_local(
+ {
+ "id": "x",
+ "start": {"dateTime": "2026-03-11T09:30:00+05:30"},
+ "end": {"dateTime": "2026-03-11T10:00:00+05:30"},
+ },
+ tz=IST,
+ )
+ assert (ev["hour"], ev["minute"], ev["duration"]) == (9, 30, 30)
+ assert ev["title"] == "No Title"
+
+
+def test_all_day_and_malformed_events_are_skipped():
+ all_day = {"id": "d", "start": {"date": "2026-03-11"}, "end": {"date": "2026-03-12"}}
+ assert gcal.gcal_event_to_local(all_day, tz=IST) is None
+ assert gcal.gcal_event_to_local({"id": "m"}, tz=IST) is None
+ bad = {"id": "b", "start": {"dateTime": "soon"}, "end": {"dateTime": "later"}}
+ assert gcal.gcal_event_to_local(bad, tz=IST) is None
+
+
+def test_short_events_get_minimum_duration():
+ ev = gcal.gcal_event_to_local(
+ {"id": "s", "start": {"dateTime": "2026-03-11T09:00:00Z"}, "end": {"dateTime": "2026-03-11T09:05:00Z"}},
+ tz=datetime.timezone.utc,
+ )
+ assert ev["duration"] == 15
diff --git a/tests/test_store.py b/tests/test_store.py
new file mode 100644
index 0000000..9788a19
--- /dev/null
+++ b/tests/test_store.py
@@ -0,0 +1,289 @@
+import datetime
+import json
+import os
+
+import pytest
+
+import foci_store as store
+
+TODAY = datetime.date(2026, 3, 11) # a Wednesday
+YESTERDAY = TODAY - datetime.timedelta(days=1)
+TOMORROW = TODAY + datetime.timedelta(days=1)
+
+
+def iso(d):
+ return d.strftime("%Y-%m-%d")
+
+
+# --- settings ---------------------------------------------------------------
+
+DEFAULTS = {
+ "theme": "Serene Morning",
+ "start_hour": 5,
+ "end_hour": 23,
+ "sounds_on": True,
+ "hour_height": 40,
+ "confetti_on": True,
+ "font_path": "assets/Domine.ttf",
+}
+THEMES = {"Serene Morning", "Midnight Deep"}
+
+
+def test_settings_defaults_when_file_missing_or_garbage():
+ assert store.sanitize_settings({}, DEFAULTS, THEMES) == DEFAULTS
+ assert store.sanitize_settings(["not", "a", "dict"], DEFAULTS, THEMES) == DEFAULTS
+ assert store.sanitize_settings(None, DEFAULTS, THEMES) == DEFAULTS
+
+
+def test_settings_unknown_theme_falls_back():
+ out = store.sanitize_settings({"theme": "Neon Vomit"}, DEFAULTS, THEMES)
+ assert out["theme"] == "Serene Morning"
+
+
+def test_settings_values_are_clamped_and_coerced():
+ out = store.sanitize_settings(
+ {"start_hour": "3", "end_hour": 99, "hour_height": 5, "sounds_on": 0},
+ DEFAULTS,
+ THEMES,
+ )
+ assert out["start_hour"] == 3
+ assert out["end_hour"] == 23
+ assert out["hour_height"] == 30
+ assert out["sounds_on"] is False
+
+
+def test_settings_font_resolver_is_applied():
+ out = store.sanitize_settings({"font_path": "x.ttf"}, DEFAULTS, THEMES, lambda p: f"/fonts/{p}")
+ assert out["font_path"] == "/fonts/x.ttf"
+
+
+def test_settings_drop_unknown_keys():
+ out = store.sanitize_settings({"evil": True}, DEFAULTS, THEMES)
+ assert "evil" not in out
+
+
+# --- events -----------------------------------------------------------------
+
+def test_event_non_dict_is_rejected():
+ assert store.sanitize_event("lunch") is None
+ assert store.sanitize_event(None) is None
+
+
+def test_event_fields_are_repaired():
+ ev = store.sanitize_event(
+ {"title": "", "hour": "25", "minute": -4, "duration": 2, "color": [1, 2], "icon": "x"}
+ )
+ assert ev["title"] == "Untitled"
+ assert ev["hour"] == 23
+ assert ev["minute"] == 0
+ assert ev["duration"] == store.MIN_EVENT_MINUTES
+ assert ev["color"] == store.DEFAULT_EVENT_COLOR
+ assert ev["icon"] == 0
+ assert ev["done"] is False
+
+
+def test_event_bad_hour_uses_default_hour():
+ assert store.sanitize_event({"hour": "noon"}, default_hour=8)["hour"] == 8
+
+
+def test_event_bool_is_not_a_color_channel():
+ ev = store.sanitize_event({"color": [True, 0, 0]})
+ assert ev["color"] == store.DEFAULT_EVENT_COLOR
+
+
+def test_event_keeps_extra_fields_and_valid_google_id():
+ ev = store.sanitize_event({"title": "Gym", "google_id": "abc", "todo_id": 7})
+ assert ev["google_id"] == "abc"
+ assert ev["todo_id"] == 7
+ assert "google_id" not in store.sanitize_event({"google_id": 123})
+
+
+def test_events_by_date_skips_junk():
+ raw = {"2026-01-01": [{"title": "a"}, "junk"], "2026-01-02": "nope"}
+ out = store.sanitize_events_by_date(raw)
+ assert [e["title"] for e in out["2026-01-01"]] == ["a"]
+ assert out["2026-01-02"] == []
+ assert store.sanitize_events_by_date([1, 2]) == {}
+
+
+# --- todos ------------------------------------------------------------------
+
+def test_todos_tree_is_cleaned_recursively():
+ raw = [
+ {"type": "folder", "name": "", "children": [{"title": "child", "tag": 5}, 3]},
+ "junk",
+ {"title": "top", "done": 1, "date": "2026-01-01"},
+ ]
+ out = store.sanitize_todos(raw)
+ assert out[0]["name"] == "Untitled Folder"
+ assert out[0]["children"] == [{"type": "todo", "title": "child", "done": False}]
+ assert out[1] == {"type": "todo", "title": "top", "done": True, "date": "2026-01-01"}
+
+
+@pytest.mark.parametrize(
+ "when, tag, date",
+ [("today", "today", TODAY), ("tomorrow", "tmr", TOMORROW)],
+)
+def test_schedule_todo_sets_tag_and_date(when, tag, date):
+ todo = {"type": "todo", "title": "x"}
+ store.schedule_todo(todo, when, today=TODAY)
+ assert todo["tag"] == tag
+ assert todo["date"] == iso(date)
+
+
+def test_schedule_tomorrow_keeps_its_tag():
+ # Regression: the context menu used to set tag="tmr" and then immediately delete it.
+ todo = store.schedule_todo({"title": "x"}, "tomorrow", today=TODAY)
+ assert "tag" in todo
+
+
+def test_schedule_someday_clears_tag_and_date():
+ todo = {"title": "x", "tag": "today", "date": iso(TODAY)}
+ store.schedule_todo(todo, "someday", today=TODAY)
+ assert "tag" not in todo and "date" not in todo
+
+
+def test_schedule_unknown_option_raises():
+ with pytest.raises(ValueError):
+ store.schedule_todo({}, "next week")
+
+
+def test_roll_tags_tomorrow_becomes_today():
+ todos = [{"title": "x", "tag": "tmr", "date": iso(TODAY)}]
+ store.roll_todo_tags(todos, today=TODAY)
+ assert todos[0]["tag"] == "today"
+
+
+def test_roll_tags_past_items_get_weekday():
+ todos = [
+ {"title": "a", "tag": "today", "date": iso(YESTERDAY)},
+ {"title": "b", "tag": "tmr", "date": iso(YESTERDAY)},
+ ]
+ store.roll_todo_tags(todos, today=TODAY)
+ assert [t["tag"] for t in todos] == ["on Tue", "on Tue"]
+
+
+def test_roll_tags_leaves_current_and_untagged_items():
+ todos = [
+ {"title": "a", "tag": "today", "date": iso(TODAY)},
+ {"title": "b", "tag": "tmr", "date": iso(TOMORROW)},
+ {"title": "c"},
+ {"title": "d", "tag": "today", "date": "not-a-date"},
+ ]
+ before = json.loads(json.dumps(todos))
+ store.roll_todo_tags(todos, today=TODAY)
+ assert todos == before
+
+
+def test_roll_tags_reaches_into_folders():
+ # Regression: only top-level to-dos used to roll over.
+ todos = [
+ {
+ "type": "folder",
+ "name": "Physics",
+ "children": [
+ {"type": "folder", "name": "Kinematics", "children": [
+ {"title": "deep", "tag": "tmr", "date": iso(TODAY)},
+ ]},
+ {"title": "shallow", "tag": "today", "date": iso(YESTERDAY)},
+ ],
+ }
+ ]
+ store.roll_todo_tags(todos, today=TODAY)
+ physics = todos[0]["children"]
+ assert physics[0]["children"][0]["tag"] == "today"
+ assert physics[1]["tag"] == "on Tue"
+
+
+def test_completed_todos_in_folders_are_found_and_removed():
+ # Regression: "Delete completed" only looked at top-level items.
+ todos = [
+ {"type": "folder", "name": "F", "children": [
+ {"title": "done", "done": True},
+ {"title": "open", "done": False},
+ ]},
+ {"title": "top open", "done": False},
+ ]
+ assert store.has_completed_todos(todos)
+ cleaned = store.remove_completed_todos(todos)
+ assert [c["title"] for c in cleaned[0]["children"]] == ["open"]
+ assert not store.has_completed_todos(cleaned)
+ # the input is not mutated
+ assert len(todos[0]["children"]) == 2
+
+
+def test_tag_label():
+ assert store.todo_tag_label({"title": "x"}) is None
+ assert store.todo_tag_label({"tag": "today", "date": iso(TODAY)}, TODAY) == ("Today", False)
+ assert store.todo_tag_label({"tag": "tmr", "date": iso(TOMORROW)}, TODAY) == ("Tomorrow", False)
+ assert store.todo_tag_label({"tag": "on Tue", "date": iso(YESTERDAY)}, TODAY) == ("on Tue", True)
+ assert store.todo_tag_label(
+ {"tag": "on Tue", "date": iso(YESTERDAY), "done": True}, TODAY
+ ) == ("on Tue", False)
+
+
+# --- JSON I/O ---------------------------------------------------------------
+
+def test_write_then_read_roundtrip(tmp_path):
+ path = tmp_path / "nested" / "events.json"
+ store.write_json_file(str(path), {"2026-01-01": [{"title": "café"}]}, ensure_ascii=False)
+ assert store.read_json_file(str(path)) == {"2026-01-01": [{"title": "café"}]}
+ assert not (tmp_path / "nested" / "events.json.tmp").exists()
+
+
+def test_read_missing_or_corrupt_returns_default(tmp_path):
+ assert store.read_json_file(str(tmp_path / "nope.json"), {"d": 1}) == {"d": 1}
+ bad = tmp_path / "bad.json"
+ bad.write_text("{ not json", encoding="utf-8")
+ assert store.read_json_file(str(bad), []) == []
+ binary = tmp_path / "bin.json"
+ binary.write_bytes(b"\xff\xfe\x00garbage")
+ assert store.read_json_file(str(binary), []) == []
+
+
+def test_safe_int():
+ assert store.safe_int("7", 0) == 7
+ assert store.safe_int(None, 3) == 3
+ assert store.safe_int("x", 3) == 3
+
+
+# --- paths ------------------------------------------------------------------
+
+def test_data_dir_env_override(tmp_path):
+ assert store.user_data_dir({"FOCI_DATA_DIR": str(tmp_path)}) == str(tmp_path)
+
+
+def test_data_dir_from_source_is_assets(monkeypatch):
+ monkeypatch.delattr("sys._MEIPASS", raising=False)
+ monkeypatch.setattr("sys.frozen", False, raising=False)
+ assert store.user_data_dir({}) == os.path.join(store.app_root(), "assets")
+
+
+def test_frozen_build_never_writes_into_bundle(monkeypatch, tmp_path):
+ # Regression: the one-file .exe saved user data inside its temp extraction
+ # folder (sys._MEIPASS), which PyInstaller deletes when the app exits.
+ bundle = tmp_path / "_MEI12345"
+ monkeypatch.setattr("sys._MEIPASS", str(bundle), raising=False)
+ monkeypatch.setattr("sys.frozen", True, raising=False)
+ data_dir = store.user_data_dir({"APPDATA": str(tmp_path / "Roaming")})
+ assert store.app_root() == str(bundle)
+ assert not data_dir.startswith(str(bundle))
+
+
+@pytest.mark.parametrize(
+ "platform, environ, expected_tail",
+ [
+ ("win32", {"APPDATA": "/r"}, os.path.join("/r", "Foci")),
+ ("darwin", {}, os.path.join("Library", "Application Support", "Foci")),
+ ("linux", {"XDG_DATA_HOME": "/x"}, os.path.join("/x", "Foci")),
+ ("linux", {}, os.path.join(".local", "share", "Foci")),
+ ],
+)
+def test_platform_data_dir(platform, environ, expected_tail):
+ assert store.platform_data_dir(platform=platform, environ=environ).endswith(expected_tail)
+
+
+def test_app_root_does_not_depend_on_cwd(monkeypatch, tmp_path):
+ monkeypatch.delattr("sys._MEIPASS", raising=False)
+ monkeypatch.chdir(tmp_path)
+ assert os.path.isfile(os.path.join(store.app_root(), "main.py"))
diff --git a/tests/test_utility.py b/tests/test_utility.py
new file mode 100644
index 0000000..3dfb0ec
--- /dev/null
+++ b/tests/test_utility.py
@@ -0,0 +1,23 @@
+import utility
+
+
+def test_format_time_basic():
+ assert utility.format_time(0) == "00:00"
+ assert utility.format_time(65) == "01:05"
+ assert utility.format_time(-5) == "00:00"
+
+
+def test_format_time_does_not_wrap_after_a_day():
+ # timedelta.seconds drops whole days, so 25h used to render as "60:00"
+ assert utility.format_time(25 * 3600) == "1500:00"
+
+
+def test_clamp_and_lerp():
+ assert utility.clamp(5, 0, 3) == 3
+ assert utility.lerp_color((0, 0, 0), (100, 200, 50), 0.5) == (50, 100, 25)
+
+
+def test_get_event_id_is_stable():
+ ev = {"hour": 9, "minute": 30, "title": "Deep work"}
+ assert utility.get_event_id(ev) == "9-30-Deep work"
+ assert utility.get_event_id({"hour": 9, "title": "x"}) == "9-0-x"
diff --git a/utility.py b/utility.py
index 772ce82..4569073 100644
--- a/utility.py
+++ b/utility.py
@@ -1,19 +1,17 @@
import pygame
import sys
import os
-import datetime
import math
import time
import random
+
+from foci_store import app_root
+
# --- Path & Resource Helpers ---
def resource_path(relative_path):
- """Get absolute path to resource (works for dev and .exe)"""
- try:
- base_path = sys._MEIPASS
- except Exception:
- base_path = os.path.abspath(".")
- return os.path.join(base_path, relative_path)
+ """Absolute path to a bundled resource (works from source and from the .exe)."""
+ return os.path.join(app_root(), relative_path)
def load_icon_safe(name, size=(28, 28)):
"""Loads an image with a fallback to a blank surface."""
@@ -51,8 +49,7 @@ def get_event_id(ev):
def format_time(seconds):
"""Formats seconds into a MM:SS string."""
- td = datetime.timedelta(seconds=int(max(0, seconds)))
- m, s = divmod(td.seconds, 60)
+ m, s = divmod(int(max(0, seconds)), 60)
return f"{m:02d}:{s:02d}"
def eased_progress(t):