v0.23.0: Routine, first public version

This commit is contained in:
2026-11-15 02:22:09 -08:00
commit 5ea848bddc
285 changed files with 23886 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
node_modules/
__pycache__/
*.pyc
/android/build/
/test-data/
/build/
/dist/
/android/apk/
/android/routine.keystore
CLAUDE.md
+131
View File
@@ -0,0 +1,131 @@
# PolyForm Noncommercial License 1.0.0
<https://polyformproject.org/licenses/noncommercial/1.0.0>
## Acceptance
In order to get any license under these terms, you must agree
to them as both strict obligations and conditions to all
your licenses.
## Copyright License
The licensor grants you a copyright license for the
software to do everything you might do with the software
that would otherwise infringe the licensor's copyright
in it for any permitted purpose. However, you may
only distribute the software according to [Distribution
License](#distribution-license) and make changes or new works
based on the software according to [Changes and New Works
License](#changes-and-new-works-license).
## Distribution License
The licensor grants you an additional copyright license
to distribute copies of the software. Your license
to distribute covers distributing the software with
changes and new works permitted by [Changes and New Works
License](#changes-and-new-works-license).
## Notices
You must ensure that anyone who gets a copy of any part of
the software from you also gets a copy of these terms or the
URL for them above, as well as copies of any plain-text lines
beginning with `Required Notice:` that the licensor provided
with the software. For example:
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
## Changes and New Works License
The licensor grants you an additional copyright license to
make changes and new works based on the software for any
permitted purpose.
## Patent License
The licensor grants you a patent license for the software that
covers patent claims the licensor can license, or becomes able
to license, that you would infringe by using the software.
## Noncommercial Purposes
Any noncommercial purpose is a permitted purpose.
## Personal Uses
Personal use for research, experiment, and testing for
the benefit of public knowledge, personal study, private
entertainment, hobby projects, amateur pursuits, or religious
observance, without any anticipated commercial application,
is use for a permitted purpose.
## Noncommercial Organizations
Use by any charitable organization, educational institution,
public research organization, public safety or health
organization, environmental protection organization,
or government institution is use for a permitted purpose
regardless of the source of funding or obligations resulting
from the funding.
## Fair Use
You may have "fair use" rights for the software under the
law. These terms do not limit them.
## No Other Rights
These terms do not allow you to sublicense or transfer any of
your licenses to anyone else, or prevent the licensor from
granting licenses to anyone else. These terms do not imply
any other licenses.
## Patent Defense
If you make any written claim that the software infringes or
contributes to infringement of any patent, your patent license
for the software granted under these terms ends immediately. If
your company makes such a claim, your patent license ends
immediately for work on behalf of your company.
## Violations
The first time you are notified in writing that you have
violated any of these terms, or done anything with the software
not covered by your licenses, your licenses can nonetheless
continue if you come into full compliance with these terms,
and take practical steps to correct past violations, within
32 days of receiving notice. Otherwise, all your licenses
end immediately.
## No Liability
***As far as the law allows, the software comes as is, without
any warranty or condition, and the licensor will not be liable
to you for any damages arising out of these terms or the use
or nature of the software, under any kind of legal claim.***
## Definitions
The **licensor** is the individual or entity offering these
terms, and the **software** is the software the licensor makes
available under these terms.
**You** refers to the individual or entity agreeing to these
terms.
**Your company** is any legal entity, sole proprietorship,
or other kind of organization that you work for, plus all
organizations that have control over, are under the control of,
or are under common control with that organization. **Control**
means ownership of substantially all the assets of an entity,
or the power to direct its management and policies by vote,
contract, or otherwise. Control can be direct or indirect.
**Your licenses** are all the licenses granted to you for the
software under these terms.
**Use** means anything you do with the software requiring one
of your licenses.
+326
View File
@@ -0,0 +1,326 @@
# Routine
![Routine with the template routine it starts with](docs/screenshot.png)
The day's routine as one long list you tick off as you go. Blocks (Morning, Work, Evening, …) hold
your tasks and their sub-tasks; tick them as you do them, skip what isn't happening today, and
write a line about the day at the bottom. Every tick plays a little stop-motion animation, with
its own sound, out of the box you ticked. Streaks count the days in a row a task got done, and
three windows look back: **History** (every task, every day, as a grid), **Statistics** and the
**Journal** (your notes).
For Linux and macOS. There is also an app for the Rabbit R1, kept in step with the desktop through
a small sync server of your own (Linux only for now).
## Install
**macOS** (13 Ventura or newer, Apple silicon or Intel). Open Terminal (⌘ Space, type Terminal),
paste this line and press Return:
```
curl -fsSL https://git.autonomic.zone/trav/routine/raw/branch/main/install-mac.sh | bash
```
No password, Xcode or Homebrew needed: it downloads Routine, its own Python and Qt (about 400 MB,
all kept in `~/Library/Application Support/Routine-app`) and puts **Routine** in your Applications
folder, so it's in Launchpad and Spotlight. To keep it in the Dock: open it, right-click its Dock
icon → Options → Keep in Dock. *The Mac version is new and hasn't been tried on a real Mac yet: if
something's off, see [If something goes wrong](#if-something-goes-wrong).*
**Linux** (Fedora, Ubuntu / Debian, Arch, and most others). In a terminal:
```
curl -fsSL https://git.autonomic.zone/trav/routine/raw/branch/main/install-linux.sh | bash
```
It needs Python 3.10 or newer (every current distribution has it) and PySide6 (Qt for Python). If
your system has PySide6 already, that's used; if not, it offers your distribution's package (it
shows the `sudo` command and asks first) or a private copy just for Routine (about 250 MB, no
password). The app goes to `~/.local/share/routine-app`, and Routine appears among your apps.
**Update**: run the same line again. **Uninstall**: the same line with `-s -- --uninstall` on the end
(`… | bash -s -- --uninstall`). Neither ever touches your routine or your history.
## First steps
1. **Open Routine.** The first time, it starts from a template routine: a few blocks with tasks
that show what a routine can hold (sub-tasks, a weekend-only block, a weekday-only task, a
suggestion, a calm task). Have a look, tick something.
2. **Make it yours**: Settings (Ctrl+, on Linux, ⌘, on a Mac) → **Routine**. Delete the template's
tasks, add your own blocks and tasks, give them hours, colours and days, then **Save routine**.
See [Changing the routine](#changing-the-routine).
3. **Tick as you go.** The window opens on the block you're in now (») and the day rolls over at 4 am,
so late-night tasks count for the evening before. Scroll sideways (or ‹ ›) for earlier days.
4. **Streaks** build by themselves; **View → History / Statistics / Journal** look back over them
([Streaks](#streaks)).
5. **Back it up**: your whole routine and history are two files; see [Your data](#your-data).
## On a Mac
Everything on the desktop works the same, with a Mac's habits: the menu bar is at the top of the
screen, ⌘ stands in for Ctrl in every shortcut (History is ⌘Y, since ⌘H hides an app), Settings
is in the Routine menu, and windows have the usual title bar. **Coming soon on macOS**: the sync
server and the Rabbit R1 (their Settings pages are there, greyed out). Your data is kept in
`~/Library/Application Support/Routine`, the error log in `~/Library/Logs/Routine`.
## If something goes wrong
Routine keeps running after most errors: it writes what went wrong to a log and says so once.
**Help → Open log folder** shows the log (`errors.log`; `launch.log` has the messages from the last
start). The log holds only where in the program things went wrong, never your routine or notes.
Please send it along with what you were doing. **Help → About Routine** shows the version and where
everything is kept.
- Linux: `~/.local/state/routine/`
- macOS: `~/Library/Logs/Routine/`
## The animations
Every tick plays a little stop-motion animation, with its own sound,
out of the box you ticked. The more you tick in a day, the more of them you get to see: the
first 5 ticks draw from set 0 (the biggest, 40 animations, since those ticks happen every day),
the next 5 from set 1, and so on, purely at random within the set: repeats can happen, and
nothing remembers what has played (`shared/ANIMATIONS.md` lists them all). A task marked
**calm animation** in the editor plays one of 40 calm ones instead: slower, two seconds, with
quiet sounds, for early mornings and late nights. Each one starts at the box you ticked but is moved,
as little as it takes, to stay entirely on screen (and drawn smaller only if it couldn't fit at all). It still counts toward the next set. Once you're past the last set, a special two-second star plays too: time to ask for
more animations.
## Using it
- **One day, top to bottom**: blocks (Morning, Work, Lunch, …) with every task and sub-task as a
checkbox. Ticking or skipping a task does the same to its sub-tasks that are still open.
- **skip** hides a task without ticking it off (recorded as skipped, no animation).
- **Click (tap on the R1) a block's heading** to hide its tasks, again to show them; remembered
per device. Until you've done it once, each heading says "click/tap to hide" or "to show".
- **All / Incomplete / Completed** at the bottom (All / To do / Done on the R1, to fit):
everything, only what's still to do, or only what got ticked (with the tasks it sits under).
In All you can untick a done task or unskip a skipped one. Today remembers the last pick; an
earlier day always opens on Completed.
- **Ticking a task on an earlier day** asks first ("this is for a day in the past, …"): yes / oops.
- **»** (Now) jumps to today at the current time (the latest block that has started: after the
last block, until the day rolls over, that last one); the app opens there. The date at the top
and the note at the bottom stay put while the tasks scroll between them.
- **Earlier days are to the left**: scroll sideways (touchpad), Alt+Left / Alt+Right, or ‹ ›.
- **The note** at the bottom of each day, past days included.
- **Settings → Appearance → Look**: the date (always "Sunday, November 8th"; **Show the year** adds ", 2026",
and the R1 follows at install), the header font (the date; default Edition), the note title's
font (default Caveat, a handwritten script bundled in `shared/fonts`, SIL Open Font License), and
block colours: a swatch by each block's name, the heading row in its colour, or the whole block.
**Emboss the block colours** draws whichever of those as a button (hover and press darken it,
as on any button), with no dark edge unless **Colours → Block edge** gives it one (0 % none,
35 % a button's); the R1 stays flat.
**Say "now" on the current block** (on by default) shows or hides that word; the R1 never says it.
- **Settings → Appearance → Colours**: every gray (header, background, tasks area, buttons, the note,
lists) and a tint, with Light and Dark tabs for each mode's own set (shared-resources design.html#colors).
- The day rolls over at 4 am (`dayStartsAt`), so night tasks after midnight count for the night before.
- **Ctrl+,** (or Edit → Settings in the menu bar: tap **Alt** to show it) opens Settings: the
routine editor, look, sounds, tooltips, streaks (streak animations, cheat days, embossed history
dots), where the data is kept, the sync server, the R1. On a Mac: **⌘,** or Routine → Settings
in the menu bar at the top of the screen.
- **Help → Open log folder** and **Help → About Routine** (the version, and where everything is kept).
- On the R1 the wheel stays volume (wheel down + side button = screenshot); scroll by touch.
The moon / sun in its bottom bar switches between the dark look (white on black, best in
bright sunlight) and the light one (the desktop's: embossed boxes, the Edition date, the
desktop's block colouring, sent along at install). The date scrolls away with the tasks there.
## Changing the routine
Settings → Routine: a tree of blocks and the tasks nested under them, with a form for the
selected one (name, hours, colour and days of the week for a block; name and days for a task,
and whether it's **just a suggestion**: quiet text with no checkbox, like an idea for how to do
the task above it, never ticked or skipped) or has a **calm animation** (see below). A block or
task left off a day takes everything under it along. ↑ at the top of a block moves a task into
the end of the block above; ↓ at the bottom moves it into the start of the block below. Add block / task /
sub-task, delete, move with ↑ ↓, and indent/outdent with → ←. **Save routine** bumps its `rev`,
gives today's list the new routine, and sends it through the sync server to the R1 at its next sync. Past
days keep the routine they had; renaming a task keeps its history (moving it under a different
parent starts a new one).
**The first run** starts from a template (`shared/schedule.json`): a few blocks whose tasks show
what a routine can hold (sub-tasks two deep, a weekend-only block, a weekday-only task, a
suggestion, a calm task). It's copied into your data folder as `schedule.json`, and from then on
that copy is your routine: it always wins over the template, whatever their `rev`s. Delete the
template's tasks in Settings → Routine and add your own. A fresh R1 install also begins with the
template (its `rev` is 0, so the first sync replaces it with the desktop's routine as soon as
that has been saved once).
An install from before the template (a history already there, but no `schedule.json` of its
own) is never switched to the template: it takes a `schedule.from-repo*.json` from the data
folder if there is one (a saved copy of the routine the repo used to ship), else it rebuilds the
routine from the most recent day in the history (that day's blocks and tasks, ids kept; weekday
limits can't be told from one day, so check them in the editor).
## Streaks
Every task keeps a streak: the days in a row it got ticked. Days a task isn't on (a weekday-only
task at the weekend) don't count either way, and today doesn't count against it until it's over.
When a tick by hand brings a streak to **7, 21, 42, 66, 100, 150, 254 or 365** days (and every 100
more after that), a special two-second streak animation plays instead, showing the number (a calm
task gets a calm one). **Cheat days**: after 7 days in a row (Settings → Streaks sets how many, or
turns it off) one missed day is forgiven and the streak carries on; two misses running end it.
**On the R1** the same ticks play the same streak animations, with the same number: the R1 only
holds the last couple of months, so the desktop sends each streak as it stood 30 days ago through
the sync server (with the streak settings), and the R1 counts on from there. Until it has that (a
server that hasn't been updated yet), the R1 counts from its own days and only plays a streak animation when it
can see where the streak began; the settings then come along at install.
**View → History** (Ctrl+H; ⌘Y on a Mac), **Statistics** (Ctrl+T) and **Journal** (Ctrl+J) open windows of their own
beside the main one, each showing a range of days picked at its top (last 30 / 90 days, this
year, all time, or from – to).
**History** is the range as a grid: blocks and their tasks across the top, days down the left
(months marked by a line), opening on today at the bottom. Two buttons beside the range tiles
change that, both remembered: the arrow flips the day order (newest at the bottom or at the top;
with the axes swapped, on the right or on the left), and the axes button (lit while on) swaps the
axes: days across, tasks down the side, so long streaks run sideways on a wide screen. A day a
task got done is a dot in its block's colour; a streak joins its dots into one pill, which narrows
to a thin stem over days the task wasn't on, so a weekday-only streak reads as one. A cheat day is
a hole in the pill; a missed day a faint speck; today, still to do, a faint ring. Click a block's
heading to fold it into one column (or row): full colour where every task was done, pale where
some were, empty where none were (click again to open it; remembered). Hover a dot for the task,
the day and its streak; hover a heading for the task's full name. Pinch, Ctrl+wheel or Ctrl + / −
zoom around the pointer (Ctrl+0 back to 100 %, remembered); zoomed far out it turns into bars with
week or month labels, so years fit. Home / End jump to the start / end of the days (top or left /
bottom or right). Settings → Streaks embosses the dots or draws them flat.
**Statistics** lays the routine out as the main window does (the same blocks, colours and indents,
every task with a record in the range, in today's order; a task since removed in quiet italics),
read-only, with a figure where the checkbox would be. The tiles at the bottom pick it: **% of days**
(of the days it was on), **Longest streak** (in the range, with the cheat days that streak used and
the streak going now beside it) or **Days done**; each heading shows its tasks' % together.
Click a task for its details in the panel at the bottom (longest streak with its dates and cheat
days, the streak now, % and days done, the next reward and how far off it is); click it again and
the panel sums up the range (the routine's %, the best streaks, perfect days, cheat days used).
Headings hide their tasks on a click here too, remembered apart from the main window's.
**Journal** is the notes, newest first, each under its date with the % of that day's tasks done;
click the % for what got done that day, by block, and below a line what didn't. **With a note**
(the default) leaves out the days without one; **Every day** shows them too. Double-click an entry
to open that day in the main window; right-click to copy its note.
## Your data
Two files are everything: **`schedule.json`**, your routine, and **`routine.db`**, the history:
every day from the first run on has a record, ticked or not (SQLite, one JSON document per day:
see `routine/model.py`), with your notes and a log of every animation that played, when, and for
which task. The sync server only relays the last 60 days between the desktop and the R1.
They start out in
- Linux: `~/.local/share/routine/` (settings in `~/.config/routine/config.json`)
- macOS: `~/Library/Application Support/Routine/` (settings in `config.json` there too)
To **back them up**, copy those two files (with Routine closed, to be safe), or keep them in a
folder that's backed up or synced already: **Settings → Data** keeps either one in a folder of
your choosing. Pick it and the file is moved there (copied, checked, then the original removed).
If that folder already has one, it asks: **use that one** (yours stays where it was), **replace
it with mine** (that one is kept beside it as `<name>.replaced-<time>`), or cancel. **Default**
moves it back. All of it happens with the app running: the open windows and the sync carry on.
The folders are `schedule_dir` and `db_dir` in `config.json` (empty = the default).
`ROUTINE_HOME=DIR` puts the data, the config file and the logs in DIR instead, for testing.
Uninstalling or updating Routine never touches these files.
## Licence
Routine is under the [PolyForm Noncommercial License 1.0.0](LICENSE): you're free to use it, change
it and share it for any noncommercial purpose; commercial rights are reserved by the author.
Required Notice: Copyright trav (https://git.autonomic.zone/trav/routine)
The bundled Caveat font (`shared/fonts`) is under the SIL Open Font License (`shared/fonts/Caveat-OFL.txt`).
Qt for Python (PySide6) is under the LGPL.
---
# For developers
```
python3 -m routine # run it from a checkout (needs PySide6, or PyQt6)
scripts/install-desktop.sh # put this checkout in the app grid (Linux); then right-click → Pin to Dash
./install-linux.sh # or: a copy of its own in ~/.local/share/routine-app (re-run to update)
```
**Qt**: everything imports Qt through `routine/qt/` (`from routine.qt.QtCore import Qt, Signal`),
which picks PySide6 when it's there and falls back to PyQt6; `ROUTINE_QT=pyside6|pyqt6` forces
one. The installers use PySide6 (LGPL), pinned in `install-*.sh` and `scripts/build-mac-app.sh`.
One PySide6 pitfall: an attribute named like a Qt virtual method (`self.metric = …` on a QWidget)
shadows it and crashes PySide6 when Qt calls it.
**Linux and macOS**: what differs lives in `routine/system.py` (data / config / log folders, the
system or the app's own window frame, the global menu bar, sync and the R1 off on a Mac, sound
players, gsettings, shortcuts), each function testable for either platform from either
(`tests/test_system.py`). On a Mac the windows keep the system's frame (Qt can't resize a frameless
window there), the menu bar is the Mac's, and sync / the R1 are "coming soon".
**The Mac app**: `install-mac.sh` makes a small Routine.app that starts the app from
`~/Library/Application Support/Routine-app` (uv, a standalone Python and PySide6, all inside that
folder). `scripts/build-mac-app.sh`, run on a Mac, makes a self-contained, ad-hoc signed
Routine.app and a drag-to-install `.dmg` with PyInstaller: see `docs/building-the-mac-app.md`.
`shared/icon.icns` is made from `shared/icon.svg` by `tools/make_icns.py` (no Mac needed).
`docs/mac-testing.md` is the checklist for trying it on a Mac.
## Pieces
```
shared/schedule.json the template routine (a first run starts from it; both apps)
shared/animations.json the animations + the star, frame by frame ← tools/gen_animations.py
shared/ANIMATIONS.md the catalogue: every one, its set, colour and sound (generated)
shared/sounds/*.wav one sound each ← tools/gen_sounds.py
shared/fonts/ Caveat (the note title's default font) + its licence
shared/icon.svg, icon.icns the app icon (the .icns ← tools/make_icns.py)
routine/ desktop app (PySide6); model.py is shared with the server (and has the streaks)
routine/qt/ the Qt binding: PySide6, else PyQt6
routine/system.py what differs on Linux and macOS (no Qt, tested)
routine/crash.py unhandled errors: logged (tracebacks only), a notice once, the app keeps going
routine/gui/frame.py the window chrome every window shares; SideWindow, the side windows' base
routine/gui/daterange.py the date range at the top of the side windows
routine/gui/history.py, stats.py, journal.py View → History / Statistics / Journal
routine/gui/history_cols.py the History grid's columns and marks (no Qt, tested)
routine/tally.py the Statistics and Journal figures (pure, tested)
routine/storage.py first run (the template), existing users, moving the data (no Qt, tested)
tools/anim_kit.py, sound_kit.py the drawing and synth helpers every animation / sound uses
tools/streak_anims/ the streak animations: levelK.py + levelK_sounds.py per level, calm.py
tools/fake_history.py a fake history in a scratch folder, to test with (never real data)
tests/ QT_QPA_PLATFORM=offscreen python3 -m unittest discover tests
(test_r1.py runs the R1's streak code on the JDK: android/src/test)
install-linux.sh, install-mac.sh the one-line installers (install, update, --uninstall)
scripts/build-mac-app.sh Routine.app + .dmg with PyInstaller, on a Mac
server/ routine-server, the sync relay → scripts/deploy-server.sh
android/ the R1 app (plain Java, no Gradle) → android/build.py
docs/ the screenshot, the Mac build and testing notes
```
`tools/preview_animations.py OUTDIR` draws every frame of every animation on contact sheets.
One streak level on its own, into a scratch folder (shared/ untouched):
```
python3 tools/gen_animations.py --level 0 --out DIR # DIR/animations.json + ANIMATIONS.md
python3 tools/gen_sounds.py --level 0 --out DIR # DIR/sounds/
python3 tools/preview_animations.py DIR/sheets --json DIR/animations.json --streak 0 [--number 465] [--every]
```
To try the app on fake data: `python3 tools/fake_history.py DIR`, then `ROUTINE_HOME=DIR python3 -m routine`
(it prints which tasks are one tick short of a streak level today). The installers can be tried
the same way, without touching your own install: `ROUTINE_SOURCE=. HOME=/tmp/x ./install-linux.sh`
(and `ROUTINE_INSTALL_TEST=1` lets `install-mac.sh` run on Linux).
## The sync server
Optional: without it the desktop app works on its own. With it, the desktop and the R1 keep each
other's ticks, notes and the routine. `server/routine_server.py` is standard-library Python (plus
`routine/model.py`), plain HTTP with a bearer token, so run it on a machine of yours that both
devices reach privately (a home server on a VPN such as WireGuard or Tailscale), not on the open
internet.
```
ROUTINE_SERVER_HOST=10.0.0.5 scripts/deploy-server.sh me@myserver # copy it there, (re)start it in screen
scripts/deploy-server.sh me@myserver --token # the token for Settings → Sync
scripts/deploy-server.sh me@myserver --stop
```
`DEPLOY_DIR` (default `routine-server` in the remote home) and `ROUTINE_SERVER_PORT` (default 8070)
change where and on what port; the address and port are kept in `DEPLOY_DIR/app/server.env`, so
a boot script on the server only has to run `DEPLOY_DIR/app/run.sh`. Then in the desktop app,
Settings → Sync: the address (`http://10.0.0.5:8070`) and the token; **Install / update on the R1**
hands both to the R1.
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Build the R1 app without Gradle (shared-resources rabbit.html#toolchain).
aapt2 compile/link -> javac --release 11 -> d8 -> zipalign -> apksigner, then copy the APK
to android/apk/routine.apk with its version in apk/routine-apk.json (the desktop installs it).
python3 android/build.py the real app -> android/apk/routine.apk (committed)
python3 android/build.py --dev me.teafry.routine.dev, "Routine dev", own storage -> build/routine-dev.apk
"""
import datetime as dt
import glob
import json
import os
import shutil
import subprocess
import sys
import zipfile
VERSION_NAME = "0.17.0"
PKG = "me.teafry.routine"
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)
SDK = os.environ.get("ANDROID_HOME", os.path.expanduser("~/Android/Sdk"))
JAVA = os.environ.get("JAVA_HOME", "/usr/lib/jvm/java-21-openjdk")
BT = os.path.join(SDK, "build-tools", "34.0.0")
JAR = os.path.join(SDK, "platforms", "android-33", "android.jar")
B = os.path.join(HERE, "build")
KEYSTORE = os.path.join(HERE, "routine.keystore")
KS_PASS = "routine-r1" # a sideloaded app: nothing for the key to protect (rabbit.html)
def run(*cmd):
env = dict(os.environ, JAVA_HOME=JAVA, PATH=os.path.join(JAVA, "bin") + os.pathsep + os.environ["PATH"])
r = subprocess.run(cmd, env=env, capture_output=True, text=True)
if r.returncode:
sys.exit("FAILED: %s\n%s%s" % (" ".join(cmd), r.stdout, r.stderr))
return r.stdout
def main():
dev = "--dev" in sys.argv
pkg, label = (PKG + ".dev", "Routine dev") if dev else (PKG, "Routine")
shutil.rmtree(B, ignore_errors=True)
for d in ("assets/sounds", "gen", "classes", "dex"):
os.makedirs(os.path.join(B, d))
for f in ("schedule.json", "animations.json"):
shutil.copy(os.path.join(REPO, "shared", f), os.path.join(B, "assets", f))
for f in glob.glob(os.path.join(REPO, "shared", "sounds", "*.wav")):
shutil.copy(f, os.path.join(B, "assets", "sounds"))
os.makedirs(os.path.join(B, "assets", "fonts"))
for f in glob.glob(os.path.join(REPO, "shared", "fonts", "*.ttf")): # Caveat: the note's title
shutil.copy(f, os.path.join(B, "assets", "fonts"))
edition = os.path.expanduser("~/.local/share/fonts/edition_.ttf") # the light look's date, if
if os.path.exists(edition): # this machine has it (not in
shutil.copy(edition, os.path.join(B, "assets", "fonts", "Edition.ttf")) # the repo: its licence is unknown)
# the tasks' font, as on the desktop: Century Gothic if this machine has it (not in the repo,
# it's licensed), else URW Gothic (free, from Fedora's urw-base35 fonts), else the system's
for src, name in ((os.path.expanduser("~/.local/share/fonts/GOTHIC.TTF"), "Tasks.ttf"),
("/usr/share/fonts/urw-base35/URWGothic-Book.otf", "Tasks.otf")):
if os.path.exists(src):
shutil.copy(src, os.path.join(B, "assets", "fonts", name))
break
with open(os.path.join(HERE, "src/main/AndroidManifest.xml")) as f:
manifest = f.read().replace("@PKG@", pkg).replace("@LABEL@", label)
with open(B + "/AndroidManifest.xml", "w") as f:
f.write(manifest)
code = int((dt.datetime.now() - dt.datetime(2026, 1, 1)).total_seconds() // 60)
run(os.path.join(BT, "aapt2"), "compile", "--dir", os.path.join(HERE, "src/main/res"), "-o", B + "/res.zip")
run(os.path.join(BT, "aapt2"), "link", "-I", JAR, "--manifest", B + "/AndroidManifest.xml",
"--custom-package", PKG,
"-o", B + "/base.apk", "-A", B + "/assets", "--java", B + "/gen", "--min-sdk-version", "26",
"--target-sdk-version", "33", "--version-code", str(code), "--version-name", VERSION_NAME,
"-0", "wav", "-0", "json", B + "/res.zip")
srcs = glob.glob(os.path.join(HERE, "src/main/java/**/*.java"), recursive=True) + \
glob.glob(B + "/gen/**/*.java", recursive=True)
run(os.path.join(JAVA, "bin/javac"), "--release", "11", "-classpath", JAR, "-d", B + "/classes", "-Xlint:-options", *srcs)
# build-tools 34's d8 crashes on javac 21's nameless MethodParameters in inner-class constructors:
# only static nested classes and lambdas are allowed (rabbit.html#toolchain).
classes = glob.glob(B + "/classes/**/*.class", recursive=True)
bad = []
for c in classes:
if "$" not in os.path.basename(c):
continue
name = os.path.basename(c)[:-6].split("$")[-1]
if name.isdigit():
bad.append(c)
elif "MethodParameters" in run(os.path.join(JAVA, "bin/javap"), "-v", c):
bad.append(c)
if bad:
sys.exit("anonymous/inner classes are not allowed:\n " + "\n ".join(bad))
run(os.path.join(BT, "d8"), "--release", "--min-api", "26", "--lib", JAR, "--output", B + "/dex", *classes)
with zipfile.ZipFile(B + "/base.apk", "a") as z:
z.write(B + "/dex/classes.dex", "classes.dex")
run(os.path.join(BT, "zipalign"), "-f", "-p", "4", B + "/base.apk", B + "/aligned.apk")
if not os.path.exists(KEYSTORE):
run(os.path.join(JAVA, "bin/keytool"), "-genkeypair", "-keystore", KEYSTORE, "-storepass", KS_PASS,
"-keypass", KS_PASS, "-alias", "routine", "-keyalg", "RSA", "-keysize", "2048", "-validity", "36500",
"-dname", "CN=routine")
run(os.path.join(BT, "apksigner"), "sign", "--ks", KEYSTORE, "--ks-pass", "pass:" + KS_PASS,
"--out", B + "/routine.apk", B + "/aligned.apk")
if dev:
print("built android/build/routine.apk as %s (dev), %d" % (pkg, code))
return
os.makedirs(os.path.join(HERE, "apk"), exist_ok=True)
shutil.copy(B + "/routine.apk", os.path.join(HERE, "apk", "routine.apk"))
with open(os.path.join(HERE, "apk", "routine-apk.json"), "w") as f:
json.dump({"package": PKG, "versionName": VERSION_NAME, "versionCode": code}, f, indent=2)
print("built android/apk/routine.apk %s (%d), %d KiB" % (VERSION_NAME, code,
os.path.getsize(B + "/routine.apk") // 1024))
if __name__ == "__main__":
main()
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="@PKG@">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="@LABEL@"
android:icon="@drawable/ic_launcher"
android:allowBackup="false"
android:usesCleartextTraffic="true"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
<activity
android:name="me.teafry.routine.MainActivity"
android:exported="true"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation|screenSize|keyboardHidden|keyboard|navigation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,374 @@
package me.teafry.routine;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.media.AudioAttributes;
import android.media.SoundPool;
import android.os.SystemClock;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Plays the stop-motion check-off animations (assets/animations.json, made by
* tools/gen_animations.py) out of a box, with their sounds. Frames are held 1/fps s each.
* A tick that reaches a streak level (Model.streakLevel) plays one of that level's streak
* animations instead (a calm task: a calm streak one), drawn with the streak number (Digits);
* a level with none yet falls back to the nearest lower level that has some (else the nearest
* higher), as on the desktop (routine/gui/overlay.py). A streak play also shows "<n> days!"
* (Digits.captionStrokes) under the animation, or over it when that keeps it bigger or nearer the
* box, from the frame its number first shows (Digits.captionStart) to the end; placement fits the animation and its caption together.
*/
final class AnimView extends View {
static final class Anim {
String name;
int color;
String sound;
float[][][] frames; // frame -> shape -> [kind(0 p, 1 l, 2 c, 3 colour, 4 number), w, coords...]
float x0, y0, x1, y1; // all it ever draws but the number, in box units from the box's centre
boolean hasNumber; // has "n" shapes
float maxN; // the tallest "n" shape's h (sizes the caption)
int firstN = -1; // the first frame with an "n" shape (starts the caption)
}
static final class Playing {
Anim a;
long t0;
View box;
float x, y, u; // where and how big: near the box, all of it on screen
int number; // the streak number its "n" shapes show (0: none)
float[] b; // x0, y0, x1, y1: all it draws, the number (and caption) included
float[] cap; // the caption's {cx, top} in box units, or null: none
float capH; // its height (Digits.captionH)
float bx, by; // the box's centre, as last seen
}
private final List<Anim> anims = new ArrayList<>();
private final java.util.Random random = new java.util.Random();
private final Map<String, Integer> palette = new HashMap<>();
private Anim star;
private final List<Anim> calm = new ArrayList<>();
private final List<List<Anim>> streakSets = new ArrayList<>(); // per level (animations.json "streak")
private final List<Anim> streakCalm = new ArrayList<>();
private int[] sets = new int[0];
private final List<Playing> playing = new ArrayList<>();
private final Map<String, Integer> sounds = new HashMap<>();
private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path path = new Path();
private final int[] loc = new int[2], me = new int[2];
private SoundPool pool;
private int fps = 12;
private final float unit;
AnimView(Context c, String json) {
super(c);
unit = Ui.dp(c, Ui.ANIM_UNIT);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
try {
JSONObject d = new JSONObject(json);
fps = d.optInt("fps", 12);
JSONObject colors = d.getJSONObject("colors");
java.util.Iterator<String> names = colors.keys();
while (names.hasNext()) {
String n = names.next();
palette.put(n, Color.parseColor(colors.getString(n)));
}
JSONArray as = d.getJSONArray("animations");
for (int i = 0; i < as.length(); i++) anims.add(parse(as.getJSONObject(i)));
if (d.optJSONObject("star") != null) star = parse(d.getJSONObject("star"));
JSONArray cs = d.optJSONArray("calm");
if (cs != null) for (int i = 0; i < cs.length(); i++) calm.add(parse(cs.getJSONObject(i)));
JSONArray ss = d.optJSONArray("sets");
sets = new int[ss == null ? 1 : ss.length()];
if (ss == null) sets[0] = anims.size();
else for (int i = 0; i < ss.length(); i++) sets[i] = ss.getInt(i);
JSONObject st = d.optJSONObject("streak");
JSONArray sl = st == null ? null : st.optJSONArray("sets");
for (int i = 0; sl != null && i < sl.length(); i++) {
List<Anim> level = new ArrayList<>();
JSONArray la = sl.optJSONArray(i);
for (int k = 0; la != null && k < la.length(); k++) level.add(parse(la.getJSONObject(k)));
streakSets.add(level);
}
JSONArray sc = st == null ? null : st.optJSONArray("calm");
for (int i = 0; sc != null && i < sc.length(); i++) streakCalm.add(parse(sc.getJSONObject(i)));
} catch (JSONException e) {
android.util.Log.w("routine", "bad animations.json", e);
}
pool = new SoundPool.Builder().setMaxStreams(4).setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()).build();
List<Anim> withStar = new ArrayList<>(anims);
if (star != null) withStar.add(star);
withStar.addAll(calm);
for (List<Anim> level : streakSets) withStar.addAll(level);
withStar.addAll(streakCalm);
for (Anim a : withStar) {
if (sounds.containsKey(a.sound)) continue;
try (AssetFileDescriptor fd = c.getAssets().openFd("sounds/" + a.sound)) {
sounds.put(a.sound, pool.load(fd, 1));
} catch (IOException e) {
android.util.Log.w("routine", "no sound " + a.sound, e);
}
}
}
private Anim parse(JSONObject o) throws JSONException {
Anim a = new Anim();
a.name = o.getString("name");
Integer c = palette.get(o.getString("color"));
a.color = c == null ? Ui.WHITE : c;
a.sound = o.getString("sound");
JSONArray fr = o.getJSONArray("frames");
a.frames = new float[fr.length()][][];
for (int f = 0; f < fr.length(); f++) {
JSONArray shapes = fr.getJSONArray(f);
a.frames[f] = new float[shapes.length()][];
for (int s = 0; s < shapes.length(); s++) {
JSONArray sh = shapes.getJSONArray(s);
String k = sh.getString(0);
float[] v;
if (k.equals("k")) { // ["k", colour name]: the shapes after it use that colour
Integer pc = palette.get(sh.getString(1));
v = new float[] {3, pc == null ? a.color : pc};
} else {
v = new float[sh.length()];
v[0] = k.equals("p") ? 0 : k.equals("l") ? 1 : k.equals("n") ? 4 : 2;
for (int n = 1; n < sh.length(); n++) v[n] = (float) sh.getDouble(n);
}
a.frames[f][s] = v;
if (v[0] == 4) {
a.hasNumber = true;
if (a.firstN < 0) a.firstN = f;
if (v.length > 4) a.maxN = Math.max(a.maxN, v[4]);
}
if (v[0] == 3 || v[0] == 4) continue; // everything it draws, for keeping it on screen
float pad = v[1] / 2;
if (v[0] == 2) {
float r = v[4] + pad;
a.x0 = Math.min(a.x0, v[2] - r);
a.x1 = Math.max(a.x1, v[2] + r);
a.y0 = Math.min(a.y0, v[3] - r);
a.y1 = Math.max(a.y1, v[3] + r);
} else {
for (int n = 2; n + 1 < v.length; n += 2) {
a.x0 = Math.min(a.x0, v[n] - pad);
a.x1 = Math.max(a.x1, v[n] + pad);
a.y0 = Math.min(a.y0, v[n + 1] - pad);
a.y1 = Math.max(a.y1, v[n + 1] + pad);
}
}
}
}
return a;
}
void release() {
if (pool != null) pool.release();
pool = null;
}
/** The streak animations for a level index: its own, else the nearest lower level's that has
* some (else the nearest higher); a calm task's: the calm streak ones. Empty = none at all. */
List<Anim> streakChoices(int level, boolean isCalm) {
if (isCalm && !streakCalm.isEmpty()) return streakCalm;
for (int k = Math.min(level, streakSets.size() - 1); k >= 0; k--) if (!streakSets.get(k).isEmpty()) return streakSets.get(k);
for (int k = level + 1; k < streakSets.size(); k++) if (!streakSets.get(k).isEmpty()) return streakSets.get(k);
return new ArrayList<>();
}
/** Play out of box; returns {name, set} pairs for the day's log (see Model.animSet).
* A calm task plays one of the calm set instead, never the star. streak: the streak this
* tick reached; a rewarded one plays a streak animation instead (set STREAK_SET / STREAK_CALM_SET). */
List<String[]> play(View box, int doneBefore, boolean isCalm, int streak) {
List<String[]> out = new ArrayList<>();
int level = streak > 0 ? Model.streakLevel(streak) : -1;
List<Anim> choices = level >= 0 ? streakChoices(level, isCalm) : new ArrayList<>();
if (anims.isEmpty() && choices.isEmpty()) return out;
int[] set = anims.isEmpty() ? new int[] {0, 0, 0, 0} : Model.animSet(doneBefore, sets);
List<Anim> chosen = new ArrayList<>();
int number = 0;
if (!choices.isEmpty()) {
chosen.add(choices.get(random.nextInt(choices.size())));
set[2] = isCalm && !streakCalm.isEmpty() ? Model.STREAK_CALM_SET : Model.STREAK_SET;
number = streak;
} else if (isCalm && !calm.isEmpty()) {
chosen.add(calm.get(random.nextInt(calm.size())));
set[2] = Model.CALM_SET;
} else {
chosen.add(anims.get(set[0] + random.nextInt(set[1] - set[0])));
if (set[3] == 1 && star != null) chosen.add(star);
}
long now = SystemClock.uptimeMillis();
for (Anim a : chosen) {
Playing pl = new Playing();
pl.a = a;
pl.t0 = now;
pl.box = box;
pl.u = unit;
pl.number = number;
pl.b = bounds(a, number);
if (number != 0) placeCaption(pl);
centre(pl);
playing.add(pl);
Integer id = sounds.get(a.sound);
if (id != null && pool != null) pool.play(id, 0.8f, 0.8f, 1, 0, 1f);
out.add(new String[] {a.name, Integer.toString(set[2])});
}
invalidate();
return out;
}
/** The caption under the animation, or above it if that draws it bigger, then nearer the box
* (anim_paint.caption_place; the desktop's overlay chooses the same way). */
private void placeCaption(Playing pl) {
float[] b = pl.b;
pl.capH = (float) Digits.captionH(pl.a.maxN);
float[] best = null;
float bestU = 0, bestMove = 0;
for (boolean above : new boolean[] {false, true}) {
float[] cp = Digits.captionPlace(b, pl.number, above, pl.capH);
pl.b = new float[] {cp[2], cp[3], cp[4], cp[5]};
if (!centre(pl)) {
best = cp;
break;
}
float move = Math.abs(pl.x - pl.bx) + Math.abs(pl.y - pl.by);
if (best == null || pl.u > bestU || (pl.u == bestU && move < bestMove)) {
best = cp;
bestU = pl.u;
bestMove = move;
}
}
pl.cap = new float[] {best[0], best[1]};
pl.b = new float[] {best[2], best[3], best[4], best[5]};
}
/** anim_paint.bounds: everything a draws over all its frames, the number's strokes (and their
* half widths) included when it has one to show. */
private static float[] bounds(Anim a, int number) {
float[] b = {a.x0, a.y0, a.x1, a.y1};
if (!a.hasNumber || number == 0) return b;
for (float[][] frame : a.frames) {
for (float[] sh : frame) {
if (sh[0] != 4 || sh.length < 6) continue;
float pad = sh[1] / 2;
for (float[] st : Digits.strokes(number, sh[2], sh[3], sh[4], sh[5])) {
for (int n = 0; n + 1 < st.length; n += 2) {
b[0] = Math.min(b[0], st[n] - pad);
b[2] = Math.max(b[2], st[n] + pad);
b[1] = Math.min(b[1], st[n + 1] - pad);
b[3] = Math.max(b[3], st[n + 1] + pad);
}
}
}
}
return b;
}
/** Out of the box's centre, moved as little as keeps all of it on screen; smaller only
* when it can't fit at full size. */
private boolean centre(Playing pl) {
if (pl.box == null || !pl.box.isShown()) return false;
pl.box.getLocationInWindow(loc);
getLocationInWindow(me);
pl.bx = loc[0] - me[0] + pl.box.getWidth() / 2f;
pl.by = loc[1] - me[1] + pl.box.getHeight() / 2f;
float[] b = pl.b;
float edge = Ui.dp(getContext(), 6);
pl.u = unit * Math.min(1f, Math.min((getWidth() - 2 * edge) / Math.max(1e-3f, (b[2] - b[0]) * unit),
(getHeight() - 2 * edge) / Math.max(1e-3f, (b[3] - b[1]) * unit)));
pl.x = fit(pl.bx, b[0] * pl.u, b[2] * pl.u, getWidth(), edge);
pl.y = fit(pl.by, b[1] * pl.u, b[3] * pl.u, getHeight(), edge);
return true;
}
private static float fit(float c, float lo, float hi, float size, float edge) {
if (hi - lo >= size - 2 * edge) return size / 2 - (lo + hi) / 2;
if (c + lo < edge) return edge - lo;
if (c + hi > size - edge) return size - edge - hi;
return c;
}
@Override
protected void onDraw(Canvas c) {
long now = SystemClock.uptimeMillis();
for (int i = playing.size() - 1; i >= 0; i--) {
Playing pl = playing.get(i);
int f = (int) ((now - pl.t0) * fps / 1000);
if (f >= pl.a.frames.length) {
playing.remove(i);
continue;
}
centre(pl);
p.setColor(pl.a.color);
for (float[] sh : pl.a.frames[f]) {
if (sh[0] == 3) p.setColor((int) sh[1]);
else if (sh[0] == 4) drawNumber(c, sh, pl.number, pl.x, pl.y, pl.u);
else draw(c, sh, pl.x, pl.y, pl.u);
}
if (pl.cap != null) drawCaption(c, pl, f);
}
if (!playing.isEmpty()) postInvalidateDelayed(1000 / fps);
}
/** ["n", w, cx, cy, h, rot]: the number's digit strokes, w wide, round caps and joins, never filled. */
private void drawNumber(Canvas c, float[] sh, int number, float cx, float cy, float unit) {
if (number == 0 || sh.length < 6) return;
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(sh[1] * unit);
for (float[] st : Digits.strokes(number, sh[2], sh[3], sh[4], sh[5])) {
path.reset();
path.moveTo(cx + st[0] * unit, cy + st[1] * unit);
for (int k = 2; k + 1 < st.length; k += 2) path.lineTo(cx + st[k] * unit, cy + st[k + 1] * unit);
c.drawPath(path, p);
}
}
/** "<n> days!" in the animation's own colour, popping in over the first frames. */
private void drawCaption(Canvas c, Playing pl, int frame) {
double s = Digits.captionScale(frame, Digits.captionStart(pl.a.firstN, pl.a.frames.length));
if (s <= 0) return;
p.setColor(pl.a.color);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth((float) (Digits.CAPTION_STROKE * pl.capH * s * pl.u));
for (float[] st : Digits.captionStrokes(pl.number, pl.cap[0], pl.cap[1], pl.capH, s)) {
path.reset();
path.moveTo(pl.x + st[0] * pl.u, pl.y + st[1] * pl.u);
for (int k = 2; k + 1 < st.length; k += 2) path.lineTo(pl.x + st[k] * pl.u, pl.y + st[k + 1] * pl.u);
c.drawPath(path, p);
}
}
private void draw(Canvas c, float[] sh, float cx, float cy, float unit) {
float w = sh[1];
if (w > 0) {
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(w * unit);
} else {
p.setStyle(Paint.Style.FILL);
}
if (sh[0] == 2) {
c.drawCircle(cx + sh[2] * unit, cy + sh[3] * unit, sh[4] * unit, p);
return;
}
path.reset();
path.moveTo(cx + sh[2] * unit, cy + sh[3] * unit);
for (int k = 4; k + 1 < sh.length; k += 2) path.lineTo(cx + sh[k] * unit, cy + sh[k + 1] * unit);
if (sh[0] == 0) path.close();
c.drawPath(path, p);
}
}
@@ -0,0 +1,120 @@
package me.teafry.routine;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.view.View;
/**
* The checkbox. Dark: a white-rimmed square; done = filled with a check, skipped = a dash.
* Light: the desktop's (design.html#emboss): a softly embossed button-gray square, sunk while
* pressed; done = a check in the highlight colour, skipped = a gray dash.
*/
final class BoxView extends View {
String state = Model.PENDING;
private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
private final RectF r = new RectF();
private final Path check = new Path();
BoxView(Context c) {
super(c);
setClickable(true);
}
void setState(String s) {
state = s;
setContentDescription(Model.DONE.equals(s) ? "done" : Model.SKIPPED.equals(s) ? "skipped" : "not done");
invalidate();
}
/** Qt's darker(f) / lighter(f) on a gray-ish colour: each channel scaled by 100/f (or f/100). */
static int shade(int c, float f) {
float k = f >= 0 ? 100f / f : -f / 100f;
int a = c >>> 24, rr = Math.min(255, Math.round(((c >> 16) & 255) * k)),
g = Math.min(255, Math.round(((c >> 8) & 255) * k)), b = Math.min(255, Math.round((c & 255) * k));
return (a << 24) | (rr << 16) | (g << 8) | b;
}
static int darker(int c, int f) {
return shade(c, f);
}
static int lighter(int c, int f) {
return shade(c, -f);
}
@Override
protected void onDraw(Canvas c) {
if (Ui.light) {
drawLight(c);
return;
}
float w = getWidth(), h = getHeight(), s = Math.min(w, h), sw = s * 0.08f;
r.set((w - s) / 2 + sw, (h - s) / 2 + sw, (w + s) / 2 - sw, (h + s) / 2 - sw);
p.setShader(null);
p.setStrokeWidth(sw);
boolean done = Model.DONE.equals(state);
p.setStyle(done ? Paint.Style.FILL_AND_STROKE : Paint.Style.STROKE);
p.setColor(isPressed() ? Ui.HIGHLIGHT : Model.SKIPPED.equals(state) ? Ui.GRAY : Ui.WHITE);
c.drawRoundRect(r, s * 0.14f, s * 0.14f, p);
if (done) {
p.setStyle(Paint.Style.STROKE);
p.setColor(Ui.BLACK);
p.setStrokeWidth(s * 0.12f);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
drawCheck(c);
} else if (Model.SKIPPED.equals(state)) {
p.setStrokeCap(Paint.Cap.ROUND);
c.drawLine(r.left + r.width() * 0.25f, r.centerY(), r.right - r.width() * 0.25f, r.centerY(), p);
}
}
private void drawLight(Canvas c) {
float w = getWidth(), h = getHeight(), s = Math.min(w, h) * 0.86f, rad = s * 0.18f;
r.set((w - s) / 2, (h - s) / 2, (w + s) / 2, (h + s) / 2);
boolean sunk = isPressed();
int face = sunk ? darker(Ui.BUTTON, 125) : Ui.BUTTON;
int top = sunk ? darker(face, 116) : lighter(face, 116), bot = sunk ? lighter(face, 116) : darker(face, 116);
int ftop = sunk ? darker(face, 103) : lighter(face, 103), fbot = sunk ? lighter(face, 103) : darker(face, 103);
p.setStyle(Paint.Style.FILL);
p.setShader(new LinearGradient(0, r.top, 0, r.bottom, new int[] {top, ftop, face, face, fbot, bot},
new float[] {0f, 0.08f, 0.3f, 0.7f, 0.92f, 1f}, Shader.TileMode.CLAMP));
c.drawRoundRect(r, rad, rad, p);
p.setShader(null);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(Math.max(1.5f, s * 0.03f));
p.setColor(darker(face, 135));
c.drawRoundRect(r, rad, rad, p);
if (Model.DONE.equals(state)) {
p.setColor(Ui.HIGHLIGHT);
p.setStrokeWidth(s * 0.13f);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
drawCheck(c);
} else if (Model.SKIPPED.equals(state)) {
p.setColor(Ui.GRAY);
p.setStrokeWidth(s * 0.1f);
p.setStrokeCap(Paint.Cap.ROUND);
c.drawLine(r.left + r.width() * 0.28f, r.centerY(), r.right - r.width() * 0.28f, r.centerY(), p);
}
}
private void drawCheck(Canvas c) {
check.reset();
check.moveTo(r.left + r.width() * 0.22f, r.top + r.height() * 0.52f);
check.lineTo(r.left + r.width() * 0.42f, r.top + r.height() * 0.72f);
check.lineTo(r.left + r.width() * 0.78f, r.top + r.height() * 0.28f);
c.drawPath(check, p);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
}
@@ -0,0 +1,45 @@
package me.teafry.routine;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.View;
/** The light look's date, like the desktop's: capitals of a set height on a fixed baseline,
* a set space above them and a little below; smaller only when the width runs out. */
final class DateView extends View {
private final String text;
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final int above, cap, below, side;
DateView(Context c, String text, Typeface face, int color, int above, int cap, int below, int side) {
super(c);
this.text = text;
this.above = above;
this.cap = cap;
this.below = below;
this.side = side;
paint.setTypeface(face);
paint.setColor(color);
setContentDescription(text);
}
@Override
protected void onMeasure(int w, int h) {
setMeasuredDimension(MeasureSpec.getSize(w), above + cap + below);
}
@Override
protected void onDraw(Canvas c) {
Rect r = new Rect();
paint.setTextSize(100);
paint.getTextBounds("HEMT", 0, 4, r); // the capitals' real height at 100 px
float size = 100f * cap / Math.max(1, r.height());
paint.setTextSize(size);
float room = getWidth() - 2 * side, w = paint.measureText(text);
if (w > room) paint.setTextSize(size * room / w);
c.drawText(text, side, above + cap, paint);
}
}
@@ -0,0 +1,150 @@
package me.teafry.routine;
/**
* The streak number shape ["n", w, cx, cy, h, rot] and the "<n> days!" caption under a streak
* animation: a port of routine/gui/anim_paint.py's number_strokes, DIGITS, LETTERS, caption_h,
* caption_strokes, caption_place and caption_scale (its docstring is the spec; keep the two in step).
* Pure, for android/test.
*/
final class Digits {
static final double DIGIT_W = 0.6, DIGIT_ADV = 0.82;
/** Hand-drawn strokes in a DIGIT_W x 1 cell, y down: DIGITS[d] = strokes, each x0, y0, x1, y1, ... */
static final double[][][] DIGITS = {
{{0.3, 0.0, 0.5, 0.07, 0.6, 0.3, 0.6, 0.7, 0.5, 0.93, 0.3, 1.0, 0.1, 0.93, 0.0, 0.7, 0.0, 0.3, 0.1, 0.07,
0.3, 0.0}},
{{0.1, 0.2, 0.34, 0.0, 0.34, 1.0}, {0.1, 1.0, 0.56, 1.0}},
{{0.02, 0.22, 0.12, 0.06, 0.3, 0.0, 0.48, 0.06, 0.58, 0.24, 0.52, 0.44, 0.02, 1.0, 0.6, 1.0}},
{{0.04, 0.1, 0.24, 0.0, 0.46, 0.04, 0.56, 0.2, 0.48, 0.38, 0.26, 0.46, 0.5, 0.54, 0.6, 0.74, 0.52, 0.92,
0.3, 1.0, 0.04, 0.9}},
{{0.46, 1.0, 0.46, 0.0, 0.0, 0.68, 0.6, 0.68}},
{{0.56, 0.0, 0.1, 0.0, 0.05, 0.44, 0.28, 0.38, 0.5, 0.46, 0.6, 0.68, 0.52, 0.9, 0.3, 1.0, 0.02, 0.92}},
{{0.52, 0.04, 0.32, 0.0, 0.12, 0.12, 0.02, 0.4, 0.02, 0.72, 0.12, 0.94, 0.3, 1.0, 0.5, 0.94, 0.6, 0.74,
0.52, 0.52, 0.3, 0.46, 0.1, 0.54, 0.02, 0.7}},
{{0.0, 0.0, 0.6, 0.0, 0.22, 1.0}},
{{0.3, 0.46, 0.1, 0.38, 0.06, 0.2, 0.16, 0.04, 0.3, 0.0, 0.44, 0.04, 0.54, 0.2, 0.5, 0.38, 0.3, 0.46,
0.06, 0.56, 0.0, 0.76, 0.1, 0.94, 0.3, 1.0, 0.5, 0.94, 0.6, 0.76, 0.54, 0.56, 0.3, 0.46}},
{{0.08, 0.96, 0.28, 1.0, 0.48, 0.88, 0.58, 0.6, 0.58, 0.28, 0.48, 0.06, 0.3, 0.0, 0.1, 0.06, 0.0, 0.26,
0.08, 0.48, 0.3, 0.54, 0.5, 0.46, 0.58, 0.3}},
};
/** The caption's letters (d, a, y, s, !): their widths, and strokes in the same cell as DIGITS. */
static final String LETTER_CHARS = "days!";
static final double[] LETTER_W = {0.5, 0.52, 0.5, 0.45, 0.16};
static final double[][][] LETTERS = {
{{0.5, 0.0, 0.5, 1.0}, {0.5, 0.58, 0.38, 0.45, 0.22, 0.43, 0.08, 0.52, 0.02, 0.72, 0.08, 0.92,
0.22, 1.0, 0.38, 0.98, 0.5, 0.86}},
{{0.46, 0.43, 0.46, 0.92, 0.52, 1.0}, {0.46, 0.58, 0.34, 0.45, 0.2, 0.43, 0.07, 0.52, 0.0, 0.72,
0.07, 0.92, 0.2, 1.0, 0.34, 0.97, 0.46, 0.84}},
{{0.0, 0.43, 0.26, 0.98}, {0.5, 0.43, 0.24, 1.12, 0.16, 1.28, 0.04, 1.32}},
{{0.44, 0.5, 0.32, 0.43, 0.16, 0.43, 0.04, 0.5, 0.04, 0.62, 0.16, 0.69, 0.32, 0.74, 0.45, 0.82,
0.45, 0.93, 0.32, 1.0, 0.14, 1.0, 0.0, 0.92}},
{{0.08, 0.0, 0.08, 0.7}, {0.08, 0.98, 0.08, 1.0}},
};
static final double CAPTION_H = 0.9, CAPTION_REL = 0.7, CAPTION_MIN = 0.6, CAPTION_STROKE = 0.16,
CAPTION_GAP = 0.18, CAPTION_SPACE = 0.32, CAPTION_SEP = 0.35, CAPTION_DEEP = 1.32;
static final double[] CAPTION_POP = {0.5, 0.8, 1.08};
static final int CAPTION_LAST = 10; // on screen at least this many frames (the last ones)
private Digits() {}
/** caption_h: from the tallest "n" shape's h in an animation (maxN; 0 = none). */
static double captionH(double maxN) {
return maxN > 0 ? Math.max(CAPTION_MIN, Math.min(CAPTION_H, CAPTION_REL * maxN)) : CAPTION_H;
}
/** caption_start: the first frame with an "n" shape (firstN; -1 = none: 0), at the latest CAPTION_LAST from the end. */
static int captionStart(int firstN, int frames) {
return Math.max(0, Math.min(Math.max(firstN, 0), frames - CAPTION_LAST));
}
/** caption_scale: 0 (not drawn) before start, then CAPTION_POP, then 1. */
static double captionScale(int frame, int start) {
int k = frame - start;
if (k < 0) return 0.0;
return k < CAPTION_POP.length ? CAPTION_POP[k] : 1.0;
}
/** caption_strokes: "<n> days!" in box units, centred on cx, its cell's top at top, scaled by scale. */
static float[][] captionStrokes(int number, double cx, double top, double h, double scale) {
String text = number + " days!";
double[] widths = new double[text.length()];
double[][][] glyphs = new double[text.length()][][];
for (int k = 0; k < text.length(); k++) {
char ch = text.charAt(k);
int li = LETTER_CHARS.indexOf(ch);
if (ch >= '0' && ch <= '9') {
widths[k] = DIGIT_W;
glyphs[k] = DIGITS[ch - '0'];
} else if (li >= 0) {
widths[k] = LETTER_W[li];
glyphs[k] = LETTERS[li];
} else {
widths[k] = CAPTION_SPACE;
glyphs[k] = new double[0][];
}
}
double[] starts = new double[text.length()];
double x = 0;
for (int k = 0; k < text.length(); k++) {
starts[k] = x;
x += widths[k] + CAPTION_GAP;
}
double W = x - CAPTION_GAP;
java.util.List<float[]> out = new java.util.ArrayList<>();
for (int k = 0; k < text.length(); k++) {
for (double[] stroke : glyphs[k]) {
float[] pts = new float[stroke.length];
for (int m = 0; m + 1 < stroke.length; m += 2) {
pts[m] = (float) (cx + (starts[k] + stroke[m] - W / 2) * h * scale);
pts[m + 1] = (float) (top + h / 2 + (stroke[m + 1] - 0.5) * h * scale);
}
out.add(pts);
}
}
return out.toArray(new float[0][]);
}
/** caption_place: {cx, top, x0, y0, x1, y1} = where the caption goes under (above) bounds b
* ({x0, y0, x1, y1}), and the union of b and the caption. */
static float[] captionPlace(float[] b, int number, boolean above, double h) {
double pad = CAPTION_STROKE * h / 2;
double cx = (b[0] + b[2]) / 2.0;
double top = above ? Math.min(b[1], -0.5) - CAPTION_SEP - pad - CAPTION_DEEP * h
: Math.max(b[3], 0.5) + CAPTION_SEP + pad;
double x0 = Double.MAX_VALUE, y0 = Double.MAX_VALUE, x1 = -Double.MAX_VALUE, y1 = -Double.MAX_VALUE;
for (float[] st : captionStrokes(number, cx, top, h, 1.0)) {
for (int m = 0; m + 1 < st.length; m += 2) {
x0 = Math.min(x0, st[m]);
x1 = Math.max(x1, st[m]);
y0 = Math.min(y0, st[m + 1]);
y1 = Math.max(y1, st[m + 1]);
}
}
return new float[] {(float) cx, (float) top, (float) Math.min(b[0], x0 - pad), (float) Math.min(b[1], y0 - pad),
(float) Math.max(b[2], x1 + pad), (float) Math.max(b[3], y1 + pad)};
}
/** The number's strokes in box units, [[x0, y0, x1, y1, ...], ...]: its digits left to right, each
* DIGIT_W * h wide, DIGIT_ADV * h apart, the row centred on (cx, cy) and turned by rot. */
static float[][] strokes(int number, double cx, double cy, double h, double rot) {
String text = Integer.toString(number);
double W = (text.length() - 1) * DIGIT_ADV + DIGIT_W;
double c = Math.cos(rot), s = Math.sin(rot);
java.util.List<float[]> out = new java.util.ArrayList<>();
for (int k = 0; k < text.length(); k++) {
int d = text.charAt(k) - '0';
if (d < 0 || d > 9) continue;
for (double[] stroke : DIGITS[d]) {
float[] pts = new float[stroke.length];
for (int m = 0; m + 1 < stroke.length; m += 2) {
double u = (k * DIGIT_ADV + stroke[m] - W / 2) * h;
double v = (stroke[m + 1] - 0.5) * h;
pts[m] = (float) (cx + u * c - v * s);
pts[m + 1] = (float) (cy + u * s + v * c);
}
out.add(pts);
}
}
return out.toArray(new float[0][]);
}
}
@@ -0,0 +1,69 @@
package me.teafry.routine;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
/** The bottom bar's drawn icons: a shining sun (light look), a crescent moon (dark look),
* and the double chevron for Now. */
final class IconView extends View {
static final int SUN = 0, MOON = 1, CHEVRONS = 2;
int kind;
float stroke, tall; // the chevrons: line weight and height (0 = from the view's size)
private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path path = new Path(), cut = new Path();
IconView(Context c, int kind) {
super(c);
this.kind = kind;
setClickable(true);
}
@Override
protected void onDraw(Canvas c) {
float w = getWidth(), h = getHeight(), s = Math.min(w, h) * 0.62f, cx = w / 2, cy = h / 2;
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
if (kind == SUN) {
p.setStyle(Paint.Style.FILL);
p.setColor(Ui.SUN);
c.drawCircle(cx, cy, s * 0.24f, p);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(s * 0.09f);
for (int k = 0; k < 8; k++) {
double a = k * Math.PI / 4;
c.drawLine(cx + (float) (s * 0.36 * Math.cos(a)), cy + (float) (s * 0.36 * Math.sin(a)),
cx + (float) (s * 0.5 * Math.cos(a)), cy + (float) (s * 0.5 * Math.sin(a)), p);
}
} else if (kind == MOON) {
p.setStyle(Paint.Style.FILL);
p.setColor(0xFFFFE7A0);
path.reset();
path.addCircle(cx, cy, s * 0.42f, Path.Direction.CW);
cut.reset();
cut.addCircle(cx + s * 0.24f, cy - s * 0.16f, s * 0.36f, Path.Direction.CW);
path.op(cut, Path.Op.DIFFERENCE);
c.drawPath(path, p);
} else {
p.setStyle(Paint.Style.STROKE);
p.setColor(Ui.FG);
p.setStrokeWidth(stroke > 0 ? stroke : s * 0.13f);
float u = tall > 0 ? tall / 2.6f : s * 0.26f;
for (float dx : new float[] {-u * 0.9f, u * 0.9f}) {
path.reset();
path.moveTo(cx + dx - u * 0.6f, cy - u * 1.3f);
path.lineTo(cx + dx + u * 0.6f, cy);
path.lineTo(cx + dx - u * 0.6f, cy + u * 1.3f);
c.drawPath(path, p);
}
}
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,438 @@
package me.teafry.routine;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/** Line-for-line port of routine/model.py: the day record and how two copies merge. Keep in step. */
final class Model {
static final String DONE = "done", SKIPPED = "skipped", PENDING = "";
static final String STAR = "star_special";
static final int PER_SET = 5;
static final int CALM_SET = -1; // the play log's set number for the calm set
private Model() {}
static String slug(String label) {
String s = label.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]+", "-").replaceAll("^-+|-+$", "");
return s.isEmpty() ? "item" : s;
}
static String fmt(Calendar c) {
return String.format(Locale.ROOT, "%04d-%02d-%02d", c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1,
c.get(Calendar.DAY_OF_MONTH));
}
static Calendar parse(String date) {
Calendar c = Calendar.getInstance();
c.clear();
c.set(Integer.parseInt(date.substring(0, 4)), Integer.parseInt(date.substring(5, 7)) - 1,
Integer.parseInt(date.substring(8, 10)), 12, 0);
return c;
}
/** The routine day now belongs to: before dayStartsAt it is still yesterday. */
static String routineDate(JSONObject schedule) {
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR_OF_DAY, -schedule.optInt("dayStartsAt", 4));
return fmt(c);
}
private static boolean has(JSONArray a, int v) {
for (int i = 0; i < a.length(); i++) if (a.optInt(i, -1) == v) return true;
return false;
}
static boolean onDay(JSONObject x, int weekday) {
JSONArray days = x.optJSONArray("days");
return days == null || has(days, weekday);
}
private static void flatten(JSONArray items, int weekday, String prefix, int depth, JSONArray out)
throws JSONException {
Set<String> seen = new HashSet<>();
for (int i = 0; i < items.length(); i++) {
JSONObject it = items.getJSONObject(i);
if (!onDay(it, weekday)) continue;
String id = prefix + "/" + (it.has("id") ? it.getString("id") : slug(it.getString("label")));
while (seen.contains(id)) id += "-2";
seen.add(id);
JSONObject o = new JSONObject();
o.put("id", id);
o.put("label", it.getString("label"));
o.put("depth", depth);
if (it.optBoolean("hint", false)) o.put("hint", true);
if (it.optBoolean("calm", false)) o.put("calm", true);
out.put(o);
JSONArray sub = it.optJSONArray("items");
if (sub != null) flatten(sub, weekday, id, depth + 1, out);
}
}
static JSONArray snapshot(JSONObject schedule, String date) throws JSONException {
int weekday = parse(date).get(Calendar.DAY_OF_WEEK) - 1; // 0 = Sunday
JSONArray blocks = new JSONArray();
JSONArray src = schedule.getJSONArray("blocks");
for (int i = 0; i < src.length(); i++) {
JSONObject b = src.getJSONObject(i);
if (!onDay(b, weekday)) continue;
JSONArray items = new JSONArray();
JSONArray bi = b.optJSONArray("items");
if (bi != null) flatten(bi, weekday, b.getString("id"), 0, items);
JSONObject o = new JSONObject();
o.put("id", b.getString("id"));
o.put("label", b.getString("label"));
o.put("start", b.getInt("start"));
o.put("end", b.getInt("end"));
o.put("color", b.getString("color"));
o.put("items", items);
blocks.put(o);
}
return blocks;
}
static JSONObject newDay(JSONObject schedule, String date) throws JSONException {
JSONObject d = new JSONObject();
d.put("date", date);
d.put("rev", schedule.optInt("rev", 1));
d.put("blocks", snapshot(schedule, date));
d.put("states", new JSONObject());
JSONObject note = new JSONObject();
note.put("text", "");
note.put("t", 0);
d.put("note", note);
return d;
}
static boolean refreshSnapshot(JSONObject schedule, JSONObject day) throws JSONException {
int rev = schedule.optInt("rev", 1);
if (day.optInt("rev", 0) >= rev) return false;
day.put("rev", rev);
day.put("blocks", snapshot(schedule, day.getString("date")));
return true;
}
static String state(JSONObject day, String id) {
JSONObject s = day.optJSONObject("states");
JSONObject v = s == null ? null : s.optJSONObject(id);
return v == null ? PENDING : v.optString("s", PENDING);
}
static void setState(JSONObject day, String id, String s) throws JSONException {
JSONObject v = new JSONObject();
v.put("s", s);
v.put("t", System.currentTimeMillis());
day.getJSONObject("states").put(id, v);
}
/** Tick or skip an item and give its still-pending sub-items (not suggestions) the same state; returns ids changed. */
static java.util.List<String> setWithChildren(JSONObject day, String id, String s) throws JSONException {
java.util.List<String> changed = new java.util.ArrayList<>();
changed.add(id);
setState(day, id, s);
if (!s.equals(PENDING)) {
JSONArray blocks = day.getJSONArray("blocks");
for (int i = 0; i < blocks.length(); i++) {
JSONArray items = blocks.getJSONObject(i).getJSONArray("items");
for (int k = 0; k < items.length(); k++) {
JSONObject it = items.getJSONObject(k);
String cid = it.getString("id");
if (cid.startsWith(id + "/") && !it.optBoolean("hint", false) && state(day, cid).equals(PENDING)) {
setState(day, cid, s);
changed.add(cid);
}
}
}
}
return changed;
}
/** Tasks ticked by hand and still ticked: distinct items in the play log that are done. */
static int ticks(JSONObject day) {
java.util.Set<String> ids = new java.util.HashSet<>();
JSONArray plays = day.optJSONArray("plays");
if (plays != null) {
for (int i = 0; i < plays.length(); i++) {
JSONObject p = plays.optJSONObject(i);
if (p == null || STAR.equals(p.optString("a"))) continue;
String id = p.optString("i");
if (DONE.equals(state(day, id))) ids.add(id);
}
}
return ids.size();
}
/** sets = each set's size (animations.json "sets"). {first, last+1, set number, star (1/0)}. */
static int[] animSet(int doneBefore, int[] sets) {
int k = doneBefore / PER_SET;
boolean star = k >= sets.length;
k = Math.min(k, sets.length - 1);
int lo = 0;
for (int i = 0; i < k; i++) lo += sets[i];
return new int[] {lo, lo + sets[k], k, star ? 1 : 0};
}
static void addPlay(JSONObject day, String name, String itemId, int setNo) throws JSONException {
addPlay(day, name, itemId, setNo, 0);
}
/** streak: the streak a streak animation celebrated (logged as "n"); 0 for any other play. */
static void addPlay(JSONObject day, String name, String itemId, int setNo, int streak) throws JSONException {
JSONArray plays = day.optJSONArray("plays");
if (plays == null) {
plays = new JSONArray();
day.put("plays", plays);
}
JSONObject p = new JSONObject();
p.put("t", System.currentTimeMillis());
p.put("a", name);
p.put("i", itemId);
p.put("s", setNo);
if (streak != 0) p.put("n", streak);
plays.put(p);
}
private static int comparePlays(JSONObject x, JSONObject y) {
int c = Long.compare(x.optLong("t"), y.optLong("t"));
if (c != 0) return c;
c = x.optString("a").compareTo(y.optString("a"));
return c != 0 ? c : x.optString("i").compareTo(y.optString("i"));
}
static void setNote(JSONObject day, String text) throws JSONException {
JSONObject n = new JSONObject();
n.put("text", text);
n.put("t", System.currentTimeMillis());
day.put("note", n);
}
private static JSONObject newer(JSONObject a, JSONObject b, String key) {
long ta = a.optLong("t", 0), tb = b.optLong("t", 0);
if (ta != tb) return ta > tb ? a : b;
return a.optString(key, "").compareTo(b.optString(key, "")) >= 0 ? a : b;
}
static JSONObject copy(JSONObject o) throws JSONException {
return new JSONObject(o.toString());
}
/** Merge two copies of the same day (either may be null). Pure. */
static JSONObject merge(JSONObject a, JSONObject b) throws JSONException {
if (a == null) return copy(b);
if (b == null) return copy(a);
JSONObject snap = a.optInt("rev", 0) >= b.optInt("rev", 0) ? a : b;
JSONObject states = copy(a.optJSONObject("states") == null ? new JSONObject() : a.getJSONObject("states"));
JSONObject bs = b.optJSONObject("states");
if (bs != null) {
Iterator<String> keys = bs.keys();
while (keys.hasNext()) {
String k = keys.next();
JSONObject v = bs.getJSONObject(k);
JSONObject cur = states.optJSONObject(k);
states.put(k, copy(cur == null ? v : newer(cur, v, "s")));
}
}
JSONObject empty = new JSONObject();
empty.put("text", "");
empty.put("t", 0);
JSONObject na = a.optJSONObject("note"), nb = b.optJSONObject("note");
JSONObject note = newer(na == null ? empty : na, nb == null ? empty : nb, "text");
JSONObject out = new JSONObject();
out.put("date", a.getString("date"));
out.put("rev", snap.optInt("rev", 0));
out.put("blocks", new JSONArray(snap.getJSONArray("blocks").toString()));
out.put("states", states);
out.put("note", copy(note));
java.util.TreeMap<String, JSONObject> plays = new java.util.TreeMap<>();
java.util.List<JSONObject> all = new java.util.ArrayList<>();
for (JSONObject d : new JSONObject[] {a, b}) {
JSONArray ps = d.optJSONArray("plays");
if (ps != null) for (int i = 0; i < ps.length(); i++) if (ps.optJSONObject(i) != null) all.add(ps.getJSONObject(i));
}
java.util.Map<String, JSONObject> byKey = new HashMap<>();
for (JSONObject p : all) byKey.put(p.optLong("t") + "\u0000" + p.optString("a") + "\u0000" + p.optString("i"), p);
java.util.List<JSONObject> sorted = new java.util.ArrayList<>(byKey.values());
java.util.Collections.sort(sorted, Model::comparePlays);
JSONArray outPlays = new JSONArray();
for (JSONObject p : sorted) outPlays.put(copy(p));
out.put("plays", outPlays);
return out;
}
// ── streaks (model.py's "Streaks"): the part a tick needs, the number it reaches ──
// (History, the block marks, run lists and totals are the desktop windows'; not ported)
static final int[] STREAK_LEVELS = {7, 21, 42, 66, 100, 150, 254, 365};
static final int STREAK_EVERY = 100; // past the last level, every 100 more days is the top level again
static final int CHEAT_AFTER = 7; // done days in a row that earn one cheat day (the default)
static final int STREAK_SET = -2; // the play log's set number for a streak animation
static final int STREAK_CALM_SET = -3; // ... and for a calm streak animation
static final String S_DONE = "done", S_MISS = "miss", S_OFF = "off", S_CHEAT = "cheat", S_OPEN = "open";
/** The level index (into STREAK_LEVELS) a streak number is rewarded at, or -1 (model.py: None). */
static int streakLevel(int n) {
for (int k = 0; k < STREAK_LEVELS.length; k++) if (n == STREAK_LEVELS[k]) return k;
int top = STREAK_LEVELS[STREAK_LEVELS.length - 1];
if (n > top && (n - top) % STREAK_EVERY == 0) return STREAK_LEVELS.length - 1;
return -1;
}
/** day_marks' items half: {item id: S_DONE | S_MISS | S_OPEN}; suggestions and absent items are left out. */
static Map<String, String> dayMarks(JSONObject day, String today) {
boolean past = day.optString("date").compareTo(today) < 0;
Map<String, String> items = new HashMap<>();
JSONArray blocks = day.optJSONArray("blocks");
for (int i = 0; blocks != null && i < blocks.length(); i++) {
JSONObject b = blocks.optJSONObject(i);
JSONArray its = b == null ? null : b.optJSONArray("items");
for (int k = 0; its != null && k < its.length(); k++) {
JSONObject it = its.optJSONObject(k);
if (it == null || it.optBoolean("hint", false)) continue;
String s = state(day, it.optString("id"));
items.put(it.optString("id"), DONE.equals(s) ? S_DONE : past || SKIPPED.equals(s) ? S_MISS : S_OPEN);
}
}
return items;
}
/** model.Run: one streak; length = its done days (its number). */
static final class Run {
String start, end;
int length;
final java.util.List<String> cheats = new java.util.ArrayList<>();
Run(String start) {
this.start = start;
this.end = start;
}
}
/** model.Streak: one item's record, fed its marks day by day in date order. */
static final class Streak {
final String key;
final int cheatAfter;
final Map<String, String> status = new HashMap<>();
private Run run; // the run going on (null: none)
private int since; // done days since the run began or the last cheat day
private boolean held; // a cheat day earned and not used yet
private String cheat; // the date of a cheat day not yet followed by a done day
Streak(String key, int cheatAfter) {
this.key = key;
this.cheatAfter = cheatAfter > 0 ? cheatAfter : 0;
}
void feed(String date, String mark) {
if (S_OPEN.equals(mark)) {
status.put(date, S_OPEN);
} else if (S_DONE.equals(mark)) {
if (run == null) {
run = new Run(date);
since = 0;
held = false;
}
cheat = null; // a cheat day followed by a done day: a rescue
run.length += 1;
run.end = date;
status.put(date, S_DONE);
since += 1;
if (cheatAfter > 0 && !held && since >= cheatAfter) held = true;
} else { // a miss
if (run != null && cheat != null) { // two misses running: no rescue after all
status.put(cheat, S_MISS);
run.cheats.remove(cheat);
cheat = null;
run = null;
status.put(date, S_MISS);
} else if (run != null && held) { // forgiven: the run goes on
held = false;
since = 0;
cheat = date;
run.cheats.add(date);
status.put(date, S_CHEAT);
} else {
run = null;
status.put(date, S_MISS);
}
}
}
/** The streak alive after the last day fed, else 0. */
int current() {
return run != null ? run.length : 0;
}
/** model.Streak.seed: start from base() = [length, since, held, cheat] as after asof (null: no run). */
void seed(JSONArray state, String asof) {
if (state == null || state.length() < 4 || state.optInt(0) <= 0) return;
run = new Run(asof);
run.length = state.optInt(0);
since = state.optInt(1);
held = state.optInt(2) != 0;
if (state.optInt(3) != 0) {
cheat = asof;
run.cheats.add(asof);
}
}
}
/** model.streak_ending: the streak itemId reaches if date is done, counting date and the days before
* it (date taken as today); 0 if it isn't done. base: a streak_base, used when date is after its asof
* (only the days after asof are read, and its cheat_after counts). days: any order. */
static int streakEnding(java.util.Collection<JSONObject> days, String itemId, String date, int cheatAfter,
JSONObject base) {
Streak st = new Streak(itemId, cheatAfter);
String after = "";
if (base != null && date.compareTo(base.optString("asof", "")) > 0) {
after = base.optString("asof");
st = new Streak(itemId, base.optInt("cheat_after", cheatAfter));
JSONObject items = base.optJSONObject("items");
st.seed(items == null ? null : items.optJSONArray(itemId), after);
}
java.util.TreeMap<String, JSONObject> sorted = new java.util.TreeMap<>();
for (JSONObject d : days) {
String dd = d.optString("date");
if (dd.compareTo(after) > 0 && dd.compareTo(date) <= 0) sorted.put(dd, d);
}
for (Map.Entry<String, JSONObject> e : sorted.entrySet()) {
String m = dayMarks(e.getValue(), date).get(itemId);
if (m != null) st.feed(e.getKey(), m);
}
return S_DONE.equals(st.status.get(date)) ? st.current() : 0;
}
/** Same content, whatever the key order. */
static boolean same(JSONObject a, JSONObject b) {
if (a == null || b == null) return a == b;
return canon(a).equals(canon(b));
}
private static String canon(Object o) {
if (o instanceof JSONObject) {
JSONObject j = (JSONObject) o;
java.util.TreeSet<String> keys = new java.util.TreeSet<>();
Iterator<String> it = j.keys();
while (it.hasNext()) keys.add(it.next());
StringBuilder sb = new StringBuilder("{");
for (String k : keys) sb.append(JSONObject.quote(k)).append(':').append(canon(j.opt(k))).append(',');
return sb.append('}').toString();
}
if (o instanceof JSONArray) {
JSONArray a = (JSONArray) o;
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < a.length(); i++) sb.append(canon(a.opt(i))).append(',');
return sb.append(']').toString();
}
if (o instanceof String) return JSONObject.quote((String) o);
if (o instanceof Number) return Long.toString(((Number) o).longValue());
return String.valueOf(o);
}
}
@@ -0,0 +1,171 @@
package me.teafry.routine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* The phone's copy of the days: files/days/YYYY-MM-DD.json, plus files/sync.json
* ({"seq": n, "dirty": [dates]}). The desktop holds the full history; this keeps KEEP_DAYS.
* files/streaks.json: the desktop's streak base as the sync server last gave it (see Streaks).
*/
final class Store {
static final int KEEP_DAYS = 90;
private final File dir, syncFile;
private JSONObject sync;
private final Map<String, JSONObject> cache = new HashMap<>(); // parsed days, for counting streaks
Store(File filesDir) {
dir = new File(filesDir, "days");
dir.mkdirs();
syncFile = new File(filesDir, "sync.json");
try {
sync = new JSONObject(read(syncFile));
} catch (IOException | JSONException e) {
sync = new JSONObject();
}
prune();
}
static String read(File f) throws IOException {
byte[] b = new byte[(int) f.length()];
try (FileInputStream in = new FileInputStream(f)) {
int n = 0;
while (n < b.length) {
int r = in.read(b, n, b.length - n);
if (r < 0) break;
n += r;
}
}
return new String(b, StandardCharsets.UTF_8);
}
private static void write(File f, String s) throws IOException {
File tmp = new File(f.getPath() + ".tmp");
try (FileOutputStream out = new FileOutputStream(tmp)) {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.getFD().sync();
}
if (!tmp.renameTo(f)) throw new IOException("rename " + f);
}
JSONObject get(String date) {
try {
return new JSONObject(read(new File(dir, date + ".json")));
} catch (IOException | JSONException e) {
return null;
}
}
void put(JSONObject day, boolean dirty) {
try {
String date = day.getString("date");
cache.remove(date);
write(new File(dir, date + ".json"), day.toString());
if (dirty) setDirty(date, true);
} catch (IOException | JSONException e) {
android.util.Log.w("routine", "can't save day", e);
}
}
/** Every day held, date -> record, read once and kept until put() changes it. Read only: don't edit. */
Map<String, JSONObject> all() {
Map<String, JSONObject> out = new HashMap<>();
for (String d : dates()) {
JSONObject o = cache.get(d);
if (o == null && (o = get(d)) != null) cache.put(d, o);
if (o != null) out.put(d, o);
}
return out;
}
/** The desktop's streak base (model.streak_base + "t", "anims"), or null before the server has sent one. */
JSONObject streakBase() {
try {
return new JSONObject(read(new File(syncFile.getParentFile(), "streaks.json")));
} catch (IOException | JSONException e) {
return null;
}
}
void saveStreakBase(JSONObject base) {
try {
write(new File(syncFile.getParentFile(), "streaks.json"), base.toString());
} catch (IOException e) {
android.util.Log.w("routine", "can't save streaks", e);
}
}
List<String> dates() {
List<String> out = new ArrayList<>();
String[] names = dir.list();
if (names != null) for (String n : names) if (n.endsWith(".json")) out.add(n.substring(0, n.length() - 5));
Collections.sort(out);
return out;
}
List<String> dirty() {
List<String> out = new ArrayList<>();
JSONArray a = sync.optJSONArray("dirty");
if (a != null) for (int i = 0; i < a.length(); i++) out.add(a.optString(i));
return out;
}
void setDirty(String date, boolean on) {
List<String> d = dirty();
d.remove(date);
if (on) d.add(date);
try {
sync.put("dirty", new JSONArray(d));
} catch (JSONException ignored) {
}
saveSync();
}
void saveSchedule(JSONObject sch) {
try {
write(new File(syncFile.getParentFile(), "schedule.json"), sch.toString());
} catch (IOException e) {
android.util.Log.w("routine", "can't save schedule", e);
}
}
long seq() {
return sync.optLong("seq", 0);
}
void setSeq(long s) {
try {
sync.put("seq", s);
} catch (JSONException ignored) {
}
saveSync();
}
private void saveSync() {
try {
write(syncFile, sync.toString());
} catch (IOException e) {
android.util.Log.w("routine", "can't save sync state", e);
}
}
private void prune() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -KEEP_DAYS);
String cutoff = Model.fmt(c);
for (String d : dates()) if (d.compareTo(cutoff) < 0 && !dirty().contains(d)) new File(dir, d + ".json").delete();
}
}
@@ -0,0 +1,79 @@
package me.teafry.routine;
import java.util.Calendar;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
/**
* The streak a tick on the R1 reaches, from the days the R1 holds (the sync server relays only its last 60;
* Store keeps 90) and the desktop's streak base (model.streak_base, sent through the server and kept in
* files/streaks.json): the R1's own copy of what the desktop's app.streak_of works out.
*
* With a base whose asof is before the day ticked, and the R1 holding the day after asof (or an
* earlier one): carry on from the base over the days after asof. That is the desktop's number.
* Otherwise (no base yet, the server is an old one, the base is too old, or the tick is on a day
* before asof): count over the R1's own days, and trust the number only once two misses running
* (one when cheat days are off) have ended whatever came before them; a streak that may reach
* back past the oldest day held gives 0, so no streak animation, never a wrong number.
* A date missing in between counts as the routine's day with nothing ticked, as on the desktop
* (its Store fills in every day).
*
* Pure (org.json only), so android/test can run it on the JDK against model.py.
*/
final class Streaks {
private Streaks() {}
static String next(String date) {
Calendar c = Model.parse(date);
c.add(Calendar.DAY_OF_MONTH, 1);
return Model.fmt(c);
}
/** days: date -> the R1's copy of that day (the one being ticked, as edited, among them).
* schedule: the routine, for missing dates. cheatAfter: used when the base isn't. */
static int ending(Map<String, JSONObject> days, JSONObject schedule, String itemId, String date,
int cheatAfter, JSONObject base) {
String first = null;
for (String d : days.keySet()) if (first == null || d.compareTo(first) < 0) first = d;
if (first == null || first.compareTo(date) > 0) return 0;
String asof = base == null ? null : base.optString("asof", "");
boolean useBase = asof != null && !asof.isEmpty() && date.compareTo(asof) > 0
&& first.compareTo(next(asof)) <= 0;
Model.Streak st;
String d;
boolean sure;
if (useBase) {
st = new Model.Streak(itemId, base.optInt("cheat_after", cheatAfter));
JSONObject items = base.optJSONObject("items");
st.seed(items == null ? null : items.optJSONArray(itemId), asof);
d = next(asof);
sure = true;
} else {
st = new Model.Streak(itemId, cheatAfter);
d = first;
sure = false;
}
int misses = 0, ends = st.cheatAfter > 0 ? 2 : 1;
for (int guard = 0; d.compareTo(date) <= 0 && guard < 4000; d = next(d), guard++) {
JSONObject day = days.get(d);
if (day == null) {
try {
day = Model.newDay(schedule, d);
} catch (JSONException | RuntimeException e) {
continue;
}
}
String m = Model.dayMarks(day, date).get(itemId);
if (m == null) continue;
st.feed(d, m);
if (Model.S_DONE.equals(m)) {
misses = 0;
} else if (Model.S_MISS.equals(m) && ++misses >= ends) {
sure = true; // whatever ran before is over: from here it's all in view
}
}
return sure && Model.S_DONE.equals(st.status.get(date)) ? st.current() : 0;
}
}
@@ -0,0 +1,144 @@
package me.teafry.routine;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
/**
* Holds the day's scroll; a sideways drag moves to another day (finger right = an earlier day).
* While dragging, the neighbouring day (a preview from Peek) rides in alongside, following
* the finger; let go past the threshold and both glide the rest of the way, then Go swaps
* in the real day under the preview, and the preview is dropped. Short of the threshold, or with
* no day that way, everything springs back.
*/
final class SwipeFrame extends FrameLayout {
interface Peek {
/** A preview of the day that way (-1 earlier, +1 later), or null when there isn't one. */
View peek(int dir);
}
interface Go {
/** Show the day that way for real; call done once it's on screen. */
void go(int dir, Runnable done);
}
private static final long GLIDE_MS = 170;
private final int slop, min;
private float x0, y0;
private boolean dragging, busy;
private int peekDir;
private View peek;
Peek peeker; // lambdas, not an anonymous class: rabbit.html#toolchain
Go goer;
SwipeFrame(Context c) {
super(c);
slop = ViewConfiguration.get(c).getScaledTouchSlop();
min = Ui.dp(c, 90);
}
private View page() {
return getChildAt(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (busy) return true;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
x0 = e.getX();
y0 = e.getY();
dragging = false;
break;
case MotionEvent.ACTION_MOVE:
float dx = e.getX() - x0, dy = e.getY() - y0;
if (Math.abs(dx) > slop * 2 && Math.abs(dx) > Math.abs(dy) * 2) {
dragging = true;
return true;
}
break;
default:
break;
}
return false;
}
/** The preview for the way the finger is going (made once per direction). */
private void ensurePeek(int dir) {
if (peekDir == dir) return;
dropPeek();
peekDir = dir;
peek = peeker == null ? null : peeker.peek(dir);
if (peek != null) addView(peek, new FrameLayout.LayoutParams(-1, -1));
}
private void dropPeek() {
if (peek != null) removeView(peek);
peek = null;
peekDir = 0;
}
private void place(float dx) {
int w = getWidth();
float t = peek == null ? dx / 3f : dx; // nothing that way: a little give, no more
page().setTranslationX(t);
if (peek != null) peek.setTranslationX(t + (peekDir < 0 ? -w : w));
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (busy) return true;
float dx = e.getX() - x0;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_MOVE:
if (dragging && dx != 0) {
ensurePeek(dx > 0 ? -1 : 1);
place(dx);
}
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
boolean go = dragging && peek != null && Math.abs(dx) > min
&& e.getActionMasked() == MotionEvent.ACTION_UP;
dragging = false;
if (go) finish();
else back();
return true;
default:
return true;
}
}
private void finish() {
busy = true;
final int dir = peekDir, w = getWidth();
page().animate().translationX(dir < 0 ? w : -w).setDuration(GLIDE_MS)
.setInterpolator(new DecelerateInterpolator()).start();
peek.animate().translationX(0).setDuration(GLIDE_MS).setInterpolator(new DecelerateInterpolator())
.withEndAction(() -> goer.go(dir, () -> {
page().setTranslationX(0);
dropPeek();
busy = false;
})).start();
}
private void back() {
if (page().getTranslationX() == 0 && peek == null) return;
busy = true;
final int w = getWidth(), dir = peekDir;
page().animate().translationX(0).setDuration(GLIDE_MS).setInterpolator(new DecelerateInterpolator())
.withEndAction(() -> {
dropPeek();
busy = false;
}).start();
if (peek != null) {
peek.animate().translationX(dir < 0 ? -w : w).setDuration(GLIDE_MS)
.setInterpolator(new DecelerateInterpolator()).start();
}
}
}
@@ -0,0 +1,60 @@
package me.teafry.routine;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import android.os.Handler;
import org.json.JSONObject;
/** One POST /sync on a worker thread; the answer comes back on the main thread. */
final class Sync {
interface Done {
void done(JSONObject result, String error);
}
private Sync() {}
static void post(String base, String token, String body, Handler main, Done cb) {
new Thread(() -> {
JSONObject res = null;
String err = null;
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(base.replaceAll("/+$", "") + "/sync").openConnection();
c.setConnectTimeout(8000);
c.setReadTimeout(20000);
c.setRequestMethod("POST");
c.setDoOutput(true);
c.setRequestProperty("Authorization", "Bearer " + token);
c.setRequestProperty("Content-Type", "application/json");
try (OutputStream o = c.getOutputStream()) {
o.write(body.getBytes(StandardCharsets.UTF_8));
}
int code = c.getResponseCode();
if (code != 200) {
err = "the server said " + code + (code == 401 ? " (token?)" : "");
} else {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
try (InputStream in = c.getInputStream()) {
byte[] b = new byte[8192];
int n;
while ((n = in.read(b)) > 0) buf.write(b, 0, n);
}
res = new JSONObject(buf.toString("UTF-8"));
}
} catch (Exception e) {
err = "can't reach the sync server";
} finally {
if (c != null) c.disconnect();
}
final JSONObject fr = res;
final String fe = err;
main.post(() -> cb.done(fr, fe));
}, "routine-sync").start();
}
}
@@ -0,0 +1,83 @@
package me.teafry.routine;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
/**
* A button face in the light look, after shared-resources design.html: embossed (#emboss: rims
* lighter/darker(116) over 8 %, face 103, outline darker(135)), sunk at darker(125) while held
* (#states), chosen = sunk at darker(112) (#toggles). Tiles (#tiles) touch: corners square where
* they meet, and each later tile overlaps the one before by the outline, so they share one line.
*/
final class TileDrawable extends Drawable {
private final int face;
private final boolean sunk;
private final float[] radii;
private final float line;
private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path path = new Path();
private final RectF r = new RectF();
TileDrawable(int face, boolean sunk, float[] radii, float line) {
this.face = face;
this.sunk = sunk;
this.radii = radii;
this.line = line;
}
/** radius on the outer corners only: first/last say which ends are rounded. */
static float[] corners(float rad, boolean first, boolean last) {
float a = first ? rad : 0, b = last ? rad : 0;
return new float[] {a, a, b, b, b, b, a, a};
}
/** The button: idle, and sunk while pressed. chosen = a pick-one tile that's picked. */
static Drawable button(float[] radii, float line, boolean chosen) {
int f = chosen ? BoxView.darker(Ui.BUTTON, 112) : Ui.BUTTON;
StateListDrawable s = new StateListDrawable();
s.addState(new int[] {android.R.attr.state_pressed},
new TileDrawable(BoxView.darker(Ui.BUTTON, 125), true, radii, line));
s.addState(new int[] {}, new TileDrawable(f, chosen, radii, line));
return s;
}
@Override
public void draw(Canvas c) {
r.set(getBounds());
r.inset(line / 2, line / 2);
path.reset();
path.addRoundRect(r, radii, Path.Direction.CW);
int top = sunk ? BoxView.darker(face, 116) : BoxView.lighter(face, 116);
int bot = sunk ? BoxView.lighter(face, 116) : BoxView.darker(face, 116);
int ftop = sunk ? BoxView.darker(face, 103) : BoxView.lighter(face, 103);
int fbot = sunk ? BoxView.lighter(face, 103) : BoxView.darker(face, 103);
p.setStyle(Paint.Style.FILL);
p.setShader(new LinearGradient(0, r.top, 0, r.bottom, new int[] {top, ftop, face, face, fbot, bot},
new float[] {0f, 0.08f, 0.3f, 0.7f, 0.92f, 1f}, Shader.TileMode.CLAMP));
c.drawPath(path, p);
p.setShader(null);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(line);
p.setColor(BoxView.darker(face, 135));
c.drawPath(path, p);
}
@Override
public void setAlpha(int a) {}
@Override
public void setColorFilter(ColorFilter cf) {}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
@@ -0,0 +1,53 @@
package me.teafry.routine;
import android.content.Context;
/**
* Every size and colour in one place, sizes already doubled for the R1 (rabbit.html#dp).
* Two looks: dark (white on black, the default: best in bright sunlight) and light (the
* desktop's: its grays, embossed boxes, block colours, the Edition date). setLight picks one;
* the colours below FG are set by it.
*/
final class Ui {
static final float TEXT_SMALL = 22, TEXT_BODY = 28, TEXT_BIG = 32, TEXT_SUB = 25;
static final int ROW_MIN = 88, BAR = 76, BOX = 52, INDENT = 40, ANIM_UNIT = 44;
static final int WHITE = 0xFFFFFFFF, BLACK = 0xFF000000, HIGHLIGHT = 0xFF3584E4, SUN = 0xFFFFC400;
static boolean light;
static int FG, BG, TASKS, BAR_BG, GRAY, DIM, NOTE_BG, NOTE_EDGE, BUTTON;
static {
setLight(false);
}
static void setLight(boolean on) {
light = on;
if (on) { // shared-resources design.html#colors light defaults
FG = BLACK;
BG = 0xFFEFEFEF; // 239: header and footer
TASKS = 0xFFF7F7F7; // 247: the tasks area, a little lighter
BAR_BG = 0xFFEFEFEF;
GRAY = 0xFF808080;
DIM = 0xFFA8A8A8;
NOTE_BG = WHITE;
NOTE_EDGE = 0xFFBDBDBD;
BUTTON = 0xFFF7F7F7; // 247
} else {
FG = WHITE;
BG = BLACK;
TASKS = BLACK;
BAR_BG = 0xFF111111;
GRAY = 0xFF8A8A8A;
DIM = 0xFF3A3A3A;
NOTE_BG = 0xFF161616;
NOTE_EDGE = DIM;
BUTTON = BLACK;
}
}
private Ui() {}
static int dp(Context c, float v) {
return Math.round(v * c.getResources().getDisplayMetrics().density);
}
}
@@ -0,0 +1,8 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp" android:height="108dp" android:viewportWidth="128" android:viewportHeight="128">
<path android:fillColor="#FFFFFF" android:pathData="M32,8h64a24,24 0 0 1 24,24v64a24,24 0 0 1 -24,24h-64a24,24 0 0 1 -24,-24v-64a24,24 0 0 1 24,-24z"/>
<path android:strokeColor="#000000" android:strokeWidth="5" android:pathData="M38,56h26a8,8 0 0 1 8,8v26a8,8 0 0 1 -8,8h-26a8,8 0 0 1 -8,-8v-26a8,8 0 0 1 8,-8z"/>
<path android:strokeColor="#3584E4" android:strokeWidth="7" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M39,77l9,9l16,-20"/>
<path android:strokeColor="#E8202A" android:strokeWidth="6" android:strokeLineCap="round" android:pathData="M80,48L94,34M66,40L68,22M88,62L106,60"/>
<path android:fillColor="#FFC400" android:pathData="M100,24m-6,0a6,6 0 1 1 12,0a6,6 0 1 1 -12,0"/>
</vector>
@@ -0,0 +1,123 @@
package me.teafry.routine;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Runs the R1's pure streak / number / merge code on the JDK, for tests/test_r1.py (which compares
* the answers with routine/model.py and anim_paint.py). Reads a JSON file of cases, prints answers:
*
* in: {"ending": [{"days", "schedule", "item", "date", "cheat", "base"?}], "model": [same, the
* whole history], "digits": [[n, cx, cy, h, rot]], "merge": [[a, b]], "levels": [n, ...],
* "caption": [[n, cx, top, h, scale]], "place": [[x0, y0, x1, y1, n, above (0/1), h]],
* "captionh": [tallest n h], "pop": [[frame, start]],
* "start": [[first n frame, frames]]}
* out: {"ending": [Streaks.ending], "model": [Model.streakEnding], "digits": [strokes],
* "merge": [Model.merge], "levels": [Model.streakLevel], "caption": [strokes],
* "place": [Digits.captionPlace], "captionh": [Digits.captionH], "pop": [Digits.captionScale],
* "start": [Digits.captionStart]}
*/
public final class R1Check {
private R1Check() {}
public static void main(String[] args) throws Exception {
JSONObject in = new JSONObject(new String(Files.readAllBytes(Paths.get(args[0])), StandardCharsets.UTF_8));
JSONObject out = new JSONObject();
JSONArray r = new JSONArray();
JSONArray cases = in.optJSONArray("ending");
for (int i = 0; cases != null && i < cases.length(); i++) {
JSONObject c = cases.getJSONObject(i);
Map<String, JSONObject> days = new HashMap<>();
JSONArray ds = c.getJSONArray("days");
for (int k = 0; k < ds.length(); k++) days.put(ds.getJSONObject(k).getString("date"), ds.getJSONObject(k));
r.put(Streaks.ending(days, c.getJSONObject("schedule"), c.getString("item"), c.getString("date"),
c.optInt("cheat", Model.CHEAT_AFTER), c.optJSONObject("base")));
}
out.put("ending", r);
r = new JSONArray();
cases = in.optJSONArray("model");
for (int i = 0; cases != null && i < cases.length(); i++) {
JSONObject c = cases.getJSONObject(i);
List<JSONObject> days = new ArrayList<>();
JSONArray ds = c.getJSONArray("days");
for (int k = 0; k < ds.length(); k++) days.add(ds.getJSONObject(k));
r.put(Model.streakEnding(days, c.getString("item"), c.getString("date"),
c.optInt("cheat", Model.CHEAT_AFTER), c.optJSONObject("base")));
}
out.put("model", r);
r = new JSONArray();
JSONArray dg = in.optJSONArray("digits");
for (int i = 0; dg != null && i < dg.length(); i++) {
JSONArray a = dg.optJSONArray(i);
JSONArray strokes = new JSONArray();
for (float[] st : Digits.strokes(a.getInt(0), a.getDouble(1), a.getDouble(2), a.getDouble(3), a.getDouble(4))) {
JSONArray pts = new JSONArray();
for (float v : st) pts.put((double) v);
strokes.put(pts);
}
r.put(strokes);
}
out.put("digits", r);
r = new JSONArray();
JSONArray mg = in.optJSONArray("merge");
for (int i = 0; mg != null && i < mg.length(); i++) {
JSONArray ab = mg.optJSONArray(i);
r.put(Model.merge(ab.optJSONObject(0), ab.optJSONObject(1)));
}
out.put("merge", r);
r = new JSONArray();
JSONArray lv = in.optJSONArray("levels");
for (int i = 0; lv != null && i < lv.length(); i++) r.put(Model.streakLevel(lv.optInt(i)));
out.put("levels", r);
r = new JSONArray();
JSONArray cp = in.optJSONArray("caption");
for (int i = 0; cp != null && i < cp.length(); i++) {
JSONArray a = cp.optJSONArray(i);
r.put(strokes(Digits.captionStrokes(a.getInt(0), a.getDouble(1), a.getDouble(2), a.getDouble(3), a.getDouble(4))));
}
out.put("caption", r);
r = new JSONArray();
JSONArray pl = in.optJSONArray("place");
for (int i = 0; pl != null && i < pl.length(); i++) {
JSONArray a = pl.optJSONArray(i);
float[] b = {(float) a.getDouble(0), (float) a.getDouble(1), (float) a.getDouble(2), (float) a.getDouble(3)};
JSONArray res = new JSONArray();
for (float v : Digits.captionPlace(b, a.getInt(4), a.getInt(5) != 0, a.getDouble(6))) res.put((double) v);
r.put(res);
}
out.put("place", r);
r = new JSONArray();
JSONArray chs = in.optJSONArray("captionh");
for (int i = 0; chs != null && i < chs.length(); i++) r.put(Digits.captionH(chs.getDouble(i)));
out.put("captionh", r);
r = new JSONArray();
JSONArray pop = in.optJSONArray("pop");
for (int i = 0; pop != null && i < pop.length(); i++)
r.put(Digits.captionScale(pop.optJSONArray(i).optInt(0), pop.optJSONArray(i).optInt(1)));
out.put("pop", r);
r = new JSONArray();
JSONArray sts = in.optJSONArray("start");
for (int i = 0; sts != null && i < sts.length(); i++)
r.put(Digits.captionStart(sts.optJSONArray(i).optInt(0), sts.optJSONArray(i).optInt(1)));
out.put("start", r);
System.out.println(out);
}
private static JSONArray strokes(float[][] all) {
JSONArray strokes = new JSONArray();
for (float[] st : all) {
JSONArray pts = new JSONArray();
for (float v : st) pts.put((double) v);
strokes.put(pts);
}
return strokes;
}
}
@@ -0,0 +1,108 @@
package org.json;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** Test-only stand-in for Android's org.json.JSONArray (see JSONException). */
public class JSONArray {
final List<Object> list = new ArrayList<>();
public JSONArray() {}
public JSONArray(Collection<?> c) {
list.addAll(c);
}
public JSONArray(String s) throws JSONException {
Object o = new JSONObject.Parser(s).value();
if (!(o instanceof JSONArray)) throw new JSONException("not an array");
list.addAll(((JSONArray) o).list);
}
public int length() {
return list.size();
}
public Object opt(int i) {
return i >= 0 && i < list.size() ? list.get(i) : null;
}
public JSONArray put(Object v) {
list.add(v);
return this;
}
public JSONArray put(int v) {
list.add((long) v);
return this;
}
public JSONArray put(long v) {
list.add(v);
return this;
}
public JSONArray put(double v) {
list.add(v);
return this;
}
public JSONObject optJSONObject(int i) {
Object o = opt(i);
return o instanceof JSONObject ? (JSONObject) o : null;
}
public JSONArray optJSONArray(int i) {
Object o = opt(i);
return o instanceof JSONArray ? (JSONArray) o : null;
}
public JSONObject getJSONObject(int i) throws JSONException {
JSONObject o = optJSONObject(i);
if (o == null) throw new JSONException("no object at " + i);
return o;
}
public int optInt(int i) {
return optInt(i, 0);
}
public int optInt(int i, int d) {
Object o = opt(i);
return o instanceof Number ? ((Number) o).intValue() : d;
}
public int getInt(int i) throws JSONException {
Object o = opt(i);
if (!(o instanceof Number)) throw new JSONException("no int at " + i);
return ((Number) o).intValue();
}
public double getDouble(int i) throws JSONException {
Object o = opt(i);
if (!(o instanceof Number)) throw new JSONException("no number at " + i);
return ((Number) o).doubleValue();
}
public String getString(int i) throws JSONException {
Object o = opt(i);
if (o == null) throw new JSONException("no value at " + i);
return o.toString();
}
public String optString(int i) {
Object o = opt(i);
return o == null ? "" : o.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(',');
sb.append(JSONObject.write(list.get(i)));
}
return sb.append(']').toString();
}
}
@@ -0,0 +1,8 @@
package org.json;
/** Test-only stand-in for Android's org.json (android.jar has only stubs): just what the app's pure classes use. */
public class JSONException extends Exception {
public JSONException(String m) {
super(m);
}
}
@@ -0,0 +1,249 @@
package org.json;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/** Test-only stand-in for Android's org.json.JSONObject (see JSONException). */
public class JSONObject {
final Map<String, Object> map = new LinkedHashMap<>();
public static final Object NULL = new Object() {
@Override
public String toString() {
return "null";
}
};
public JSONObject() {}
public JSONObject(String s) throws JSONException {
Object o = new Parser(s).value();
if (!(o instanceof JSONObject)) throw new JSONException("not an object");
map.putAll(((JSONObject) o).map);
}
public boolean has(String k) {
return map.containsKey(k);
}
public Object opt(String k) {
return map.get(k);
}
public Iterator<String> keys() {
return map.keySet().iterator();
}
public JSONObject put(String k, Object v) {
if (v == null) map.remove(k);
else map.put(k, v instanceof Integer ? (Object) (long) (Integer) v : v);
return this;
}
public JSONObject put(String k, int v) {
map.put(k, (long) v);
return this;
}
public JSONObject put(String k, long v) {
map.put(k, v);
return this;
}
public JSONObject put(String k, boolean v) {
map.put(k, v);
return this;
}
public JSONObject put(String k, double v) {
map.put(k, v);
return this;
}
public JSONObject optJSONObject(String k) {
Object o = map.get(k);
return o instanceof JSONObject ? (JSONObject) o : null;
}
public JSONArray optJSONArray(String k) {
Object o = map.get(k);
return o instanceof JSONArray ? (JSONArray) o : null;
}
public JSONObject getJSONObject(String k) throws JSONException {
JSONObject o = optJSONObject(k);
if (o == null) throw new JSONException("no object " + k);
return o;
}
public JSONArray getJSONArray(String k) throws JSONException {
JSONArray o = optJSONArray(k);
if (o == null) throw new JSONException("no array " + k);
return o;
}
public String getString(String k) throws JSONException {
Object o = map.get(k);
if (o == null || o == NULL) throw new JSONException("no string " + k);
return o.toString();
}
public int getInt(String k) throws JSONException {
Object o = map.get(k);
if (!(o instanceof Number)) throw new JSONException("no int " + k);
return ((Number) o).intValue();
}
public String optString(String k) {
return optString(k, "");
}
public String optString(String k, String d) {
Object o = map.get(k);
return o == null || o == NULL ? d : o.toString();
}
public int optInt(String k) {
return optInt(k, 0);
}
public int optInt(String k, int d) {
Object o = map.get(k);
return o instanceof Number ? ((Number) o).intValue() : d;
}
public long optLong(String k) {
return optLong(k, 0);
}
public long optLong(String k, long d) {
Object o = map.get(k);
return o instanceof Number ? ((Number) o).longValue() : d;
}
public boolean optBoolean(String k, boolean d) {
Object o = map.get(k);
return o instanceof Boolean ? (Boolean) o : d;
}
public static String quote(String s) {
StringBuilder sb = new StringBuilder("\"");
for (char c : s.toCharArray()) {
if (c == '"' || c == '\\') sb.append('\\').append(c);
else if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
return sb.append('"').toString();
}
static String write(Object o) {
if (o instanceof String) return quote((String) o);
if (o instanceof Double) {
double d = (Double) o;
return d == Math.rint(d) && Math.abs(d) < 1e15 ? Long.toString((long) d) : Double.toString(d);
}
return String.valueOf(o);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<String, Object> e : map.entrySet()) {
if (!first) sb.append(',');
first = false;
sb.append(quote(e.getKey())).append(':').append(write(e.getValue()));
}
return sb.append('}').toString();
}
static final class Parser {
final String s;
int i;
Parser(String s) {
this.s = s;
}
void ws() {
while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
}
Object value() throws JSONException {
ws();
if (i >= s.length()) throw new JSONException("end of input");
char c = s.charAt(i);
if (c == '{') {
i++;
JSONObject o = new JSONObject();
ws();
if (s.charAt(i) == '}') {
i++;
return o;
}
while (true) {
ws();
String k = (String) value();
ws();
i++; // :
o.map.put(k, value());
ws();
if (s.charAt(i++) == '}') return o;
}
}
if (c == '[') {
i++;
JSONArray a = new JSONArray();
ws();
if (s.charAt(i) == ']') {
i++;
return a;
}
while (true) {
a.list.add(value());
ws();
if (s.charAt(i++) == ']') return a;
}
}
if (c == '"') {
StringBuilder sb = new StringBuilder();
i++;
while (s.charAt(i) != '"') {
char ch = s.charAt(i++);
if (ch == '\\') {
char e = s.charAt(i++);
if (e == 'u') {
sb.append((char) Integer.parseInt(s.substring(i, i + 4), 16));
i += 4;
} else {
sb.append(e == 'n' ? '\n' : e == 't' ? '\t' : e == 'r' ? '\r' : e == 'b' ? '\b'
: e == 'f' ? '\f' : e);
}
} else {
sb.append(ch);
}
}
i++;
return sb.toString();
}
if (s.startsWith("true", i)) {
i += 4;
return Boolean.TRUE;
}
if (s.startsWith("false", i)) {
i += 5;
return Boolean.FALSE;
}
if (s.startsWith("null", i)) {
i += 4;
return NULL;
}
int st = i;
while (i < s.length() && "+-0123456789.eE".indexOf(s.charAt(i)) >= 0) i++;
String num = s.substring(st, i);
if (num.isEmpty()) throw new JSONException("bad json at " + st);
if (num.contains(".") || num.contains("e") || num.contains("E")) return Double.parseDouble(num);
return Long.parseLong(num);
}
}
}
+82
View File
@@ -0,0 +1,82 @@
# Building Routine.dmg on a Mac (once, for everyone)
`install-mac.sh` is the way to install Routine on a Mac today: one line in Terminal. A `.dmg` you
open and drag to Applications is friendlier, but it has to be built on a Mac, and nobody has run
the build yet. If you have a Mac, this is how to build it once and send it back, so it can be put
up for download. **Untested so far**: if any step fails, send the whole Terminal output.
## What you need
- macOS 13 (Ventura) or newer. The app you build runs on the same kind of Mac as yours: on an
Apple-silicon Mac (M1 and later) you build the Apple-silicon version; on an Intel Mac, the
Intel one. (Both are welcome.)
- About 2 GB of free space and an internet connection. No Xcode, Homebrew or admin password.
## Build it
In Terminal (⌘ Space, type `Terminal`):
```
cd ~/Downloads
curl -fsSL https://git.autonomic.zone/trav/routine/archive/main.tar.gz | tar -xzf -
cd routine
scripts/build-mac-app.sh
```
It downloads uv, a Python and the packages into `build/mac/` (nothing outside this folder),
freezes the app with PyInstaller, signs it ad hoc and makes the disk image. At the end it prints
```
Done: …/routine/dist/Routine-<version>.dmg (… MB), for arm64 Macs.
```
## Check it, then send it
1. Open `dist/Routine-<version>.dmg`: a window shows **Routine** and an **Applications** folder.
2. Drag Routine onto Applications, eject the disk image, open Routine from Launchpad.
3. Walk through `docs/mac-testing.md` from step 2 (skip step 1's install line, and in step 9
remove it by dragging Routine from Applications to the Bin).
4. Send `dist/Routine-<version>.dmg` (it's too big for most email: a file-sharing link is fine),
with the last lines the build printed and your macOS version and chip.
To start over: delete `build/` and `dist/` and run the script again.
## What people see when they open it: Gatekeeper
The app is signed "ad hoc" (`codesign -s -`), not with an Apple Developer ID, and it isn't
notarized by Apple (that needs a paid developer account). So the first time someone opens a copy
they **downloaded**, macOS stops it. It only happens once per copy.
**macOS 15 Sequoia and newer**:
1. Double-clicking says **"Routine" Not Opened: Apple could not verify "Routine" is free of malware
that may harm your Mac or compromise your privacy.** Click **Done** (not Move to Bin).
2. Open **System Settings → Privacy & Security**, scroll down to **Security**: it says
*"Routine" was blocked to protect your Mac.* Click **Open Anyway**, then enter your password.
3. Open Routine again and click **Open Anyway** in the box that appears. From then on it opens
normally.
**macOS 13 Ventura and 14 Sonoma**: right-click (or Control-click) Routine in Applications →
**Open**, then **Open** in the box that appears. (Or the System Settings route above.)
**In Terminal, any version** (for people comfortable with it): after dragging it to Applications,
```
xattr -dr com.apple.quarantine /Applications/Routine.app
```
and it opens without the warning.
The one-line installer (`install-mac.sh`) doesn't hit any of this: it builds the app on the Mac
itself, and nothing it downloads is marked as "from the internet".
## Notes for whoever maintains this
- The script pins uv, Python 3.13, PySide6-Essentials and PyInstaller (`scripts/build-mac-app.sh`).
PySide6-Essentials has no Qt Multimedia, so sounds play through macOS's own `afplay`.
- The data the app keeps is outside the bundle (`~/Library/Application Support/Routine`), so the
.dmg app and the installer's app can replace each other freely.
- Real signing + notarization later: a Developer ID certificate in place of `-`, then
`xcrun notarytool submit … --wait` and `xcrun stapler staple` on the .dmg.
- The freezing part was tried on Linux (`BUILD_TEST=1`: it builds and runs); the `.app`,
`plutil`, `codesign` and `hdiutil` steps have never run.
+106
View File
@@ -0,0 +1,106 @@
# Trying Routine on a Mac: a checklist
Thank you for trying it! Routine has never run on a real Mac before, so every answer helps, "it
worked" included. It takes about 20 minutes, most of it the download. Nothing here touches anything
else on your Mac, and step 9 removes it all again if you like.
You need macOS 13 (Ventura) or newer: Apple menu → About This Mac. Write down the macOS version and
whether it says "Chip: Apple M…" or "Processor: Intel…".
For each step, note **yes / no**, and for any "no", what you saw (a screenshot is perfect: ⇧⌘4,
then drag over it; it lands on the Desktop).
## 1. Install
1. Open **Terminal** (⌘ Space, type `Terminal`, Return).
2. Paste this line and press Return:
```
curl -fsSL https://git.autonomic.zone/trav/routine/raw/branch/main/install-mac.sh | bash
```
3. Wait until it says **Routine … is installed**. It downloads about 400 MB.
- [ ] It finished without an error. (If not: copy everything in the Terminal window, ⌘A then ⌘C,
and paste it into your message.)
- [ ] Did macOS ask you anything while it ran (a password, "allow access", a developer tools
install)? It shouldn't. If it did, what exactly?
## 2. Open it
1. Open **Launchpad** (or ⌘ Space, type `Routine`) and click **Routine**.
- [ ] It opened, the first time. (If macOS said it "can't be opened" or "can't be checked for
malicious software", say so, word for word.)
- [ ] The icon in Launchpad and in the Dock is a ticked box with a few sparks, not a blank page
or a rocket.
- [ ] The menu bar at the top of the screen says **Routine** next to the Apple, not "Python".
- [ ] Hover over its Dock icon: it says **Routine**.
- [ ] There's only one Routine icon in the Dock (not one Routine and one Python).
## 3. The window
- [ ] The window has the normal Mac title bar with the red / yellow / green buttons.
- [ ] You can move it by its title bar and resize it from its edges and corners.
- [ ] The date at the top is in a clean, geometric font (not Times or a typewriter font), and the
task names are easy to read.
- [ ] The word **notes** above the box at the bottom is handwritten-looking.
- [ ] Nothing looks blurry (text, boxes, the » button).
- [ ] Turn your Mac to Dark mode (System Settings → Appearance → Dark): Routine turns dark too
(maybe after reopening it). Back to Light afterwards if you like.
## 4. Ticking
1. Tick a few tasks.
- [ ] A little animation plays from the box, **with a sound**. (Volume up! Each tick has its own.)
- [ ] Tick 6 or more: still animations and sounds.
- [ ] Untick one in **All** (bottom left), and click **skip** on another: both work.
- [ ] Write something in the box at the bottom, click a task, quit Routine (⌘Q), open it again:
the note is still there.
## 5. Moving around
- [ ] Two-finger swipe sideways on the trackpad (or ‹ ›): earlier days. » brings you back to now.
- [ ] Scrolling up and down the list is smooth.
- [ ] Click a block's heading (e.g. **Morning**): its tasks hide; click again: back.
## 6. The menus and shortcuts
- [ ] **Routine** menu (top left, next to the Apple) has **About Routine**, **Settings…** (⌘,) and
**Quit Routine** (⌘Q). All three work.
- [ ] **View → History** (⌘Y), **Statistics** (⌘T) and **Journal** (⌘J) each open a window.
- [ ] ⌘H hides Routine (as in any Mac app).
- [ ] **Help → Open log folder** opens a Finder window (it may be empty: that's good).
## 7. History, Statistics, Journal
1. Open **View → History**.
- [ ] Pinch on the trackpad: it zooms in and out around your fingers. ⌘ + scroll does too.
- [ ] Hover a dot: a tip says which task and day.
- [ ] **Statistics** and **Journal** show your ticks and today's note.
## 8. Settings
1. Open Settings (⌘,).
- [ ] **Routine**: add a task to a block, **Save routine**: it shows up in the main window.
- [ ] **Appearance**: drag a gray slider: the window changes colour as you drag.
- [ ] **Data**: shows two paths under `…/Library/Application Support/Routine`.
- [ ] **Sync** and **Rabbit R1** say **Coming soon on macOS.** and are greyed out.
## 9. Update and remove (optional)
- [ ] Run the install line from step 1 again: it finishes, Routine opens with your ticks and
routine still there.
- [ ] To remove it: paste
`curl -fsSL https://git.autonomic.zone/trav/routine/raw/branch/main/install-mac.sh | bash -s -- --uninstall`.
Routine is gone from Applications. (Your ticks stay in
`~/Library/Application Support/Routine` unless you delete that folder.)
## Sending it back
Your yes / no list, the macOS version and chip, and any screenshots. If anything went wrong, also
the files in **Help → Open log folder** (`errors.log`, `crash.log`, `launch.log`): they hold only
where the program went wrong, never your tasks or notes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env bash
# Routine for Linux: install it, update it (run this again), or remove it (--uninstall).
#
# curl -fsSL https://git.autonomic.zone/trav/routine/raw/branch/main/install-linux.sh | bash
# curl -fsSL https://git.autonomic.zone/trav/routine/raw/branch/main/install-linux.sh | bash -s -- --uninstall
#
# Puts the app in ~/.local/share/routine-app (never touches your data in ~/.local/share/routine),
# Routine in the app grid (a .desktop file and the icon), and a launcher. It needs python3 (3.10+)
# and PySide6: a PySide6 (or PyQt6) your system already has is used as it is; otherwise it offers
# your distribution's package (it shows the sudo command and asks first: it never runs sudo on its
# own) or a private copy downloaded with pip into the app folder (no password needed, ~250 MB).
#
# Settings, all optional, for testing or unusual setups:
# ROUTINE_SOURCE=DIR|FILE.tar.gz install from a local checkout / archive instead of downloading
# ROUTINE_ARCHIVE=URL the archive to download (default: the main branch)
# ROUTINE_QT_INSTALL=system|venv|distro skip the question (no terminal: venv)
# ROUTINE_PYTHON=/path/to/python3 the Python to use
# XDG_DATA_HOME / HOME where it all goes, as usual
# ROUTINE_FORCE=1 replace a Routine entry in the app grid that this script didn't make
set -euo pipefail
REPO_URL="https://git.autonomic.zone/trav/routine"
ARCHIVE="${ROUTINE_ARCHIVE:-$REPO_URL/archive/main.tar.gz}"
PINS=(PySide6-Essentials==6.11.0)
APP_ID="me.teafry.routine"
MARK="X-Routine-Installer=install-linux.sh"
DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
STATE_HOME="${XDG_STATE_HOME:-$HOME/.local/state}"
APPDIR="$DATA_HOME/routine-app"
APPS="$DATA_HOME/applications"
HICOLOR="$DATA_HOME/icons/hicolor"
DESKTOP="$APPS/$APP_ID.desktop"
DATA_DIR="$DATA_HOME/routine"
say() { printf '%s\n' "$*"; }
die() { printf 'Routine installer: %s\n' "$*" >&2; exit 1; }
have_tty() { [ -t 0 ] || { [ -r /dev/tty ] && (: </dev/tty) 2>/dev/null; }; }
# ask "question" default → the answer (read from the terminal even when this script came through a pipe)
ask() {
local reply=""
if have_tty; then
printf '%s ' "$1" >/dev/tty
read -r reply </dev/tty || reply=""
fi
printf '%s' "${reply:-$2}"
}
uninstall() {
if [ -f "$DESKTOP" ] && grep -q "^$MARK" "$DESKTOP"; then
rm -f "$DESKTOP"
rm -f "$HICOLOR/scalable/apps/$APP_ID.svg"
for n in 48 64 128 256; do rm -f "$HICOLOR/${n}x${n}/apps/$APP_ID.png"; done
command -v update-desktop-database >/dev/null && update-desktop-database "$APPS" 2>/dev/null || true
elif [ -f "$DESKTOP" ]; then
say "Left $DESKTOP alone: this installer didn't make it."
fi
rm -rf "$APPDIR"
say "Routine is removed."
say "Your routine, history and settings are still there, in case you come back:"
say " $DATA_DIR and ${XDG_CONFIG_HOME:-$HOME/.config}/routine"
say "(or wherever Settings → Data put them). Delete those folders yourself if you want them gone."
}
case "${1:-}" in
--uninstall|uninstall) uninstall; exit 0 ;;
-h|--help) sed -n '2,22p' "${BASH_SOURCE[0]:-/dev/null}" 2>/dev/null || say "See the top of install-linux.sh."; exit 0 ;;
"") ;;
*) die "unknown option $1 (try --uninstall)" ;;
esac
[ "$(uname -s)" = Linux ] || die "this is the Linux installer; on a Mac use install-mac.sh"
command -v tar >/dev/null || die "needs tar"
# ── 1. Python 3.10 or newer ──
PY="${ROUTINE_PYTHON:-$(command -v python3 || true)}"
# shellcheck source=/dev/null
DISTRO=" $( (. /etc/os-release && printf '%s %s' "${ID:-}" "${ID_LIKE:-}") 2>/dev/null || true) "
pkg_cmd() { # the command that installs $1 (a word per distro) here, or nothing
case "$DISTRO" in
*" fedora "*|*" rhel "*) printf 'sudo dnf install %s' "$1" ;;
*" debian "*|*" ubuntu "*) printf 'sudo apt install %s' "$2" ;;
*" arch "*) printf 'sudo pacman -S --needed %s' "$3" ;;
*) ;;
esac
}
if [ -z "$PY" ] || ! "$PY" -c 'import sys; sys.exit(sys.version_info < (3, 10))' 2>/dev/null; then
c="$(pkg_cmd python3 python3 python)"
die "Routine needs Python 3.10 or newer. ${c:+Install it with: $c and run this again.}"
fi
# ── 2. The app itself ──
mkdir -p "$APPDIR"
NEW="$APPDIR/src.new"
rm -rf "$NEW"
mkdir -p "$NEW"
SRC="${ROUTINE_SOURCE:-}"
if [ -z "$SRC" ]; then # run from a checkout (not through a pipe)? install that
here="$(dirname "${BASH_SOURCE[0]:-/nonexistent}")"
[ -f "$here/routine/__init__.py" ] && SRC="$(cd "$here" && pwd)"
fi
if [ -n "$SRC" ] && [ -d "$SRC" ]; then
say "Copying Routine from $SRC …"
tar -C "$SRC" --exclude=.git --exclude=__pycache__ --exclude=android/build -cf - . | tar -C "$NEW" -xf -
elif [ -n "$SRC" ]; then
tar -C "$NEW" --strip-components=1 -xzf "$SRC"
else
command -v curl >/dev/null || die "needs curl (or set ROUTINE_SOURCE to a downloaded copy)"
say "Downloading Routine …"
curl -fsSL "$ARCHIVE" | tar -C "$NEW" --strip-components=1 -xzf - || die "couldn't download $ARCHIVE"
fi
[ -f "$NEW/routine/__init__.py" ] || die "that doesn't look like Routine (no routine/__init__.py)"
VERSION="$(sed -n 's/^__version__ = "\(.*\)"/\1/p' "$NEW/routine/__init__.py")"
rm -rf "$APPDIR/src.old"
[ -d "$APPDIR/src" ] && mv "$APPDIR/src" "$APPDIR/src.old"
mv "$NEW" "$APPDIR/src"
rm -rf "$APPDIR/src.old"
# ── 3. Qt: the system's, the distribution's package, or a private copy ──
qt_ok() { (cd "$APPDIR/src" && "$1" -c 'import routine.qt.QtWidgets' 2>/dev/null); }
APP_PY=""
CHOICE="${ROUTINE_QT_INSTALL:-}"
if [ -x "$APPDIR/venv/bin/python" ] && [ "$CHOICE" != system ] && [ "$CHOICE" != distro ]; then
CHOICE=venv # installed with a private copy before: keep it (and update it)
elif [ -z "$CHOICE" ] && qt_ok "$PY"; then
CHOICE=system
fi
if [ -z "$CHOICE" ]; then
DCMD="$(pkg_cmd python3-pyside6 'python3-pyside6.qtwidgets python3-pyside6.qtnetwork python3-pyside6.qtmultimedia' pyside6)"
case "$DISTRO" in # only offer a package that exists here
*" debian "*|*" ubuntu "*) apt-cache show python3-pyside6.qtwidgets >/dev/null 2>&1 || DCMD="" ;;
esac
say ""
say "Routine needs PySide6 (Qt for Python), and this Python doesn't have it."
if [ -n "$DCMD" ]; then
say " 1) install your system's package: $DCMD (asks for your password)"
say " 2) download a private copy for Routine only (~250 MB, no password)"
a="$(ask 'Which one? [1/2, default 2]' 2)"
[ "$a" = 1 ] && CHOICE=distro || CHOICE=venv
else
say "Downloading a private copy for Routine only (~250 MB, no password needed)."
CHOICE=venv
fi
fi
case "$CHOICE" in
system)
qt_ok "$PY" || die "ROUTINE_QT_INSTALL=system, but $PY can't import PySide6 or PyQt6"
APP_PY="$PY" ;;
distro)
DCMD="${DCMD:-$(pkg_cmd python3-pyside6 'python3-pyside6.qtwidgets python3-pyside6.qtnetwork python3-pyside6.qtmultimedia' pyside6)}"
[ -n "$DCMD" ] || die "no package known for this distribution: run again and pick the private copy"
say "This will run: $DCMD"
a="$(ask 'Go ahead? [y/N]' n)"
case "$a" in y|Y|yes) $DCMD ;; *) die "stopped; nothing was installed with sudo. Run again to choose." ;; esac
qt_ok "$PY" || die "PySide6 still isn't importable by $PY; run again and pick the private copy"
APP_PY="$PY" ;;
venv)
if [ ! -x "$APPDIR/venv/bin/python" ]; then
"$PY" -m venv "$APPDIR/venv" 2>/dev/null || {
rm -rf "$APPDIR/venv"
c="$(pkg_cmd python3-virtualenv python3-venv python-virtualenv)"
die "Python can't make a private environment here. ${c:+Install that with: $c and run this again.}"
}
fi
say "Installing ${PINS[*]} into $APPDIR/venv …"
"$APPDIR/venv/bin/python" -m pip install --quiet --no-cache-dir --disable-pip-version-check "${PINS[@]}" ||
die "pip couldn't install ${PINS[*]} (it needs glibc 2.34+, e.g. Fedora 35+, Ubuntu 22.04+, Debian 12+)"
APP_PY="$APPDIR/venv/bin/python" ;;
*) die "ROUTINE_QT_INSTALL must be system, distro or venv" ;;
esac
qt_ok "$APP_PY" || die "Qt for Python still won't import with $APP_PY"
# ── 4. The launcher, the icon, the app grid ──
LAUNCHER="$APPDIR/routine"
cat >"$LAUNCHER" <<EOF
#!/bin/sh
# Starts Routine (made by install-linux.sh; run that again to update). Messages from the last start
# go to $STATE_HOME/routine/launch.log; errors to errors.log beside it.
mkdir -p "$STATE_HOME/routine"
cd "$APPDIR/src" || exit 1
exec "$APP_PY" -m routine "\$@" 2>"$STATE_HOME/routine/launch.log"
EOF
chmod +x "$LAUNCHER"
mkdir -p "$APPS" "$HICOLOR/scalable/apps"
if [ -f "$DESKTOP" ] && ! grep -q "^$MARK" "$DESKTOP" && [ "${ROUTINE_FORCE:-}" != 1 ]; then
a="$(ask "There's already a Routine in the app grid ($DESKTOP), made some other way. Replace it? [y/N]" n)"
case "$a" in y|Y|yes) ;; *) say "Kept the existing app grid entry. Start this copy with: $LAUNCHER"; exit 0 ;; esac
fi
cp "$APPDIR/src/shared/icon.svg" "$HICOLOR/scalable/apps/$APP_ID.svg"
for n in 48 64 128 256; do # fixed sizes too, for whatever doesn't read SVG
mkdir -p "$HICOLOR/${n}x${n}/apps"
(cd "$APPDIR/src" && QT_QPA_PLATFORM=offscreen "$APP_PY" -c '
import sys
from routine.qt.QtGui import QGuiApplication, QIcon
a = QGuiApplication(sys.argv)
sys.exit(0 if QIcon(sys.argv[1]).pixmap(int(sys.argv[2]), int(sys.argv[2])).save(sys.argv[3]) else 1)' \
shared/icon.svg "$n" "$HICOLOR/${n}x${n}/apps/$APP_ID.png" 2>/dev/null) || true
done
cat >"$DESKTOP" <<EOF
[Desktop Entry]
Type=Application
Name=Routine
Comment=The day's routine, ticked off as you go
Exec="$LAUNCHER"
Icon=$APP_ID
Terminal=false
Categories=Utility;
StartupWMClass=$APP_ID
StartupNotify=true
$MARK
EOF
command -v update-desktop-database >/dev/null && update-desktop-database "$APPS" 2>/dev/null || true
command -v gtk-update-icon-cache >/dev/null && gtk-update-icon-cache -q -t -f "$HICOLOR" 2>/dev/null || true
say ""
say "Routine $VERSION is installed. Find it in your apps (search for Routine), or run: $LAUNCHER"
say "Update: run the same command again. Remove: … | bash -s -- --uninstall (your data stays)."
say "Your routine and history will be kept in $DATA_DIR (Settings → Data can move them)."
Executable
+190
View File
@@ -0,0 +1,190 @@
#!/usr/bin/env bash
# Routine for macOS: install it, update it (run this again), or remove it (--uninstall).
# UNTESTED ON A REAL MAC so far: if anything goes wrong, please send the output.
#
# curl -fsSL https://git.autonomic.zone/trav/routine/raw/branch/main/install-mac.sh | bash
# curl -fsSL https://git.autonomic.zone/trav/routine/raw/branch/main/install-mac.sh | bash -s -- --uninstall
#
# No admin password, no Xcode, no Homebrew, no git. It downloads into
# ~/Library/Application Support/Routine-app the app, its own Python and Qt (~400 MB)
# and makes Routine.app (in /Applications if you can write there, else ~/Applications) that opens it.
# Your routine and history live apart from it, in ~/Library/Application Support/Routine, and are
# never touched by updating or uninstalling.
#
# How: uv (https://docs.astral.sh/uv/, a single program, kept inside the app folder) fetches a
# standalone Python 3.13 and PySide6 into that folder. Nothing is installed anywhere else.
#
# Optional settings (for testing): ROUTINE_SOURCE=DIR|FILE.tar.gz (a local copy instead of
# downloading), ROUTINE_ARCHIVE=URL, ROUTINE_APPS_DIR=DIR (where Routine.app goes), ROUTINE_UV=PATH
# (a uv already on this machine), ROUTINE_INSTALL_TEST=1 (let it run off a Mac, to test).
set -euo pipefail
REPO_URL="https://git.autonomic.zone/trav/routine"
ARCHIVE="${ROUTINE_ARCHIVE:-$REPO_URL/archive/main.tar.gz}"
UV_VERSION="0.10.4"
PYTHON_VERSION="3.13"
PINS=(PySide6-Essentials==6.11.0) # macOS 13 (Ventura) or newer; Apple silicon and Intel
MIN_MACOS=13
SUPPORT="$HOME/Library/Application Support"
APPDIR="$SUPPORT/Routine-app"
DATA_DIR="$SUPPORT/Routine"
LOGS="$HOME/Library/Logs/Routine"
say() { printf '%s\n' "$*"; }
die() { printf '\nRoutine installer: %s\n' "$*" >&2; exit 1; }
if [ -n "${ROUTINE_APPS_DIR:-}" ]; then
APPS="$ROUTINE_APPS_DIR"
elif [ -w /Applications ]; then
APPS=/Applications
else
APPS="$HOME/Applications"
fi
BUNDLE="$APPS/Routine.app"
uninstall() {
for b in "$BUNDLE" /Applications/Routine.app "$HOME/Applications/Routine.app"; do
if [ -f "$b/Contents/Resources/routine-installer" ]; then # only a Routine.app this script made
rm -rf "$b"
say "Removed $b"
fi
done
rm -rf "$APPDIR"
say "Routine is removed."
say "Your routine, history and settings are still in $DATA_DIR"
say "(or wherever Settings → Data put them), and error logs in $LOGS."
say "Delete those folders yourself if you want them gone."
}
case "${1:-}" in
--uninstall|uninstall) uninstall; exit 0 ;;
-h|--help) say "See the comments at the top of install-mac.sh."; exit 0 ;;
"") ;;
*) die "unknown option $1 (try --uninstall)" ;;
esac
if [ "$(uname -s)" != Darwin ] && [ "${ROUTINE_INSTALL_TEST:-}" != 1 ]; then
die "this is the Mac installer; on Linux use install-linux.sh"
fi
if [ "$(uname -s)" = Darwin ]; then
v="$(sw_vers -productVersion 2>/dev/null || echo 0)"
[ "${v%%.*}" -ge "$MIN_MACOS" ] 2>/dev/null ||
die "Routine needs macOS $MIN_MACOS (Ventura) or newer; this Mac has macOS $v."
fi
for c in curl tar; do command -v "$c" >/dev/null || die "needs $c"; done
say "Installing Routine into $APPDIR"
mkdir -p "$APPDIR" "$LOGS"
# ── 1. The app itself ──
NEW="$APPDIR/src.new"
rm -rf "$NEW"
mkdir -p "$NEW"
SRC="${ROUTINE_SOURCE:-}"
if [ -z "$SRC" ]; then # run from a checkout (not through a pipe)? install that
here="$(dirname "${BASH_SOURCE[0]:-/nonexistent}")"
[ -f "$here/routine/__init__.py" ] && SRC="$(cd "$here" && pwd)"
fi
if [ -n "$SRC" ] && [ -d "$SRC" ]; then
say "Copying Routine from $SRC …"
tar -C "$SRC" --exclude=.git --exclude=__pycache__ --exclude=android -cf - . | tar -C "$NEW" -xf -
elif [ -n "$SRC" ]; then
tar -C "$NEW" --strip-components=1 -xzf "$SRC"
else
say "Downloading Routine …"
curl -fsSL "$ARCHIVE" | tar -C "$NEW" --strip-components=1 -xzf - || die "couldn't download $ARCHIVE"
fi
[ -f "$NEW/routine/__init__.py" ] || die "that doesn't look like Routine (no routine/__init__.py)"
rm -rf "$NEW/android" # the Rabbit R1 app: not used on a Mac (yet)
VERSION="$(sed -n 's/^__version__ = "\(.*\)"/\1/p' "$NEW/routine/__init__.py")"
rm -rf "$APPDIR/src.old"
[ -d "$APPDIR/src" ] && mv "$APPDIR/src" "$APPDIR/src.old"
mv "$NEW" "$APPDIR/src"
rm -rf "$APPDIR/src.old"
# ── 2. uv, then Python and PySide6, all inside APPDIR ──
export UV_PYTHON_INSTALL_DIR="$APPDIR/python"
export UV_CACHE_DIR="$APPDIR/cache"
export UV_PYTHON_PREFERENCE=only-managed # its own Python: never the system's or Homebrew's
export UV_NO_CONFIG=1
UV="${ROUTINE_UV:-$APPDIR/uv/uv}"
if [ ! -x "$UV" ] || ! "$UV" --version 2>/dev/null | grep -q " $UV_VERSION"; then
if [ -z "${ROUTINE_UV:-}" ]; then
say "Downloading uv $UV_VERSION (it fetches Python and Qt) …"
rm -rf "$APPDIR/uv"
curl -LsSf "https://astral.sh/uv/$UV_VERSION/install.sh" |
env UV_UNMANAGED_INSTALL="$APPDIR/uv" INSTALLER_NO_MODIFY_PATH=1 sh >/dev/null ||
die "couldn't download uv from astral.sh"
fi
fi
[ -x "$UV" ] || die "uv isn't at $UV"
if [ ! -x "$APPDIR/venv/bin/python" ]; then
say "Downloading Python $PYTHON_VERSION …"
"$UV" venv --quiet --python "$PYTHON_VERSION" "$APPDIR/venv" || die "couldn't set up Python"
fi
say "Installing ${PINS[*]} (the first time this is a big download) …"
"$UV" pip install --quiet --python "$APPDIR/venv/bin/python" "${PINS[@]}" || die "couldn't install ${PINS[*]}"
rm -rf "$APPDIR/cache"
(cd "$APPDIR/src" && "$APPDIR/venv/bin/python" -c 'import routine.qt.QtWidgets') ||
die "Qt for Python won't start (see the message above)"
# ── 3. Routine.app: a small bundle whose program starts the app above ──
say "Making $BUNDLE …"
mkdir -p "$APPS"
TMPB="$APPS/.Routine.app.new"
rm -rf "$TMPB"
mkdir -p "$TMPB/Contents/MacOS" "$TMPB/Contents/Resources"
cp "$APPDIR/src/shared/icon.icns" "$TMPB/Contents/Resources/Routine.icns"
printf 'Made by install-mac.sh; run it again to update, or with --uninstall to remove.\n' \
>"$TMPB/Contents/Resources/routine-installer"
cat >"$TMPB/Contents/Info.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key><string>Routine</string>
<key>CFBundleDisplayName</key><string>Routine</string>
<key>CFBundleIdentifier</key><string>me.teafry.routine</string>
<key>CFBundleExecutable</key><string>Routine</string>
<key>CFBundleIconFile</key><string>Routine</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>$VERSION</string>
<key>CFBundleVersion</key><string>$VERSION</string>
<key>LSMinimumSystemVersion</key><string>$MIN_MACOS.0</string>
<key>LSApplicationCategoryType</key><string>public.app-category.productivity</string>
<key>NSHighResolutionCapable</key><true/>
<key>NSSupportsAutomaticGraphicsSwitching</key><true/>
</dict>
</plist>
EOF
# The program: bash, so no compiler is needed. exec keeps one process, so the Dock shows Routine.
cat >"$TMPB/Contents/MacOS/Routine" <<EOF
#!/bin/bash
# Starts Routine from $APPDIR (made by install-mac.sh).
APP="$APPDIR"
LOGS="$LOGS"
mkdir -p "\$LOGS"
if [ ! -x "\$APP/venv/bin/python" ] || [ ! -d "\$APP/src/routine" ]; then
/usr/bin/osascript -e 'display alert "Routine isn’t fully installed" message "Run the installer again (see the README)."' >/dev/null 2>&1
exit 1
fi
cd "\$APP/src" || exit 1
exec "\$APP/venv/bin/python" -m routine 2>"\$LOGS/launch.log"
EOF
chmod +x "$TMPB/Contents/MacOS/Routine"
rm -rf "$BUNDLE"
mv "$TMPB" "$BUNDLE"
if [ "$(uname -s)" = Darwin ]; then
xattr -dr com.apple.quarantine "$BUNDLE" 2>/dev/null || true
touch "$BUNDLE"
LSREG=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister
[ -x "$LSREG" ] && "$LSREG" -f "$BUNDLE" >/dev/null 2>&1 || true # the Dock / Launchpad see it now
fi
say ""
say "Routine $VERSION is installed: $BUNDLE"
say "Open it from Launchpad, Spotlight (⌘ Space, type Routine) or the Applications folder;"
say "to keep it in the Dock, right-click its Dock icon → Options → Keep in Dock."
say "Update: run the same command again. Remove: … | bash -s -- --uninstall (your data stays)."
say "Your routine and history will be kept in $DATA_DIR"
+2
View File
@@ -0,0 +1,2 @@
"""Routine: a day-long, check-it-off routine for the desktop, synced with the R1 through a small sync server."""
__version__ = "0.23.0"
+3
View File
@@ -0,0 +1,3 @@
from routine.gui.app import main
main()
+172
View File
@@ -0,0 +1,172 @@
"""Unhandled errors: keep the app running, write the traceback to a log, say so once.
PyQt aborts the whole app on an exception it can't hand to anyone unless sys.excepthook is
something other than the default; install() sets one that
- writes the traceback to LOGS/errors.log (timestamp, version, OS, then the stack): file names,
line numbers and the lines of code only. An exception's message is kept only for the kinds
whose message is about the code (AttributeError, TypeError, …); any other kind's message could
quote a task or a note, so it's left out. No variables, no routine contents.
- shows a small non-modal notice, "Something went wrong — details saved to <path>", at most once
per distinct error (its kind and where it happened) per run; the same error again is not
logged again either (a broken paint would otherwise fill the disk).
- catches errors on worker threads too (logged only: the notice belongs to the GUI thread).
faulthandler writes a hard crash (a segfault in Qt) to LOGS/crash.log.
"""
import datetime as dt
import faulthandler
import os
import sys
import threading
import traceback
from routine import __version__, system
LOG_NAME, CRASH_NAME = "errors.log", "crash.log"
MAX_BYTES = 512 * 1024 # then errors.log becomes errors.log.1 (one old one kept)
# Exceptions whose message describes the code, not the data: kept in the log.
CODE_ERRORS = (AttributeError, TypeError, NameError, ImportError, NotImplementedError, AssertionError,
RecursionError, ZeroDivisionError, IndexError, UnboundLocalError)
_seen = set()
_lock = threading.Lock()
_state = {"dir": None, "notify": None, "crash_file": None}
def log_path():
return os.path.join(_state["dir"] or system.log_dir(), LOG_NAME)
def key_of(etype, te):
"""What makes two errors the same one: its kind and the innermost line it came from."""
last = te.stack[-1] if te.stack else None
return (getattr(etype, "__qualname__", str(etype)), last.filename if last else "", last.lineno if last else 0)
def format_error(etype, value, tb):
"""The traceback, its message kept only for CODE_ERRORS (see the module's docstring)."""
te = traceback.TracebackException(etype, value, tb, capture_locals=False)
lines = ["Traceback (most recent call last):\n"] + list(te.stack.format())
name = getattr(etype, "__qualname__", str(etype))
if isinstance(value, CODE_ERRORS):
lines += list(te.format_exception_only())
else:
lines.append("%s: (message left out: it could quote your routine)\n" % name)
return te, "".join(lines)
def write(text, folder=None):
folder = folder or _state["dir"] or system.log_dir()
os.makedirs(folder, exist_ok=True)
path = os.path.join(folder, LOG_NAME)
try:
if os.path.getsize(path) > MAX_BYTES:
os.replace(path, path + ".1")
except OSError:
pass
with open(path, "a", encoding="utf-8") as f:
f.write(text)
return path
def header():
return "── %s · Routine %s · %s\n" % (dt.datetime.now().isoformat(timespec="seconds"), __version__,
system.describe())
def handle(etype, value, tb, gui=True):
"""Log it (once per distinct error) and, from the GUI thread, show the notice once. True if new."""
try:
te, text = format_error(etype, value, tb)
key = key_of(etype, te)
with _lock:
if key in _seen:
return False
_seen.add(key)
try:
path = write(header() + text + "\n")
except OSError:
path = None
sys.stderr.write(text)
if gui and _state["notify"] is not None:
_state["notify"](path)
return True
except Exception: # noqa: BLE001 — the hook itself must never raise
try:
traceback.print_exception(etype, value, tb)
except Exception: # noqa: BLE001
pass
return False
def _hook(etype, value, tb):
if issubclass(etype, KeyboardInterrupt):
sys.__excepthook__(etype, value, tb)
return
handle(etype, value, tb, gui=threading.current_thread() is threading.main_thread())
def _thread_hook(args):
if args.exc_type is SystemExit:
return
handle(args.exc_type, args.exc_value, args.exc_traceback, gui=False)
def install(folder=None, notify=None):
"""Set the hooks. notify(path) shows the notice (the GUI sets it once Qt is up: set_notify)."""
_state["dir"] = folder or system.log_dir()
_state["notify"] = notify
sys.excepthook = _hook
threading.excepthook = _thread_hook
try:
os.makedirs(_state["dir"], exist_ok=True)
_state["crash_file"] = open(os.path.join(_state["dir"], CRASH_NAME), "a", encoding="utf-8")
faulthandler.enable(_state["crash_file"])
except OSError:
pass
def set_notify(notify):
_state["notify"] = notify
def reset():
"""For tests: forget which errors were seen."""
_seen.clear()
# ── the notice (Qt) ──
_notices = []
def show_notice(path):
"""A small non-modal box: what happened and where the details are, with Open log folder."""
from routine.qt.QtCore import Qt, QUrl
from routine.qt.QtGui import QDesktopServices
from routine.qt.QtWidgets import QApplication, QMessageBox
if QApplication.instance() is None:
return
box = QMessageBox()
box.setWindowTitle("Routine")
box.setIcon(QMessageBox.Icon.Warning)
box.setText("Something went wrong, but Routine is still running.")
box.setInformativeText(("Details saved to %s\n\n" % path if path else "") +
"If it keeps happening, please send that file to whoever gave you Routine. "
"It holds only where the program went wrong, never your routine or notes.")
box.setWindowModality(Qt.WindowModality.NonModal)
opener = box.addButton("Open log folder", QMessageBox.ButtonRole.ActionRole)
ok = box.addButton(QMessageBox.StandardButton.Ok)
box.setEscapeButton(ok) # without one a QMessageBox refuses to close, and so blocks quitting
box.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False) # closing the main window still quits
folder = os.path.dirname(path) if path else None
def clicked(b):
if b is opener and folder:
QDesktopServices.openUrl(QUrl.fromLocalFile(folder))
if box in _notices:
_notices.remove(box)
box.buttonClicked.connect(clicked)
box.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
_notices.append(box)
box.show()
View File
+259
View File
@@ -0,0 +1,259 @@
"""Draw one frame of shared/animations.json with a QPainter (see tools/anim_kit.py for the format).
The streak number (shape "n", only in animations.json "streak"), exactly, for the Java port:
["n", w, cx, cy, h, rot] the number given to paint_frame (e.g. 7, 21, 465), in the current
colour; nothing at all if no number is given.
Its decimal digits are laid out left to right, each DIGIT_W * h wide, DIGIT_ADV * h apart,
the whole row centred on (cx, cy): with n digits, W = (n - 1) * DIGIT_ADV + DIGIT_W, and
digit k's glyph point (gx, gy) from DIGITS (a cell 0..DIGIT_W across, 0..1 down) lands at
u = (k * DIGIT_ADV + gx - W / 2) * h, v = (gy - 0.5) * h
x = cx + u cos(rot) - v sin(rot), y = cy + u sin(rot) + v cos(rot) (box units)
then px = box centre + x * unit as for every shape. Each digit is one or more open polylines
(DIGITS[d] = a list of strokes, each a flat list x0, y0, x1, y1, ...), stroked w wide (w * unit px)
with round caps and joins, never filled.
The streak caption, "<n> days!", drawn by the painters for every streak play (not frame data; no
other animation has one), in the animation's own colour (its "color", not later "k" shapes):
Glyphs: the digits above, plus LETTERS ("d", "a", "y", "s", "!": (width, strokes), same cell, y = 1
the baseline, "y" dipping to 1.32) and " " (CAPTION_SPACE wide, nothing drawn). Glyph k starts at
gx_k = sum of the widths before it + k * CAPTION_GAP; the row is W = gx_last + width_last wide.
caption_strokes(number, cx, top, h, s): glyph point (gx, gy) of glyph k lands at
x = cx + (gx_k + gx - W / 2) * h * s, y = top + h / 2 + (gy - 0.5) * h * s (box units)
(s: the pop-in scale, about the middle of the digits' height). Stroked CAPTION_STROKE * h * s wide
(times unit px), round caps and joins. h = caption_h(anim): CAPTION_REL times the tallest "n" shape's
h in the animation, at most CAPTION_H, at least CAPTION_MIN (so always smaller than its own number).
caption_place(b, number, above): b = the animation's bounds (number included). Centred on
(b.x0 + b.x1) / 2; below: top = max(b.y1, 0.5) + CAPTION_SEP + half a stroke (0.5: clear of the
ticked box), above: the caption's lowest point (the "y", 1.32 h, + half a stroke) sits CAPTION_SEP
over min(b.y0, -0.5). Returns (cx, top, the union of b and the
caption's own bounds); the union is what on-screen placement fits. Both painters try below then
above, once per play, and keep the one drawn bigger, then the one moved less (below on a tie).
Reveal: the caption starts on caption_start(anim), the first frame with an "n" shape, but no later
than CAPTION_LAST frames before the end (always on screen at least that long); nothing before it.
Pop-in: from there the scale is CAPTION_POP[0], [1], .. for the first frames, then 1.
"""
import math
from routine.qt.QtCore import QPointF, Qt
from routine.qt.QtGui import QBrush, QColor, QPainterPath, QPen
DIGIT_W, DIGIT_ADV = 0.6, 0.82
DIGITS = { # hand-drawn strokes in a DIGIT_W x 1 cell, y down (keep in step with the Java painter)
"0": [[0.3, 0.0, 0.5, 0.07, 0.6, 0.3, 0.6, 0.7, 0.5, 0.93, 0.3, 1.0, 0.1, 0.93, 0.0, 0.7, 0.0, 0.3, 0.1, 0.07,
0.3, 0.0]],
"1": [[0.1, 0.2, 0.34, 0.0, 0.34, 1.0], [0.1, 1.0, 0.56, 1.0]],
"2": [[0.02, 0.22, 0.12, 0.06, 0.3, 0.0, 0.48, 0.06, 0.58, 0.24, 0.52, 0.44, 0.02, 1.0, 0.6, 1.0]],
"3": [[0.04, 0.1, 0.24, 0.0, 0.46, 0.04, 0.56, 0.2, 0.48, 0.38, 0.26, 0.46, 0.5, 0.54, 0.6, 0.74, 0.52, 0.92,
0.3, 1.0, 0.04, 0.9]],
"4": [[0.46, 1.0, 0.46, 0.0, 0.0, 0.68, 0.6, 0.68]],
"5": [[0.56, 0.0, 0.1, 0.0, 0.05, 0.44, 0.28, 0.38, 0.5, 0.46, 0.6, 0.68, 0.52, 0.9, 0.3, 1.0, 0.02, 0.92]],
"6": [[0.52, 0.04, 0.32, 0.0, 0.12, 0.12, 0.02, 0.4, 0.02, 0.72, 0.12, 0.94, 0.3, 1.0, 0.5, 0.94, 0.6, 0.74,
0.52, 0.52, 0.3, 0.46, 0.1, 0.54, 0.02, 0.7]],
"7": [[0.0, 0.0, 0.6, 0.0, 0.22, 1.0]],
"8": [[0.3, 0.46, 0.1, 0.38, 0.06, 0.2, 0.16, 0.04, 0.3, 0.0, 0.44, 0.04, 0.54, 0.2, 0.5, 0.38, 0.3, 0.46,
0.06, 0.56, 0.0, 0.76, 0.1, 0.94, 0.3, 1.0, 0.5, 0.94, 0.6, 0.76, 0.54, 0.56, 0.3, 0.46]],
"9": [[0.08, 0.96, 0.28, 1.0, 0.48, 0.88, 0.58, 0.6, 0.58, 0.28, 0.48, 0.06, 0.3, 0.0, 0.1, 0.06, 0.0, 0.26,
0.08, 0.48, 0.3, 0.54, 0.5, 0.46, 0.58, 0.3]],
}
LETTERS = { # the caption's letters, same cell as DIGITS (keep in step with Digits.java)
"d": (0.5, [[0.5, 0.0, 0.5, 1.0], [0.5, 0.58, 0.38, 0.45, 0.22, 0.43, 0.08, 0.52, 0.02, 0.72, 0.08, 0.92,
0.22, 1.0, 0.38, 0.98, 0.5, 0.86]]),
"a": (0.52, [[0.46, 0.43, 0.46, 0.92, 0.52, 1.0], [0.46, 0.58, 0.34, 0.45, 0.2, 0.43, 0.07, 0.52, 0.0, 0.72,
0.07, 0.92, 0.2, 1.0, 0.34, 0.97, 0.46, 0.84]]),
"y": (0.5, [[0.0, 0.43, 0.26, 0.98], [0.5, 0.43, 0.24, 1.12, 0.16, 1.28, 0.04, 1.32]]),
"s": (0.45, [[0.44, 0.5, 0.32, 0.43, 0.16, 0.43, 0.04, 0.5, 0.04, 0.62, 0.16, 0.69, 0.32, 0.74, 0.45, 0.82,
0.45, 0.93, 0.32, 1.0, 0.14, 1.0, 0.0, 0.92]]),
"!": (0.16, [[0.08, 0.0, 0.08, 0.7], [0.08, 0.98, 0.08, 1.0]]),
}
CAPTION_H = 0.9 # the caption's digit height at most, box units (the animations' own numbers: 1.1 - 2.9)
CAPTION_REL = 0.7 # ... and at most this much of the animation's tallest number
CAPTION_MIN = 0.6 # ... but never under this
CAPTION_STROKE = 0.16 # its stroke, times its height
CAPTION_GAP = 0.18 # between glyphs, times its height
CAPTION_SPACE = 0.32 # the space's width
CAPTION_SEP = 0.35 # between the animation and the caption, box units
CAPTION_DEEP = 1.32 # its lowest point (the "y"), times its height
CAPTION_POP = [0.5, 0.8, 1.08] # its scale over its first frames, then 1
CAPTION_LAST = 10 # it is on screen at least this many frames (the last ones)
def caption_h(anim):
"""The caption's height for an animation (see the module docstring)."""
hs = [sh[4] for fr in anim["frames"] for sh in fr if sh[0] == "n"]
return max(CAPTION_MIN, min(CAPTION_H, CAPTION_REL * max(hs))) if hs else CAPTION_H
def caption_text(number):
return "%d days!" % number
def _glyph(ch):
if ch in DIGITS:
return DIGIT_W, DIGITS[ch]
if ch in LETTERS:
return LETTERS[ch]
return CAPTION_SPACE, []
def caption_strokes(number, cx, top, h=CAPTION_H, scale=1.0):
"""The caption's strokes in box units: [[x0, y0, x1, y1, ...], ...] (see the module docstring)."""
glyphs = [_glyph(ch) for ch in caption_text(number)]
starts, x = [], 0.0
for w, _ in glyphs:
starts.append(x)
x += w + CAPTION_GAP
W = x - CAPTION_GAP
out = []
for gx0, (_, strokes) in zip(starts, glyphs):
for stroke in strokes:
pts = []
for m in range(0, len(stroke), 2):
pts += [cx + (gx0 + stroke[m] - W / 2) * h * scale, top + h / 2 + (stroke[m + 1] - 0.5) * h * scale]
out.append(pts)
return out
def caption_place(b, number, above=False, h=CAPTION_H):
"""(cx, top, union bounds) for the caption under (above) bounds b (see the module docstring)."""
pad = CAPTION_STROKE * h / 2
cx = (b[0] + b[2]) / 2
top = min(b[1], -0.5) - CAPTION_SEP - pad - CAPTION_DEEP * h if above else max(b[3], 0.5) + CAPTION_SEP + pad
flat = [v for st in caption_strokes(number, cx, top, h) for v in st]
return cx, top, (min(b[0], min(flat[0::2]) - pad), min(b[1], min(flat[1::2]) - pad),
max(b[2], max(flat[0::2]) + pad), max(b[3], max(flat[1::2]) + pad))
def caption_start(anim):
"""The frame the caption starts on: where the number first shows, at the latest CAPTION_LAST from the end."""
first = next((k for k, fr in enumerate(anim["frames"]) if any(sh[0] == "n" for sh in fr)), 0)
return max(0, min(first, len(anim["frames"]) - CAPTION_LAST))
def caption_scale(frame, start=0):
"""The caption's scale on a frame: 0 (not drawn) before start, then CAPTION_POP, then 1."""
k = frame - start
if k < 0:
return 0.0
return CAPTION_POP[k] if k < len(CAPTION_POP) else 1.0
def paint_caption(p, number, color, cx, cy, unit, place, frame=99, h=CAPTION_H, start=0):
"""The caption at place = (caption cx, top) from caption_place, around the box centre (cx, cy) px;
h: caption_h of the animation; start: its caption_start."""
s = caption_scale(frame, start)
if s <= 0:
return
pen = QPen(QColor(color), CAPTION_STROKE * h * s * unit)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.save()
p.setRenderHint(p.RenderHint.Antialiasing, True)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
for st in caption_strokes(number, place[0], place[1], h, s):
path = QPainterPath(QPointF(cx + st[0] * unit, cy + st[1] * unit))
for k in range(2, len(st), 2):
path.lineTo(cx + st[k] * unit, cy + st[k + 1] * unit)
p.drawPath(path)
p.restore()
def number_strokes(number, cx, cy, h, rot):
"""The streak number's strokes in box units: [[x0, y0, x1, y1, ...], ...] (see the module docstring)."""
text = str(number)
W = (len(text) - 1) * DIGIT_ADV + DIGIT_W
c, s = math.cos(rot), math.sin(rot)
out = []
for k, ch in enumerate(text):
for stroke in DIGITS.get(ch, []):
pts = []
for m in range(0, len(stroke), 2):
u = (k * DIGIT_ADV + stroke[m] - W / 2) * h
v = (stroke[m + 1] - 0.5) * h
pts += [cx + u * c - v * s, cy + u * s + v * c]
out.append(pts)
return out
def bounds(anim, number=None):
"""(x0, y0, x1, y1): everything the animation draws, over all its frames, in box units
from the box's centre (strokes' half widths included). number: the streak number it will
show (the "n" shapes' size depends on its digits)."""
x0 = y0 = x1 = y1 = 0.0
for frame in anim["frames"]:
for sh in frame:
if sh[0] == "k" or (sh[0] == "n" and number is None):
continue
pad, pts = (sh[1] or 0) / 2, sh[2:]
if sh[0] == "n":
flat = [v for st in number_strokes(number, *pts[:4]) for v in st]
xs = [x + d for x in flat[0::2] for d in (-pad, pad)]
ys = [y + d for y in flat[1::2] for d in (-pad, pad)]
elif sh[0] == "c":
r = pts[2] + pad
xs, ys = (pts[0] - r, pts[0] + r), (pts[1] - r, pts[1] + r)
else:
xs = [x + d for x in pts[0::2] for d in (-pad, pad)]
ys = [y + d for y in pts[1::2] for d in (-pad, pad)]
x0, x1 = min(x0, *xs), max(x1, *xs)
y0, y1 = min(y0, *ys), max(y1, *ys)
return x0, y0, x1, y1
def fit(c, lo, hi, size, margin):
"""The centre to draw at: c (the box's), moved as little as keeps lo..hi (px either side
of the centre) inside 0..size with margin to spare; centred if it can't fit at all."""
room = size - 2 * margin
if hi - lo >= room:
return size / 2 - (lo + hi) / 2
if c + lo < margin:
return margin - lo
if c + hi > size - margin:
return size - margin - hi
return c
def paint_frame(p, frame, color, cx, cy, unit, palette=None, number=None):
"""frame: list of shapes; (cx, cy): the box centre in px; unit: px per box size.
palette: colour names -> hex, for ["k", name] shapes (the star, the streak ones).
number: the streak number the "n" shapes show (None: they draw nothing)."""
col = QColor(color)
p.save()
p.setRenderHint(p.RenderHint.Antialiasing, True)
for sh in frame:
if sh[0] == "k":
col = QColor((palette or {}).get(sh[1], color))
continue
kind, w, pts = sh[0], sh[1], sh[2:]
if kind == "n" and number is None:
continue
if w or kind == "n":
pen = QPen(col, w * unit)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
else:
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QBrush(col))
if kind == "c":
p.drawEllipse(QPointF(cx + pts[0] * unit, cy + pts[1] * unit), pts[2] * unit, pts[2] * unit)
continue
if kind == "n":
for st in number_strokes(number, *pts[:4]):
path = QPainterPath(QPointF(cx + st[0] * unit, cy + st[1] * unit))
for k in range(2, len(st), 2):
path.lineTo(cx + st[k] * unit, cy + st[k + 1] * unit)
p.drawPath(path)
continue
path = QPainterPath(QPointF(cx + pts[0] * unit, cy + pts[1] * unit))
for k in range(2, len(pts), 2):
path.lineTo(cx + pts[k] * unit, cy + pts[k + 1] * unit)
if kind == "p":
path.closeSubpath()
p.drawPath(path)
p.restore()
+585
View File
@@ -0,0 +1,585 @@
"""The desktop window: title bar, (hidden) menu bar, one day at a time, and the bottom bar.
On macOS: the system's title bar, the Mac menu bar at the top of the screen, no sync (system.py)."""
import datetime as dt
import json
import os
import sys
import urllib.request
from routine.qt.QtCore import QEvent, QLibraryInfo, QPoint, QPointF, QSize, Qt, QTimer, QUrl, Signal
from routine.qt.QtGui import (QAction, QColor, QDesktopServices, QFontDatabase, QFontMetricsF, QGuiApplication, QIcon,
QKeySequence, QPainter, QPen, QPixmap)
from routine.qt.QtNetwork import QLocalServer, QLocalSocket
from routine.qt.QtWidgets import QApplication, QHBoxLayout, QMenuBar, QMessageBox, QPushButton, QVBoxLayout, QWidget
from routine import __version__, crash, model, paths, storage, system
from routine.gui.chrome import AltMenuFilter, TitleBar, TooltipFilter, key_text
from routine.gui.dayview import DayView
from routine.gui.frame import EDGE, make_grips, paint_tile, place_grips
from routine.gui.look import HouseStyle, Look, display_font
from routine.gui.overlay import AnimOverlay
from routine.gui.prefs import Preferences, tiles
from routine.store import Store
from routine.sync import Syncer
APP_ID = system.APP_ID
BIGGER = 1.69 # the bottom bar's buttons: 1.3 × 1.3 an ordinary button (height and text)
def chevrons_icon(px, dpr, color, stroke, tall):
"""Now: a double chevron (») in the glyph colour, drawn with the ‹ › glyphs' stroke and height."""
pm = QPixmap(int(px * dpr), int(px * dpr))
pm.setDevicePixelRatio(dpr)
pm.fill(Qt.GlobalColor.transparent)
p = QPainter(pm)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
pen = QPen(QColor(color), stroke)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.setPen(pen)
c, u = px / 2, tall / 2.6
for dx in (-u * 0.9, u * 0.9):
p.drawPolyline([QPointF(c + dx - u * 0.6, c - u * 1.3), QPointF(c + dx + u * 0.6, c),
QPointF(c + dx - u * 0.6, c + u * 1.3)])
p.end()
return QIcon(pm)
def fit_window(w, h):
"""w × h, scaled down (same shape) to fit the screen's free area."""
scr = QGuiApplication.primaryScreen()
if scr is None:
return w, h
a = scr.availableGeometry()
k = min(1.0, (a.height() - 40) / h, (a.width() - 40) / w)
return int(w * k), int(h * k)
def system_mode():
scheme = QGuiApplication.styleHints().colorScheme()
return "dark" if scheme == Qt.ColorScheme.Dark else "light"
class Window(QWidget):
# Days whose record changed (ISO dates): a tick or note here, a sync from the server, a new day.
# The History / Statistics / Journal windows connect to it to stay fresh.
days_changed = Signal(list)
# A setting the side windows care about changed (its cfg key, or "look" for colours / mode / fonts).
restyled = Signal(str)
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
if not system.native_frame():
self.setWindowFlag(Qt.WindowType.FramelessWindowHint)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) # for the rounded corners
self.setWindowTitle("Routine")
self.schedule, _ = storage.load_schedule(cfg)
self.store = Store(paths.db_path(cfg))
self.today = model.routine_date(self.schedule)
self.store.ensure_history(self.schedule, self.today)
self.syncer = Syncer(self.store, cfg, lambda: self.schedule, enabled=system.sync_supported())
self.syncer.changed.connect(self._remote_changed)
self.syncer.schedule.connect(lambda s: self.apply_schedule(s, from_server=True))
self.look = Look(self._mode(), cfg)
self.view = None
self.date = self.today.isoformat()
self.prefs = None
self.side = {} # the History / Statistics / Journal windows, once opened
self._build()
self.resize(*fit_window(*cfg.get("window", paths.DEFAULTS["window"])))
self.go(self.date, now=True)
self.clock = QTimer(self, interval=60_000, timeout=self._tick)
self.clock.start()
QTimer.singleShot(500, self.syncer.sync_now)
def _mode(self):
m = self.cfg.get("mode", "system")
return system_mode() if m == "system" else m
# ── building ──
def _build(self):
app = QApplication.instance()
app.setStyle(HouseStyle(self.look))
app.setPalette(self.look.palette())
app.setStyleSheet(self.look.qss())
if self.layout():
QWidget().setLayout(self.layout()) # drop the old layout and its widgets
for a in self.actions():
self.removeAction(a)
if hasattr(self, "overlay"):
self.overlay.deleteLater()
col = QVBoxLayout(self)
col.setContentsMargins(EDGE, 0, EDGE, EDGE)
col.setSpacing(0)
self.titlebar = TitleBar(self, self.look, "") # blank: just the window buttons (the window keeps its title)
col.addWidget(self.titlebar)
self.menubar = self._menus()
if not system.global_menubar():
col.addWidget(self.menubar)
self.menubar.setVisible(not self.cfg.get("hide_menubar", True))
if hasattr(self, "alt_filter"):
app.removeEventFilter(self.alt_filter)
self.alt_filter = AltMenuFilter(self, self.menubar, self.cfg.get("hide_menubar", True))
app.installEventFilter(self.alt_filter)
self.body = QVBoxLayout()
col.addLayout(self.body, 1)
self.bottom = self._bottom()
col.addWidget(self.bottom)
if not hasattr(self, "grips"):
self.grips = make_grips(self)
self.overlay = AnimOverlay(self, self.cfg)
self.overlay.setGeometry(self.rect())
self.view = None
def _menus(self):
"""The menu bar: in the window (Linux, hidden until Alt), or the Mac's at the top of the
screen. That one is made once without a parent, so it stays while a side window has the
focus; a rebuild empties and refills it. Settings, Quit and About go to the Mac's app
menu by their roles (Qt moves them there; Ctrl is ⌘ there)."""
if system.global_menubar():
if getattr(self, "_global_bar", None) is None:
self._global_bar = QMenuBar(None)
bar = self._global_bar
bar.clear()
else:
bar = QMenuBar(self)
Role = QAction.MenuRole
def act(menu, text, keys, fn, role=Role.NoRole):
a = QAction(text, self)
if keys:
a.setShortcut(QKeySequence(keys))
a.setMenuRole(role)
a.triggered.connect(fn)
menu.addAction(a)
if not system.global_menubar(): # shortcuts keep working with the bar hidden
self.addAction(a) # (the Mac's bar is never hidden, and serves every window)
return a
m = bar.addMenu("&File")
sync = act(m, "Sync now", "Ctrl+R", self.syncer.sync_now)
if not system.sync_supported():
sync.setText("Sync now (coming soon on macOS)")
sync.setEnabled(False)
m.addSeparator()
if system.global_menubar(): # Settings goes to the app menu: no Edit menu
act(m, "&Settings…", "Ctrl+,", self.open_prefs, Role.PreferencesRole)
act(m, "&Quit", "Ctrl+Q", self.close, Role.QuitRole)
if not system.global_menubar():
m = bar.addMenu("&Edit")
act(m, "&Settings…", "Ctrl+,", self.open_prefs, Role.PreferencesRole)
m = bar.addMenu("&View")
act(m, "&All tasks", "Ctrl+1", lambda: self.filter_tiles.pick("all"))
act(m, "&Incomplete tasks", "Ctrl+2", lambda: self.filter_tiles.pick("incomplete"))
act(m, "&Completed tasks", "Ctrl+3", lambda: self.filter_tiles.pick("completed"))
m.addSeparator()
act(m, "&Now", "Ctrl+N", lambda: self.go(self.today.isoformat(), now=True))
act(m, "&Earlier day", "Alt+Left", lambda: self.step(-1))
act(m, "&Later day", "Alt+Right", lambda: self.step(1))
m.addSeparator()
act(m, "&History", system.shortcut("history"), lambda: self.open_side("history"))
act(m, "&Statistics", "Ctrl+T", lambda: self.open_side("stats"))
act(m, "&Journal", "Ctrl+J", lambda: self.open_side("journal"))
m = bar.addMenu("&Help")
act(m, "Open &log folder", None, self.open_logs)
m.addSeparator()
act(m, "&About Routine", None, self.about, Role.AboutRole)
return bar
def open_logs(self):
os.makedirs(paths.LOGS, exist_ok=True)
QDesktopServices.openUrl(QUrl.fromLocalFile(paths.LOGS))
def about(self):
QMessageBox.about(self, "About Routine",
"<b>Routine %s</b><p>The day's routine, ticked off as you go.</p>"
"<p>%s<br>Qt %s</p><p>Your routine and history: %s<br>Settings: %s<br>Error log: %s</p>"
% (__version__, system.describe(), QLibraryInfo.version().toString(),
os.path.dirname(paths.schedule_path(self.cfg)), paths.CONFIG, paths.LOGS))
def _bottom(self):
bar = QWidget()
lay = QHBoxLayout(bar)
lay.setContentsMargins(8, 4, 8, 3)
self.filter_tiles = tiles([("all", "All"), ("incomplete", "Incomplete"), ("completed", "Completed")],
self.cfg.get("filter", "all"), self.set_filter)
self.filter_tiles.setToolTip("Show every task, only the ones still to do, or only the ones done "
"(earlier days open on Completed)")
lay.addWidget(self.filter_tiles)
lay.addStretch(1)
self.prev_btn = QPushButton("‹")
self.prev_btn.setProperty("tile", "left")
self.prev_btn.setProperty("glyph", True)
self.prev_btn.setToolTip("Earlier day (%s)" % key_text("Alt+Left"))
self.prev_btn.setAccessibleName("Earlier day")
self.prev_btn.clicked.connect(lambda: self.step(-1))
self.next_btn = QPushButton("›")
self.next_btn.setProperty("tile", "right")
self.next_btn.setProperty("glyph", True)
self.next_btn.setToolTip("Later day (%s)" % key_text("Alt+Right"))
self.next_btn.setAccessibleName("Later day")
self.next_btn.clicked.connect(lambda: self.step(1))
pair = QWidget()
pl = QHBoxLayout(pair)
pl.setContentsMargins(0, 0, 0, 0)
pl.setSpacing(0)
pl.addWidget(self.prev_btn)
pl.addWidget(self.next_btn)
lay.addWidget(pair)
now = QPushButton()
px = int(now.fontMetrics().height() * 1.15 * 1.3)
now.setIcon(self._chevrons(px))
now.setIconSize(QSize(px, px))
now.setToolTip("Now")
now.setAccessibleName("Now")
now.clicked.connect(lambda: self.go(self.today.isoformat(), now=True))
lay.addWidget(now)
plain = QPushButton("All")
h = round(plain.sizeHint().height() * BIGGER)
pt = plain.font().pointSizeF() * 1.3
for b in bar.findChildren(QPushButton):
b.setFixedHeight(h)
b.setFont(display_font(pt)) # the tasks' font: easy to read
self.bar_font = display_font(pt)
now.setIcon(self._chevrons(px)) # again, now that the bar's font is known
return bar
def _chevrons(self, px):
"""» matched to the ‹ › beside it: their glyph's height, the font's stroke weight."""
f = getattr(self, "bar_font", None) or self.font()
fm = QFontMetricsF(f)
tall = fm.tightBoundingRect("›").height()
stroke = max(1.0, fm.lineWidth() * 1.15)
return chevrons_icon(px, self.devicePixelRatioF(), self.look.glyph, stroke, tall)
# ── days ──
def go(self, date, now=False):
same = date == getattr(self, "date", None)
if self.view is not None:
self.view.flush()
self.body.removeWidget(self.view)
self.view.deleteLater()
self.date = date
day = self.store.get(date)
f = self.view.filter if same and self.view else self._filter() # a redraw keeps the filter
self.filter_tiles.show(f)
self.view = DayView(self.look, self.schedule, day, f, self.today, self.cfg)
self.view.prefs_changed.connect(lambda: paths.save_config(self.cfg))
self.view.changed.connect(self._edited)
self.view.player = self.overlay.play
self.view.streak_of = self.streak_of
self.view.swipe.connect(self.step)
self.body.addWidget(self.view)
self.update() # the header band follows the new view
dates = self.store.dates()
self.prev_btn.setEnabled(dates.index(date) > 0)
self.next_btn.setEnabled(date < self.today.isoformat())
self.overlay.raise_()
if now:
self.view.scroll_to_now()
def step(self, d):
dates = self.store.dates()
i = dates.index(self.date) + d
if 0 <= i < len(dates) and dates[i] <= self.today.isoformat():
self.go(dates[i], now=dates[i] == self.today.isoformat())
def _filter(self):
"""Today: the filter last picked for it. An earlier day opens on Completed."""
return self.cfg.get("filter", "all") if self.date == self.today.isoformat() else "completed"
def set_filter(self, f):
if self.date == self.today.isoformat(): # a pick on an earlier day lasts while it's shown
self.cfg["filter"] = f
paths.save_config(self.cfg)
if self.view:
self.view.set_filter(f)
def _edited(self, day):
self.store.put(day)
self.syncer.soon()
self.days_changed.emit([day["date"]])
def _remote_changed(self, dates):
if self.date in dates and self.view:
self.view.refresh(self.store.get(self.date))
self.days_changed.emit(list(dates))
def streak_of(self, day, item_id):
"""The streak ticking item_id on day (the record being edited, maybe not saved yet) reaches."""
days = self.store.range(None, (dt.date.fromisoformat(day["date"]) - dt.timedelta(days=1)).isoformat())
return model.streak_ending(days + [day], item_id, day["date"], paths.cheat_after(self.cfg))
# ── the side windows: History, Statistics, Journal ──
def open_side(self, key):
"""Show the side window key ("history" | "stats" | "journal"), made on first use; the main
window stays open, and asking again raises the one already there."""
w = self.side.get(key)
if w is None:
from routine.gui import history, journal, stats
cls = {"history": history.HistoryWindow, "stats": stats.StatsWindow, "journal": journal.JournalWindow}[key]
w = self.side[key] = cls(self)
if w.isMinimized():
w.showNormal()
w.show()
w.raise_()
w.activateWindow()
def _tick(self):
today = model.routine_date(self.schedule)
if today != self.today:
was_today = self.date == self.today.isoformat()
self.today = today
self.store.ensure_history(self.schedule, today)
self.syncer.soon()
self.days_changed.emit([today.isoformat()])
if was_today:
self.go(today.isoformat(), now=True)
return
if self.view:
self.view.mark_now()
# ── the routine itself ──
def apply_schedule(self, sch, from_server=False):
"""A new routine, from the editor or from the sync server: keep it, give today its blocks, redraw."""
if from_server and sch.get("rev", 0) <= self.schedule.get("rev", 0):
return
storage.write_schedule(paths.schedule_path(self.cfg), sch)
self.schedule = sch
t = self.store.get(self.today.isoformat())
if model.refresh_snapshot(sch, t):
self.store.put(t)
if self.view: # any day: block colours follow the routine
y = self.view.verticalScrollBar().value()
self.go(self.date)
QTimer.singleShot(0, lambda: self.view.verticalScrollBar().setValue(y))
if from_server and self.prefs and not self.prefs.editor.dirty:
self.prefs.editor.load()
if not from_server:
self.syncer.soon()
# ── where the routine and the history are kept (Settings → Data) ──
def relocate(self, kind, folder, ask):
"""Keep the routine ("schedule") or the history ("db") in folder from now on (None = the
default), moving the file there (storage.move_file). Everything carries on live: the Store
reopens in place, so the side windows and the syncer follow. ask(target, backup_name) is
called when the folder already has one: "use", "replace" or None (cancel).
Returns a line for the Settings page, or None if cancelled."""
key = kind + "_dir"
where = paths.schedule_path if kind == "schedule" else paths.db_path
new_cfg = dict(self.cfg, **{key: folder or ""})
src, dst = where(self.cfg), where(new_cfg)
if os.path.abspath(src) == os.path.abspath(dst):
self._set_location(key, folder)
return "Already kept there."
taken = None
if os.path.exists(dst) and os.path.exists(src):
taken = ask(dst, storage.replaced_name(dst))
if taken is None:
return None
check = storage.check_schedule if kind == "schedule" else storage.check_db
if kind == "db":
if self.view:
self.view.flush()
self.store.close()
try:
done = storage.move_file(src, dst, taken, check)
except storage.MoveError as e:
if kind == "db":
self.store.open(src)
return "Not moved: %s. Nothing changed." % e
self._set_location(key, folder)
if kind == "db":
self.store.open(dst)
if done == "used": # another history: sync it from the start
self.store.set_meta("seq", 0)
self.store.set_meta("schedule_pushed", 0)
self.store.ensure_history(self.schedule, self.today)
self.syncer.database_swapped()
date = self.date if self.store.get(self.date) else self.today.isoformat()
self.go(date, now=date == self.today.isoformat())
self.days_changed.emit(self.store.dates())
elif done == "used": # their routine: make it the one in use
sch = storage.read_schedule(dst)
if sch.get("rev", 0) <= self.schedule.get("rev", 0):
sch["rev"] = self.schedule.get("rev", 0) + 1 # newer, so today and the R1 take it
self.apply_schedule(sch)
if self.prefs and not self.prefs.editor.dirty:
self.prefs.editor.load()
name = os.path.basename(dst)
if done == "moved" and taken == "replace":
return "Moved %s to %s; the one that was there is kept beside it, renamed." % (name, os.path.dirname(dst))
return {"moved": "Moved %s to %s." % (name, os.path.dirname(dst)),
"used": "Now using the %s that was in %s (the one before stays where it was)." % (name, os.path.dirname(dst)),
"nothing": "From now on %s is kept in %s." % (name, os.path.dirname(dst)),
"same": "Already kept there."}[done]
def _set_location(self, key, folder):
self.cfg[key] = folder or ""
paths.save_config(self.cfg)
# ── prefs ──
def open_prefs(self):
if self.prefs is None:
self.prefs = Preferences(self, self.cfg, self.syncer, self._pref_changed, lambda: self.schedule,
self.apply_schedule, self._mode(), self.relocate)
self.prefs.show()
self.prefs.raise_()
def _pref_changed(self, key):
if key == "look": # a gray or the tint, mid-drag: show it, save later
self.look.__init__(self._mode(), self.cfg)
if not hasattr(self, "_restyle"):
self._restyle = QTimer(self, singleShot=True, interval=30, timeout=self.restyle)
self._restyle.start()
return
paths.save_config(self.cfg)
if key == "look_saved":
return
if key in ("cheat_day", "cheat_after", "emboss_history", "streak_anims"):
self.restyled.emit(key) # streaks are counted differently / dots drawn differently
return
if key in ("chrome_font", "note_font", "block_style", "show_year", "emboss_blocks", "show_now"): # redo the window, keep Settings open
self.look.__init__(self._mode(), self.cfg)
old, self.bottom = self.bottom, self._bottom()
self.layout().replaceWidget(old, self.bottom)
old.deleteLater()
y = self.view.verticalScrollBar().value() if self.view else 0
self.go(self.date)
QTimer.singleShot(0, lambda: self.view.verticalScrollBar().setValue(y))
self.restyled.emit(key)
return
if key in ("mode", "hide_menubar"):
date = self.date
self.look.__init__(self._mode(), self.cfg)
self._build()
self.go(date)
if self.prefs:
self.prefs.close()
self.prefs.deleteLater()
self.prefs = None
self.open_prefs()
self.restyled.emit(key)
elif key in ("sync_url", "sync_token"):
self.store.set_meta("seq", 0)
self.syncer.sync_now()
def restyle(self):
"""New grays or tint: repaint everything in place (Settings stays open)."""
app = QApplication.instance()
app.setPalette(self.look.palette())
app.setStyleSheet(self.look.qss())
self.restyled.emit("look")
y = self.view.verticalScrollBar().value() if self.view else 0
self.go(self.date)
QTimer.singleShot(0, lambda: self.view.verticalScrollBar().setValue(y))
self.update()
# ── window ──
def resizeEvent(self, e):
super().resizeEvent(e)
if hasattr(self, "overlay"):
self.overlay.setGeometry(self.rect())
if hasattr(self, "grips"):
place_grips(self, self.grips)
def paintEvent(self, _):
"""The window itself: a rounded tile in the background gray, the header band (title bar +
date) in its own, the soft emboss rims and the outline (frame.paint_tile, design.html#window)."""
p = QPainter(self)
paint_tile(p, self, self.look, self.header_bottom())
p.end()
def header_bottom(self):
"""Where the header band (title bar + date) ends, in window coordinates."""
hd = getattr(self.view, "header", None) if self.view else None
if hd is None:
return 0
return hd.mapTo(self, QPoint(0, hd.height())).y()
def changeEvent(self, e):
if e.type() == QEvent.Type.ActivationChange and hasattr(self, "titlebar"):
self.titlebar.update()
super().changeEvent(e)
def closeEvent(self, e):
for w in self.side.values(): # the History / Statistics / Journal windows go too
w.close()
if self.view:
self.view.flush()
self.cfg["window"] = [self.width(), self.height()]
self.cfg.pop("size", None) # the old key: its remembered shape is retired
paths.save_config(self.cfg)
self._last_push()
super().closeEvent(e)
def _last_push(self):
"""Best effort, so a tick made just before quitting reaches the R1."""
if not system.sync_supported():
return
dirty = self.store.dirty()
if not dirty or not self.cfg.get("sync_token") or not self.cfg.get("sync_url"):
return
try:
req = urllib.request.Request(self.cfg["sync_url"].rstrip("/") + "/sync",
json.dumps({"since": int(self.store.meta("seq", 0)), "days": [d for d, _ in dirty]}).encode(),
{"Authorization": "Bearer " + self.cfg["sync_token"],
"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=3).read()
for d, m in dirty:
self.store.mark_clean(d["date"], m)
except OSError:
pass
def app_icon():
"""The window (and, on a Mac, the Dock) icon. A Mac gets the .icns: its artwork is inset on
Apple's grid, so it sits right beside the other Dock icons; the SVG fills its square."""
if system.is_mac():
icns = QIcon(os.path.join(paths.SHARED, "icon.icns"))
if icns.availableSizes():
return icns
return QIcon(os.path.join(paths.SHARED, "icon.svg"))
def main():
crash.install(paths.LOGS) # an unhandled error is logged and shown, not fatal
system.cursor_env() # Linux (Wayland) only
system.mac_app_name("Routine") # macOS: "Routine" in the menu bar, not "Python"
QApplication.setApplicationName("Routine")
QApplication.setDesktopFileName(APP_ID)
app = QApplication(sys.argv)
crash.set_notify(crash.show_notice)
app.setWindowIcon(app_icon())
for f in sorted(os.listdir(os.path.join(paths.SHARED, "fonts"))): # bundled fonts (Caveat)
if f.endswith(".ttf"):
QFontDatabase.addApplicationFont(os.path.join(paths.SHARED, "fonts", f))
# one window: a second launch (say, the dash icon clicked again) shows the first
name = system.instance_name(paths._home)
sock = QLocalSocket()
sock.connectToServer(name)
if sock.waitForConnected(300):
sock.write(b"show")
sock.waitForBytesWritten(300)
return
server = QLocalServer()
QLocalServer.removeServer(name)
server.listen(name)
cfg = paths.load_config()
app.installEventFilter(TooltipFilter(cfg))
win = Window(cfg)
def raise_win():
c = server.nextPendingConnection()
if c:
c.readAll()
win.showNormal()
win.raise_()
win.activateWindow()
server.newConnection.connect(raise_win)
win.show()
sys.exit(app.exec())
+146
View File
@@ -0,0 +1,146 @@
"""Window chrome per design.html: own title bar (Wayland), Alt-tap menu bar, tooltip switch.
On macOS the system draws the title bar (system.native_frame): TitleBar stays hidden there, and
the menu bar is the Mac's own at the top of the screen (no Alt tap)."""
from routine.qt.QtCore import QEvent, QObject, QPointF, QRectF, Qt
from routine.qt.QtGui import QKeySequence, QPainter, QPen
from routine.qt.QtWidgets import QAbstractButton, QHBoxLayout, QLabel, QWidget
from routine import system
BUTTON = 24
def key_text(keys):
"""A shortcut as this platform writes it: Alt+Left on Linux, ⌥← on a Mac (for tooltips)."""
return QKeySequence(keys).toString(QKeySequence.SequenceFormat.NativeText)
def button_layout():
"""GNOME's button-layout, e.g. 'close,minimize:appmenu' -> (['close','minimize'], [])."""
out = system.gnome_setting("org.gnome.desktop.wm.preferences", "button-layout") or ":minimize,close"
left, _, right = out.partition(":")
known = ("close", "minimize", "maximize")
return [b for b in left.split(",") if b in known], [b for b in right.split(",") if b in known]
class RoundButton(QAbstractButton):
def __init__(self, kind, look):
super().__init__()
self.kind, self.look = kind, look
self.setFixedSize(BUTTON, BUTTON)
self.setToolTip({"close": "Close", "minimize": "Minimize", "maximize": "Maximize"}[kind])
self.setAccessibleName(self.toolTip())
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
def paintEvent(self, _):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
bg = self.look.bg
disc = bg.darker(135) if self.isDown() else bg.darker(122) if self.underMouse() else bg.darker(110)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(disc)
p.drawEllipse(QRectF(0, 0, BUTTON, BUTTON))
c = self.look.text if self.window().isActiveWindow() else self.look.mid
pen = QPen(c, 1.6)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
p.setPen(pen)
m = BUTTON / 2
if self.kind == "close":
p.drawLine(QPointF(m - 4, m - 4), QPointF(m + 4, m + 4))
p.drawLine(QPointF(m + 4, m - 4), QPointF(m - 4, m + 4))
elif self.kind == "minimize":
p.drawLine(QPointF(m - 4.5, m + 3.5), QPointF(m + 4.5, m + 3.5))
else:
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRect(QRectF(m - 4, m - 4, 8, 8))
class TitleBar(QWidget):
def __init__(self, window, look, title):
super().__init__(window)
self.win, self.look = window, look
native = system.native_frame()
h = 0 if native else max(34, self.fontMetrics().height() + 18)
self.setFixedHeight(h)
lay = QHBoxLayout(self)
lay.setContentsMargins(8, 0, 8, 0)
lay.setSpacing(8)
left, right = ([], []) if native else button_layout()
for k in left:
lay.addWidget(self._button(k))
lay.addStretch(1)
lay.addStretch(1)
for k in right:
lay.addWidget(self._button(k))
self.title = QLabel(title, self)
f = self.title.font()
f.setBold(True)
self.title.setFont(f)
self.title.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.title.setAlignment(Qt.AlignmentFlag.AlignCenter)
if native: # the system's title bar has the title and the buttons
self.setVisible(False)
def _button(self, kind):
b = RoundButton(kind, self.look)
b.clicked.connect({"close": self.win.close, "minimize": self.win.showMinimized,
"maximize": lambda: self.win.showNormal() if self.win.isMaximized()
else self.win.showMaximized()}[kind])
return b
def resizeEvent(self, e):
self.title.setGeometry(0, 0, self.width(), self.height()) # centred on the whole bar
def paintEvent(self, _):
p = QPainter(self)
# nothing to fill: the window paints the header band (rounded corners) under it; no line
active = self.window().isActiveWindow()
self.title.setStyleSheet("color: %s;" % (self.look.text if active else self.look.mid).name())
def mousePressEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton and self.win.windowHandle():
self.win.windowHandle().startSystemMove()
def mouseDoubleClickEvent(self, e):
self.win.showNormal() if self.win.isMaximized() else self.win.showMaximized()
class AltMenuFilter(QObject):
"""Tap Alt (press + release, nothing in between) to show/hide the menu bar."""
def __init__(self, window, menubar, enabled):
super().__init__(window)
self.win, self.bar, self.enabled = window, menubar, enabled
self.armed = False
def eventFilter(self, obj, ev):
t = ev.type()
if not self.enabled:
return False
if t == QEvent.Type.KeyPress:
self.armed = ev.key() == Qt.Key.Key_Alt and ev.modifiers() == Qt.KeyboardModifier.AltModifier
if ev.key() == Qt.Key.Key_Escape and self.bar.isVisible() and not self.bar.activeAction():
self.bar.hide()
elif t == QEvent.Type.KeyRelease and ev.key() == Qt.Key.Key_Alt:
if self.armed:
self.bar.setVisible(not self.bar.isVisible())
self.armed = False
elif t == QEvent.Type.MouseButtonPress:
self.armed = False
if not isinstance(obj, QWidget): # app-wide filter: Wayland sends presses to QWindows too
return False
if self.bar.isVisible() and not self.bar.activeAction() and not self.bar.isAncestorOf(obj) \
and obj is not self.bar:
self.bar.hide()
elif t == QEvent.Type.WindowDeactivate and obj is self.win:
self.armed = False
return False
class TooltipFilter(QObject):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
def eventFilter(self, obj, ev):
return ev.type() == QEvent.Type.ToolTip and not self.cfg.get("tooltips", True)
+153
View File
@@ -0,0 +1,153 @@
"""The date range the History, Statistics and Journal windows show: the range written big at the top
(the main window's date header: its font and size), and a row of tiles to pick it.
DateRange(look, cfg, key, get_today, get_first)
key: whose choice it is (remembered per window in cfg["ranges"][key])
get_today() -> date: the routine's today; get_first() -> ISO date: the first day recorded
.start, .end the range, ISO date strings (inclusive), never after today
.preset "30" | "90" | "year" | "all" | "custom"
changed(start, end) emitted when the range changes (a pick, a custom date, today moving on)
saved() emitted when the choice changed in cfg: save the config
refresh() re-work the range out from today (call when the day may have rolled over)
restyle() after a change of look: refit the header's font
"""
import datetime as dt
from routine.qt.QtCore import QDate, Signal
from routine.qt.QtWidgets import QDateEdit, QHBoxLayout, QLabel, QVBoxLayout, QWidget
from routine.gui.dayview import DateHeader
from routine.gui.prefs import tiles
PRESETS = [("30", "Last 30 days"), ("90", "Last 90 days"), ("year", "This year"), ("all", "All time"),
("custom", "From – to")]
def nice(look, d, year):
"""Sunday-less header style: November 8th (, 2026)."""
n = d.day
th = "th" if 11 <= n % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
return d.strftime("%B ") + str(n) + th + (d.strftime(", %Y") if year else "")
class DateRange(QWidget):
changed = Signal(str, str)
saved = Signal()
def __init__(self, look, cfg, key, get_today, get_first):
super().__init__()
self.look, self.cfg, self.key = look, cfg, key
self.get_today, self.get_first = get_today, get_first
mine = cfg.get("ranges", {}).get(key, {})
self.preset = mine.get("preset", "30") if mine.get("preset") in dict(PRESETS) else "30"
self.custom = (mine.get("from"), mine.get("to"))
col = QVBoxLayout(self)
col.setContentsMargins(0, 0, 0, 0)
col.setSpacing(2)
probe = QLabel("X")
probe.setFont(look.chrome_font(20))
probe.setContentsMargins(12, 8, 12, 8)
self.title = DateHeader(look, "", probe.sizeHint().height() * 2) # as tall as the main window's date
col.addWidget(self.title)
row = QHBoxLayout()
row.setContentsMargins(12, 0, 12, 0)
self.tiles = tiles(PRESETS, self.preset, self._pick)
row.addWidget(self.tiles)
self.custom_row = QWidget()
cr = QHBoxLayout(self.custom_row)
cr.setContentsMargins(8, 0, 0, 0)
self.from_edit, self.to_edit = QDateEdit(), QDateEdit()
for ed in (self.from_edit, self.to_edit):
ed.setCalendarPopup(True)
ed.setDisplayFormat("MMM d, yyyy")
cr.addWidget(self.from_edit)
cr.addWidget(QLabel("to"))
cr.addWidget(self.to_edit)
row.addWidget(self.custom_row)
row.addStretch(1)
col.addLayout(row)
self.from_edit.dateChanged.connect(self._custom_changed)
self.to_edit.dateChanged.connect(self._custom_changed)
self.start = self.end = ""
self._compute(emit=False)
# ── the range ──
def _compute(self, emit=True):
today = self.get_today()
first = dt.date.fromisoformat(self.get_first())
p = self.preset
if p == "30":
a, b = today - dt.timedelta(days=29), today
elif p == "90":
a, b = today - dt.timedelta(days=89), today
elif p == "year":
a, b = dt.date(today.year, 1, 1), today
elif p == "all":
a, b = first, today
else:
try:
a = dt.date.fromisoformat(self.custom[0])
b = dt.date.fromisoformat(self.custom[1])
except (TypeError, ValueError):
a, b = today - dt.timedelta(days=29), today
b = min(b, today)
a = min(a, b)
self._show_custom(a, b)
start, end = a.isoformat(), b.isoformat()
year = self.look.show_year or a.year != b.year or b.year != today.year
self.title.setText(nice(self.look, a, year) + " – " + nice(self.look, b, year) if a != b else
nice(self.look, a, year))
self.title._fit()
self.title.setToolTip(dict(PRESETS)[p])
if (start, end) != (self.start, self.end):
self.start, self.end = start, end
if emit:
self.changed.emit(start, end)
def _show_custom(self, a, b):
self.custom_row.setVisible(self.preset == "custom")
today = self.get_today()
for ed, v in ((self.from_edit, a), (self.to_edit, b)):
ed.blockSignals(True)
ed.setMaximumDate(QDate(today.year, today.month, today.day))
ed.setDate(QDate(v.year, v.month, v.day))
ed.blockSignals(False)
def _remember(self):
r = {"preset": self.preset}
if self.preset == "custom":
r["from"], r["to"] = self.custom
self.cfg.setdefault("ranges", {})[self.key] = r
self.saved.emit()
def _pick(self, key):
self.preset = key
if key == "custom" and not self.custom[0]:
self.custom = (self.start, self.end) # start from what was showing
self._remember()
self._compute()
def _custom_changed(self, *_):
a = self.from_edit.date().toPyDate()
b = self.to_edit.date().toPyDate()
if a > b:
a, b = b, a
self.custom = (a.isoformat(), b.isoformat())
self._remember()
self._compute()
def set_range(self, start, end):
"""Show start..end as a custom range (e.g. a click in another view)."""
self.preset = "custom"
self.tiles.show("custom")
self.custom = (str(start), str(end))
self._remember()
self._compute()
def refresh(self):
self._compute()
def restyle(self):
self.title.look = self.look
self.title._fit()
self.title.update()
+526
View File
@@ -0,0 +1,526 @@
"""One day: the date fixed at the top, block headers and a row per task scrolling in the middle
(the tasks area, its own gray), and the day's note fixed at the bottom."""
import datetime as dt
from routine.qt.QtCore import QPoint, QRectF, QSize, QTimer, Qt, Signal
from routine.qt.QtGui import QColor, QFontMetricsF, QPainter, QPainterPath, QPen
from routine.qt.QtWidgets import (QAbstractButton, QFrame, QHBoxLayout, QLabel, QMessageBox, QPlainTextEdit, QPushButton,
QScrollArea, QSizePolicy, QVBoxLayout, QWidget)
from routine import model
from routine.gui.look import display_font, paint_emboss
INDENT = 26
HIDE_AFTER_MS = 1000 # a ticked row leaves the INCOMPLETE list once its animation is over
PAST_TICK = "this is for a day in the past, you sure you want to check that off?"
def hour_label(h):
h %= 24
return "%d %s" % (12 if h % 12 == 0 else h % 12, "am" if h < 12 else "pm")
def now_target(blocks, now, day_starts_at):
"""Where » scrolls: the latest block that has started by now (so after the last block, until
the day rolls over, the last one; between blocks, the one just gone), else the first."""
h = now.hour + now.minute / 60
if h < day_starts_at:
h += 24
best, best_start = None, None
for i, b in enumerate(blocks):
start = b["start"] + (24 if b["start"] < day_starts_at else 0)
if start <= h and (best_start is None or start >= best_start):
best, best_start = i, start
return best if best is not None else (0 if blocks else None)
def current_block(blocks, now, day_starts_at):
"""Index of the block the clock is in, or None before the first block starts."""
h = now.hour + now.minute / 60
if h < day_starts_at:
h += 24
for i, b in enumerate(blocks):
start, end = b["start"], b["end"]
if end <= start:
end += 24
if start <= h < end:
return i
return None
class Box(QAbstractButton):
"""The checkbox: an embossed 22 px square; done = a check in the highlight color."""
def __init__(self, look):
super().__init__()
self.look = look
self.state = model.PENDING
self.setFixedSize(26, 26)
self.setFocusPolicy(Qt.FocusPolicy.TabFocus)
def sizeHint(self):
return QSize(26, 26)
def paintEvent(self, _):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
lk = self.look
c = lk.button.darker(125) if self.isDown() else lk.button.darker(107) if self.underMouse() else lk.button
r = QRectF(2.5, 2.5, 21, 21)
paint_emboss(p, r, c, 4, sunk=self.isDown())
if self.hasFocus():
p.setPen(QPen(lk.highlight, 2))
p.drawRoundedRect(r.adjusted(-1.5, -1.5, 1.5, 1.5), 5, 5)
if self.state == model.DONE:
pen = QPen(lk.highlight, 3)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.setPen(pen)
path = QPainterPath()
path.moveTo(7, 13.5)
path.lineTo(11.5, 18)
path.lineTo(19.5, 8)
p.drawPath(path)
elif self.state == model.SKIPPED:
p.setPen(QPen(lk.mid, 2.2))
p.drawLine(8, 13, 18, 13)
class ItemRow(QWidget):
toggled = Signal(str, str, object) # item id, new state, the box (for the animation)
def __init__(self, look, item):
super().__init__()
self.look, self.item = look, item
self.state = model.PENDING
lay = QHBoxLayout(self)
lay.setContentsMargins(12 + item["depth"] * INDENT, 3, 8, 3)
lay.setSpacing(10)
self.box = Box(look)
self.box.setToolTip("Done")
self.box.clicked.connect(self._box)
self.label = QLabel(item["label"])
self.label.setWordWrap(True)
self.label.setFont(display_font(12.5 if item["depth"] == 0 else 11.5))
self.label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
self.hint = bool(item.get("hint"))
if self.hint: # suggestion text: no box, no skip, quieter words
lay.addSpacing(self.box.width())
f = self.label.font()
f.setItalic(True)
self.label.setFont(f)
self.label.setStyleSheet("color: %s;" % look.mid.name())
lay.addWidget(self.label, 1)
return
self.skip = QPushButton("skip")
self.skip.setProperty("flat", True)
self.skip.setToolTip("Skip: hide it without ticking it off")
self.skip.clicked.connect(self._skip)
lay.addWidget(self.box, 0, Qt.AlignmentFlag.AlignTop)
lay.addWidget(self.label, 1)
lay.addWidget(self.skip, 0, Qt.AlignmentFlag.AlignTop)
def set_state(self, s):
if self.hint:
return
self.state = s
self.box.state = s
self.box.setToolTip("Not done after all" if s == model.DONE else "Done")
self.skip.setText("unskip" if s == model.SKIPPED else "skip")
self.skip.setToolTip("Bring it back" if s == model.SKIPPED else "Skip: hide it without ticking it off")
f = self.label.font()
f.setStrikeOut(s == model.SKIPPED)
self.label.setFont(f)
col = self.look.mid if s != model.PENDING else self.look.text
self.label.setStyleSheet("color: %s;" % col.name())
self.box.update()
def _box(self):
new = model.PENDING if self.state == model.DONE else model.DONE
self.toggled.emit(self.item["id"], new, self.box if new == model.DONE else None)
def _skip(self):
self.toggled.emit(self.item["id"], model.PENDING if self.state == model.SKIPPED else model.SKIPPED, None)
class BlockHeader(QWidget):
"""A block's heading. Clicking it hides or shows the block's rows."""
clicked = Signal()
def __init__(self, look, block):
super().__init__()
self.look, self.block = look, block
self.now = False
lay = QHBoxLayout(self)
lay.setContentsMargins(34, 20, 12, 9) # a little taller than a row: a target
self.title = QLabel(block["label"])
self.title.setFont(display_font(16, bold=True))
self.hours = QLabel("%s – %s" % (hour_label(block["start"]), hour_label(block["end"])))
self.hours.setStyleSheet("color: %s;" % look.mid.name())
self.note = QLabel("")
self.note.setStyleSheet("color: %s;" % look.mid.name())
self.helper = QLabel("") # "click to hide", until it's been learned
self.helper.setStyleSheet("color: %s; font-style: italic;" % look.mid.name())
# one text baseline: bottom-align every label, then lift the smaller ones by the descent they lack
bottom = Qt.AlignmentFlag.AlignBottom
drop = QFontMetricsF(self.title.font()).descent()
for w in (self.hours, self.helper, self.note):
w.setContentsMargins(0, 0, 0, max(0, round(drop - QFontMetricsF(w.font()).descent())))
lay.addWidget(self.title, 0, bottom)
lay.addWidget(self.hours, 0, bottom)
lay.addStretch(1)
lay.addWidget(self.helper, 0, bottom)
lay.addWidget(self.note, 0, bottom)
self.hovered = self.pressed = False
def _state(self, hovered=None, pressed=None):
self.hovered = self.hovered if hovered is None else hovered
self.pressed = self.pressed if pressed is None else pressed
self.update()
if self.look.block_style == "block" and self.parentWidget():
self.parentWidget().update() # the whole block is this heading's face
def face(self, c):
"""The block colour as a button face: darker on hover, more when pressed (design.html#states)."""
return c.darker(125) if self.pressed else c.darker(107) if self.hovered else c
def enterEvent(self, e):
self._state(hovered=True)
def leaveEvent(self, e):
self._state(hovered=False, pressed=False)
def mousePressEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton:
self._state(pressed=True)
def mouseReleaseEvent(self, e):
was = self.pressed
self._state(pressed=False)
if was and e.button() == Qt.MouseButton.LeftButton and self.rect().contains(e.position().toPoint()):
self.clicked.emit()
def set_now(self, now):
self.now = now
self.note.setText("now" if now and self.look.show_now else "")
self.note.setStyleSheet("color: %s; font-weight: bold;" % (self.look.highlight.name() if now
else self.look.mid.name()))
self.update()
def paintEvent(self, _):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
style = self.look.block_style
emboss = self.look.emboss_blocks
if style == "heading": # the heading row in the block's colour
r = QRectF(6, 8, self.width() - 12, self.height() - 8)
fill = self.look.block_fill(self.block["color"])
if emboss:
paint_emboss(p, r.adjusted(0.5, 0.5, -0.5, -0.5), self.face(fill), 8, sunk=self.pressed,
outline=self.look.block_outline)
else:
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(fill)
p.drawRoundedRect(r, 8, 8)
elif style == "chip":
# the block's colour as a chip: flat like a picture, or (emboss_blocks) a little button
r = QRectF(12, 22 + (self.title.height() - 16) / 2, 14, 14)
if emboss:
paint_emboss(p, r, self.face(QColor(self.block["color"])), 4, sunk=self.pressed,
outline=self.look.block_outline)
else:
p.setPen(QPen(QColor(self.block["color"]).darker(135), 1))
p.setBrush(QColor(self.block["color"]))
p.drawRoundedRect(r, 4, 4)
class DateHeader(QLabel):
"""The date, as big as the header allows: its capitals fill most of the height, sitting at
the bottom with room above; smaller only when the window is too narrow for it."""
FILL = 0.6 # cap height as a share of the header's height
BOTTOM = 0.12 # baseline this share of the height above the bottom
def __init__(self, look, text, height):
super().__init__(text)
self.look = look
self.setFixedHeight(height)
self.setMinimumWidth(1)
self._fit()
@staticmethod
def _cap(f):
"""The capitals' real height, drawn (fonts' own capHeight figures can't be trusted)."""
return QFontMetricsF(f).tightBoundingRect("HEMT").height()
def _fit(self):
room = max(50, self.width() - 24)
pt = 30.0
pt *= self.height() * self.FILL / max(1.0, self._cap(self.look.chrome_font(pt)))
f = self.look.chrome_font(pt)
w = QFontMetricsF(f).horizontalAdvance(self.text())
if w > room:
f = self.look.chrome_font(pt * room / w)
self.setFont(f)
def resizeEvent(self, e):
super().resizeEvent(e)
self._fit()
def paintEvent(self, _):
"""On a fixed baseline: a little space below, the rest above (the font's room for
descenders doesn't count)."""
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.TextAntialiasing)
p.setFont(self.font())
p.setPen(self.palette().color(self.foregroundRole()))
p.drawText(QPoint(12, round(self.height() * (1 - self.BOTTOM))), self.text())
p.end()
class BlockBox(QWidget):
"""One block: its heading and rows; in the "whole block" style, all on the block's colour."""
def __init__(self, look, block):
super().__init__()
self.look, self.block = look, block
self.lay = QVBoxLayout(self)
whole = look.block_style == "block"
self.lay.setContentsMargins(0, 0, 0, 8 if whole else 0)
self.lay.setSpacing(0)
self.header = None # its BlockHeader, set by the day view
def paintEvent(self, _):
if self.look.block_style != "block":
return
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
r = QRectF(6, 8, self.width() - 12, self.height() - 8)
fill = self.look.block_fill(self.block["color"])
if self.look.emboss_blocks: # a tall button: its heading is what's pressed
h = self.header
paint_emboss(p, r.adjusted(0.5, 0.5, -0.5, -0.5), h.face(fill) if h else fill, 8,
sunk=bool(h and h.pressed), outline=self.look.block_outline)
return
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(fill)
p.drawRoundedRect(r, 8, 8)
class DayView(QWidget):
"""One day: date header, the scrolling tasks, the note."""
changed = Signal(dict) # the day record after an edit here
swipe = Signal(int) # -1 = an earlier day, +1 = a later one
prefs_changed = Signal() # a block was hidden/shown: save the config
def __init__(self, look, schedule, day, filter_, today, cfg=None):
super().__init__()
self.cfg = cfg if cfg is not None else {}
self.look, self.schedule, self.day, self.filter = look, schedule, day, filter_
self.is_today = day["date"] == today.isoformat()
self.player = None # (box, done_before, calm, streak) -> [(name, set)]: the overlay
self.streak_of = None # (day, item id) -> the streak ticking it there reaches
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
d = dt.date.fromisoformat(day["date"])
text = look.date_text(d)
probe = QLabel(text)
probe.setFont(look.chrome_font(20))
probe.setContentsMargins(12, 8, 12, 8)
title = self.header = DateHeader(look, text, probe.sizeHint().height() * 2) # twice the height it had
outer.addWidget(title) # the header: always in view
self.scroll = QScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.scroll.setFrameShape(QFrame.Shape.NoFrame)
body = self.body = QWidget()
body.setObjectName("scrollbody")
self.col = QVBoxLayout(body)
self.col.setContentsMargins(0, 0, 0, 16)
self.col.setSpacing(0)
self.rows, self.headers, self.block_rows = {}, [], []
self.hscroll = 0
colors = {b["id"]: b["color"] for b in schedule.get("blocks", [])}
self.flipped = set() # blocks opened/closed by hand in Completed: this view only
for b in day["blocks"]:
b = dict(b, color=colors.get(b["id"], b["color"])) # today's colour; the day's if since deleted
box = BlockBox(look, b)
h = BlockHeader(look, b)
h.clicked.connect(lambda bid=b["id"]: self._toggle_block(bid))
box.header = h
self.headers.append(h)
box.lay.addWidget(h)
rows = []
for it in b["items"]:
r = ItemRow(look, it)
r.toggled.connect(self._toggled)
self.rows[it["id"]] = r
rows.append(r)
box.lay.addWidget(r)
self.block_rows.append(rows)
self.col.addWidget(box)
self.col.addStretch(1)
self.scroll.setWidget(body)
outer.addWidget(self.scroll, 1)
lab = QLabel("notes")
lab.setFont(look.note_font(20))
lab.setContentsMargins(12, 10, 12, 6)
outer.addWidget(lab) # the note: always in view too
self.note = QPlainTextEdit()
self.note.setFixedHeight(110)
self.note.setPlainText(day["note"]["text"])
self.note.textChanged.connect(lambda: self.note_timer.start())
wrap = QWidget()
wl = QVBoxLayout(wrap)
wl.setContentsMargins(12, 0, 12, 0)
wl.addWidget(self.note)
outer.addWidget(wrap)
self.note_timer = QTimer(self, singleShot=True, interval=700, timeout=self._save_note)
self.hide_timer = QTimer(self, singleShot=True, interval=HIDE_AFTER_MS, timeout=self.apply_filter)
self.scroll.viewport().installEventFilter(self)
self.refresh(day)
self.mark_now()
# ── state ──
def refresh(self, day):
"""Show a (possibly remotely changed) record without losing what's being typed."""
self.day = day
for iid, r in self.rows.items():
r.set_state(model.state(day, iid))
if not self.note.hasFocus() and self.note.toPlainText() != day["note"]["text"]:
self.note.blockSignals(True)
self.note.setPlainText(day["note"]["text"])
self.note.blockSignals(False)
self.apply_filter()
def set_filter(self, f):
self.filter = f
self.apply_filter()
def _toggle_block(self, bid):
if self.filter == "completed": # Completed opens what got done: a click here is for now
self.flipped ^= {bid}
self.apply_filter()
return
hidden = set(self.cfg.get("hidden_blocks", []))
hidden ^= {bid}
self.cfg["hidden_blocks"] = sorted(hidden)
self.cfg["block_tap_learned"] = True # no more "click to hide / show" helpers
self.apply_filter()
self.prefs_changed.emit()
def apply_filter(self):
inc, comp = self.filter == "incomplete", self.filter == "completed"
done = {iid for iid, r in self.rows.items() if not r.hint and r.state == model.DONE}
has_done = {iid.rpartition("/")[0] for iid in done} # a done task keeps its parents in view
for iid in list(has_done):
while iid:
has_done.add(iid)
iid = iid.rpartition("/")[0]
hidden = set(self.cfg.get("hidden_blocks", []))
learned = self.cfg.get("block_tap_learned", False)
for h, rows in zip(self.headers, self.block_rows):
bid = h.block["id"]
gone = bid in hidden
left, got, shown = 0, 0, {}
for r in rows:
iid = r.item["id"]
if r.hint: # a suggestion goes with the task it's under
par = iid.rpartition("/")[0]
show = shown.get(par, True)
else:
show = (iid in done or iid in has_done) if comp else not inc or r.state == model.PENDING
left += r.state == model.PENDING
got += r.state == model.DONE
shown[iid] = show
if comp: # open if anything got done, closed if not; clicks flip it
gone = (not got) != (bid in self.flipped)
if not got: # a none-done block opened: all of it
shown = dict.fromkeys(shown, True)
for r in rows:
r.setVisible(shown[r.item["id"]] and not gone)
h.helper.setText("" if learned or not rows else "click to show" if gone else "click to hide")
if not rows:
h.hours.setText(hour_label(h.block["start"]))
elif inc and left == 0:
h.hours.setText("all done")
else:
h.hours.setText("%s – %s" % (hour_label(h.block["start"]), hour_label(h.block["end"])))
def _past_ok(self):
"""Ticking on an earlier day: ask first. yes / oops (Escape = oops)."""
m = QMessageBox(QMessageBox.Icon.Question, "Routine", PAST_TICK, parent=self)
yes = m.addButton("yes", QMessageBox.ButtonRole.YesRole)
oops = m.addButton("oops", QMessageBox.ButtonRole.NoRole)
m.setDefaultButton(oops)
m.setEscapeButton(oops)
m.exec()
return m.clickedButton() is yes
def _toggled(self, iid, s, box):
if s == model.DONE and not self.is_today and not self._past_ok():
return
done_before = model.ticks(self.day)
for cid in model.set_with_children(self.day, iid, s):
self.rows[cid].set_state(model.state(self.day, cid))
if box is not None:
if self.player:
streak = 0
if self.streak_of and self.cfg.get("streak_anims", True):
streak = self.streak_of(self.day, iid)
for name, set_no in self.player(box, done_before, bool(self.rows[iid].item.get("calm")), streak):
model.add_play(self.day, name, iid, set_no,
streak if set_no in (model.STREAK_SET, model.STREAK_CALM_SET) else None)
self.hide_timer.start()
else:
self.apply_filter()
self.changed.emit(self.day)
def _save_note(self):
model.set_note(self.day, self.note.toPlainText())
self.changed.emit(self.day)
def flush(self):
if self.note_timer.isActive():
self.note_timer.stop()
self._save_note()
# ── now ──
def mark_now(self):
idx = current_block(self.day["blocks"], dt.datetime.now(), self.schedule.get("dayStartsAt", 4)) \
if self.is_today else None
for i, h in enumerate(self.headers):
h.set_now(i == idx)
return idx
def verticalScrollBar(self):
return self.scroll.verticalScrollBar()
def scroll_to_now(self):
self.mark_now()
idx = now_target(self.day["blocks"], dt.datetime.now(), self.schedule.get("dayStartsAt", 4)) \
if self.is_today else None
if idx is None:
self.verticalScrollBar().setValue(0)
else:
QTimer.singleShot(0, lambda: self.verticalScrollBar().setValue(
self.headers[idx].parentWidget().mapTo(self.body, QPoint(0, 0)).y()))
# ── sideways = other days ──
def eventFilter(self, obj, ev):
if ev.type() == ev.Type.Wheel:
dx = ev.angleDelta().x()
if dx and abs(dx) > abs(ev.angleDelta().y()):
self.hscroll += dx
if abs(self.hscroll) >= 240:
self.swipe.emit(-1 if self.hscroll > 0 else 1)
self.hscroll = 0
return True
return super().eventFilter(obj, ev)
+538
View File
@@ -0,0 +1,538 @@
"""The routine editor (Preferences → Routine): blocks and tasks, nested as deep as you like.
A tree on the left (blocks at the top level, tasks and sub-tasks under them) and a form on
the right for whatever is selected: blocks and tasks alike can be limited to some days of the
week, a task can be a suggestion (text under a task, with no checkbox) instead of a task, and a
task can be calm (ticking it plays one of the calm animations). ↑ ↓ carry a task over into the
block above or below when it's already at the top or bottom of its own. Every item keeps an explicit id, so renaming a task
keeps its history (moving one under a different parent starts a new history line); a new item gets one made from its name when the routine is saved.
Saving bumps the schedule's rev, which is what carries it to today's record and the R1.
"""
import copy
from routine.qt.QtCore import Qt, Signal
from routine.qt.QtGui import QColor, QIcon, QPixmap
from routine.qt.QtWidgets import (QCheckBox, QColorDialog, QComboBox, QFormLayout, QGroupBox, QHBoxLayout, QLabel,
QLineEdit, QMessageBox, QPushButton, QStackedWidget, QTreeWidget, QTreeWidgetItem,
QVBoxLayout, QWidget)
from routine import model
from routine.gui.dayview import hour_label
ROLE = Qt.ItemDataRole.UserRole
DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] # 0 = Sunday, as in schedule.json
def days_text(days):
""" "" for every day, else " (Mon Tue …)"."""
if days is None or len(days) == 7:
return ""
return " (" + (" ".join(DAYS[k] for k in sorted(days)) or "never") + ")"
class DayPicker(QWidget):
"""S M T W T F S: which days of the week something shows up on."""
changed = Signal()
def __init__(self):
super().__init__()
lay = QVBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
row = QHBoxLayout()
row.setContentsMargins(0, 0, 0, 0)
self.boxes = []
for d in DAYS:
cb = QCheckBox(d)
cb.toggled.connect(self._toggled)
self.boxes.append(cb)
row.addWidget(cb)
row.addStretch(1)
lay.addLayout(row)
self.note = QLabel("")
lay.addWidget(self.note)
def set_days(self, days):
days = list(range(7)) if days is None else days
for k, cb in enumerate(self.boxes):
cb.blockSignals(True)
cb.setChecked(k in days)
cb.blockSignals(False)
self._note()
def days(self):
"""None = every day."""
days = [k for k, cb in enumerate(self.boxes) if cb.isChecked()]
return None if len(days) == 7 else days
def _note(self):
days = self.days()
self.note.setText("every day" if days is None else "never: tick at least one day" if not days
else "only on " + ", ".join(DAYS[k] for k in days))
def _toggled(self, *_):
self._note()
self.changed.emit()
def swatch(color, size=14):
pm = QPixmap(size, size)
pm.fill(QColor(color))
return QIcon(pm)
class RoutineEditor(QWidget):
saved = Signal(dict)
def __init__(self, get_schedule):
super().__init__()
self.get_schedule = get_schedule
self.dirty = False
self._loading = False
self.tree = QTreeWidget()
self.tree.setHeaderHidden(True)
self.tree.setMinimumWidth(300)
self.tree.currentItemChanged.connect(self._selected)
def btn(text, tip, fn, glyph=False):
b = QPushButton(text)
b.setToolTip(tip)
b.setAccessibleName(tip)
if glyph:
b.setProperty("glyph", True)
b.clicked.connect(fn)
return b
self.b_block = btn("Add block", "A new top-level block (Morning, Work, …)", self.add_block)
self.b_task = btn("Add task", "A new task after the selected one (or at the end of the selected block)",
self.add_task)
self.b_sub = btn("Add sub-task", "A new task nested under the selected one", self.add_sub)
self.b_del = btn("Delete", "Delete the selected block or task (and what's under it)", self.delete)
self.b_up = btn("↑", "Move up (from the top of a block, into the end of the block above)",
lambda: self.move(-1), True)
self.b_down = btn("↓", "Move down (from the bottom of a block, into the start of the block below)",
lambda: self.move(1), True)
self.b_out = btn("←", "Outdent: out of the task it's under", self.outdent, True)
self.b_in = btn("→", "Indent: under the task above it", self.indent, True)
moves = QWidget()
ml = QHBoxLayout(moves)
ml.setContentsMargins(0, 0, 0, 0)
ml.setSpacing(0)
for n, b in enumerate((self.b_up, self.b_down, self.b_out, self.b_in)):
b.setProperty("tile", "left" if n == 0 else "right" if n == 3 else "mid")
ml.addWidget(b)
row1 = QHBoxLayout()
for b in (self.b_block, self.b_task, self.b_sub):
row1.addWidget(b)
row1.addStretch(1)
row2 = QHBoxLayout()
row2.addWidget(moves)
row2.addStretch(1)
row2.addWidget(self.b_del)
# forms
self.forms = QStackedWidget()
self.forms.addWidget(QLabel("Pick a block or a task to edit it."))
bf = QGroupBox("Block")
f = QFormLayout(bf)
self.blk_name = QLineEdit()
self.blk_name.textEdited.connect(self._form_changed)
self.blk_start, self.blk_end = QComboBox(), QComboBox()
for c in (self.blk_start, self.blk_end):
for h in range(24):
c.addItem(hour_label(h), h)
c.currentIndexChanged.connect(self._form_changed)
self.blk_color = QPushButton("Colour…")
self.blk_color.clicked.connect(self._pick_color)
self.blk_days = DayPicker()
self.blk_days.setToolTip("The whole block, and everything in it, only shows up on these days")
self.blk_days.changed.connect(self._form_changed)
f.addRow("Name:", self.blk_name)
f.addRow("Starts:", self.blk_start)
f.addRow("Ends:", self.blk_end)
f.addRow("Colour:", self.blk_color)
f.addRow("On:", self.blk_days)
self.forms.addWidget(bf)
tf = QGroupBox("Task")
f2 = QFormLayout(tf)
self.task_name = QLineEdit()
self.task_name.textEdited.connect(self._form_changed)
f2.addRow("Name:", self.task_name)
self.task_days = DayPicker()
self.task_days.setToolTip("It, and what's under it, only shows up on these days")
self.task_days.changed.connect(self._form_changed)
f2.addRow("On:", self.task_days)
self.task_hint = QCheckBox("Just a suggestion: no checkbox")
self.task_hint.setToolTip("Shown as quiet text (an idea for how to do the task above it), "
"never ticked off or skipped")
self.task_hint.toggled.connect(self._form_changed)
f2.addRow("", self.task_hint)
self.task_calm = QCheckBox("Calm animation")
self.task_calm.setToolTip("Ticking it plays one of the quiet, slow calm animations instead "
"(it still counts toward the day's next set)")
self.task_calm.toggled.connect(self._form_changed)
f2.addRow("", self.task_calm)
self.forms.addWidget(tf)
# day start + save
self.day_start = QComboBox()
for h in range(0, 13):
self.day_start.addItem(hour_label(h), h)
self.day_start.currentIndexChanged.connect(lambda: self._touch())
self.status = QLabel("")
self.b_revert = QPushButton("Revert")
self.b_revert.setToolTip("Throw away the changes since the last save")
self.b_revert.clicked.connect(self.load)
self.b_save = QPushButton("Save routine")
self.b_save.clicked.connect(self.save)
right = QVBoxLayout()
right.addWidget(self.forms)
g = QGroupBox("The day")
gf = QFormLayout(g)
gf.addRow("New day starts at:", self.day_start)
gf.addRow(QLabel("Before then, it still counts as the night before."))
right.addWidget(g)
right.addStretch(1)
body = QHBoxLayout()
body.addWidget(self.tree, 3)
body.addLayout(right, 2)
foot = QHBoxLayout()
foot.addWidget(self.status, 1)
foot.addWidget(self.b_revert)
foot.addWidget(self.b_save)
col = QVBoxLayout(self)
col.setContentsMargins(0, 0, 0, 0)
col.addLayout(row1)
col.addLayout(row2)
col.addLayout(body, 1)
col.addLayout(foot)
self.load()
# ── loading / saving ──
def load(self):
self._loading = True
sch = self.get_schedule()
self.base = copy.deepcopy(sch)
self.tree.clear()
for b in sch["blocks"]:
data = {"kind": "block", "id": b["id"], "label": b["label"], "start": b["start"], "end": b["end"],
"color": b["color"], "days": b.get("days")}
it = self._make(data)
self.tree.addTopLevelItem(it)
self._load_items(it, b.get("items", []))
self.tree.expandAll()
self.day_start.setCurrentIndex(max(0, min(12, sch.get("dayStartsAt", 4))))
self._loading = False
self._set_dirty(False)
self._selected(self.tree.currentItem(), None)
def _load_items(self, parent, items):
seen = set()
for x in items:
iid = x.get("id", model.slug(x["label"]))
while iid in seen: # same rule as model._flatten
iid += "-2"
seen.add(iid)
data = {"kind": "item", "id": iid, "label": x["label"], "days": x.get("days"),
"hint": bool(x.get("hint")), "calm": bool(x.get("calm"))}
it = self._make(data)
parent.addChild(it)
self._load_items(it, x.get("items", []))
def _make(self, data):
it = QTreeWidgetItem([data["label"]])
it.setData(0, ROLE, data)
self._paint(it)
return it
def _paint(self, it):
d = it.data(0, ROLE)
if d["kind"] == "block":
f = it.font(0)
f.setBold(True)
it.setFont(0, f)
it.setIcon(0, swatch(d["color"]))
it.setText(0, "%s %s – %s%s" % (d["label"], hour_label(d["start"]), hour_label(d["end"]),
days_text(d.get("days"))))
else:
f = it.font(0)
f.setItalic(bool(d.get("hint")))
it.setFont(0, f)
it.setText(0, d["label"] + (" (suggestion)" if d.get("hint") else " (calm)" if d.get("calm") else "")
+ days_text(d.get("days")))
def _gather(self):
def unique(base, taken):
iid = base or "item"
while iid in taken:
iid += "-2"
taken.add(iid)
return iid
def items_of(parent):
out, taken = [], set()
kids = [parent.child(k) for k in range(parent.childCount())]
for k in kids: # keep existing ids first
if k.data(0, ROLE).get("id"):
taken.add(k.data(0, ROLE)["id"])
for k in kids:
d = k.data(0, ROLE)
iid = d.get("id") or unique(model.slug(d["label"]), taken)
x = {"id": iid, "label": d["label"]}
if d.get("days") is not None and len(d["days"]) < 7:
x["days"] = sorted(d["days"])
if d.get("hint"):
x["hint"] = True
elif d.get("calm"):
x["calm"] = True
sub = items_of(k)
if sub:
x["items"] = sub
out.append(x)
return out
blocks, taken = [], {self.tree.topLevelItem(k).data(0, ROLE).get("id") for k in range(self.tree.topLevelItemCount())}
taken.discard(None)
for k in range(self.tree.topLevelItemCount()):
it = self.tree.topLevelItem(k)
d = it.data(0, ROLE)
bid = d.get("id") or unique(model.slug(d["label"]), taken)
b = {"id": bid, "label": d["label"], "start": d["start"], "end": d["end"], "color": d["color"]}
if d.get("days") is not None and len(d["days"]) < 7:
b["days"] = sorted(d["days"])
b["items"] = items_of(it)
blocks.append(b)
sch = {k: v for k, v in self.base.items() if k not in ("blocks", "rev", "dayStartsAt")}
sch["rev"] = self.base.get("rev", 1) + 1
sch["dayStartsAt"] = self.day_start.currentData()
sch["blocks"] = blocks
return sch
def save(self):
if any(not it.data(0, ROLE)["label"].strip() for it in self._all()):
QMessageBox.warning(self, "Routine", "Every block and task needs a name.")
return
sch = self._gather()
self.saved.emit(sch)
self.load()
self.status.setText("Saved. Today's list has the new routine; the R1 gets it at its next sync.")
def _all(self):
out = []
def walk(it):
out.append(it)
for k in range(it.childCount()):
walk(it.child(k))
for k in range(self.tree.topLevelItemCount()):
walk(self.tree.topLevelItem(k))
return out
def _set_dirty(self, on):
self.dirty = on
self.b_save.setEnabled(on)
self.b_revert.setEnabled(on)
self.status.setText("Unsaved changes" if on else "")
def _touch(self):
if not self._loading:
self._set_dirty(True)
# ── selection and the forms ──
def _selected(self, cur, _prev):
self._loading = True
d = cur.data(0, ROLE) if cur else None
kind = d["kind"] if d else None
self.forms.setCurrentIndex({None: 0, "block": 1, "item": 2}[kind])
if kind == "block":
self.blk_name.setText(d["label"])
self.blk_start.setCurrentIndex(d["start"] % 24)
self.blk_end.setCurrentIndex(d["end"] % 24)
self.blk_color.setIcon(swatch(d["color"]))
self.blk_days.set_days(d.get("days"))
elif kind == "item":
self.task_name.setText(d["label"])
self.task_days.set_days(d.get("days"))
self.task_hint.setChecked(bool(d.get("hint")))
self.task_calm.setChecked(bool(d.get("calm")))
self.task_calm.setEnabled(not d.get("hint"))
self._loading = False
is_item = kind == "item"
self.b_task.setEnabled(cur is not None)
self.b_sub.setEnabled(cur is not None)
self.b_del.setEnabled(cur is not None)
self.b_up.setEnabled(cur is not None)
self.b_down.setEnabled(cur is not None)
par = cur.parent() if cur else None
self.b_out.setEnabled(is_item and par is not None and par.parent() is not None)
idx = par.indexOfChild(cur) if par else -1
self.b_in.setEnabled(is_item and idx > 0)
def _form_changed(self, *_):
if self._loading:
return
it = self.tree.currentItem()
if not it:
return
d = dict(it.data(0, ROLE))
if d["kind"] == "block":
d["label"] = self.blk_name.text()
d["start"] = self.blk_start.currentData()
d["end"] = self.blk_end.currentData()
d["days"] = self.blk_days.days()
else:
d["label"] = self.task_name.text()
d["days"] = self.task_days.days()
d["hint"] = self.task_hint.isChecked()
d["calm"] = self.task_calm.isChecked()
self.task_calm.setEnabled(not d["hint"]) # a suggestion is never ticked
it.setData(0, ROLE, d)
self._paint(it)
self._touch()
def _pick_color(self):
it = self.tree.currentItem()
if not it:
return
d = dict(it.data(0, ROLE))
c = QColorDialog.getColor(QColor(d["color"]), self, "Block colour",
QColorDialog.ColorDialogOption.DontUseNativeDialog) # GNOME's is very slow here
if c.isValid():
d["color"] = c.name().upper()
it.setData(0, ROLE, d)
self.blk_color.setIcon(swatch(d["color"]))
self._paint(it)
self._touch()
# ── tree edits ──
def _new_item(self, label="new task"):
return self._make({"kind": "item", "id": None, "label": label, "days": None, "hint": False, "calm": False})
def _select_new(self, it):
if it.parent():
it.parent().setExpanded(True)
self.tree.setCurrentItem(it)
self._touch()
name = self.task_name if it.data(0, ROLE)["kind"] == "item" else self.blk_name
name.setFocus()
name.selectAll()
def add_block(self):
cur = self.tree.currentItem()
top = cur
while top is not None and top.parent() is not None:
top = top.parent()
it = self._make({"kind": "block", "id": None, "label": "New block", "start": 12, "end": 13, "color": "#CCCCCC",
"days": None})
at = self.tree.indexOfTopLevelItem(top) + 1 if top else self.tree.topLevelItemCount()
self.tree.insertTopLevelItem(at, it)
self._select_new(it)
def add_task(self):
cur = self.tree.currentItem()
if not cur:
return
it = self._new_item()
if cur.data(0, ROLE)["kind"] == "block":
cur.addChild(it)
else:
par = cur.parent()
par.insertChild(par.indexOfChild(cur) + 1, it)
self._select_new(it)
def add_sub(self):
cur = self.tree.currentItem()
if not cur:
return
it = self._new_item("new sub-task" if cur.data(0, ROLE)["kind"] == "item" else "new task")
cur.addChild(it)
self._select_new(it)
def delete(self):
cur = self.tree.currentItem()
if not cur:
return
d = cur.data(0, ROLE)
n = len(self._subtree(cur)) - 1
what = ("the block “%s”" if d["kind"] == "block" else "“%s”") % d["label"]
if n or d["kind"] == "block":
msg = "Delete %s%s?" % (what, " and the %d task%s under it" % (n, "s" * (n != 1)) if n else "")
if QMessageBox.question(self, "Routine", msg + "\n\nPast days keep it in their history.") \
!= QMessageBox.StandardButton.Yes:
return
par = cur.parent()
if par:
par.removeChild(cur)
else:
self.tree.takeTopLevelItem(self.tree.indexOfTopLevelItem(cur))
self._touch()
def _subtree(self, it):
out = [it]
for k in range(it.childCount()):
out += self._subtree(it.child(k))
return out
def _take(self, it):
par = it.parent()
if par:
return par, par.indexOfChild(it), par.takeChild(par.indexOfChild(it))
i = self.tree.indexOfTopLevelItem(it)
return None, i, self.tree.takeTopLevelItem(i)
def _put(self, par, i, it):
if par:
par.insertChild(i, it)
else:
self.tree.insertTopLevelItem(i, it)
self._restore_expanded(it)
self.tree.setCurrentItem(it)
def _restore_expanded(self, it):
for x in self._subtree(it):
x.setExpanded(True)
def move(self, d):
cur = self.tree.currentItem()
if not cur:
return
par = cur.parent()
n = par.childCount() if par else self.tree.topLevelItemCount()
i = par.indexOfChild(cur) if par else self.tree.indexOfTopLevelItem(cur)
if par is not None and par.parent() is None and not 0 <= i + d < n:
# a task already at the top (bottom) of its block: into the block above (below)
b = self.tree.indexOfTopLevelItem(par) + d
if 0 <= b < self.tree.topLevelItemCount():
dest = self.tree.topLevelItem(b)
_, _, it = self._take(cur)
self._put(dest, dest.childCount() if d < 0 else 0, it)
dest.setExpanded(True)
self._touch()
return
par, i, it = self._take(cur)
j = max(0, min(n - 1, i + d))
self._put(par, j, it)
if j != i:
self._touch()
def indent(self):
cur = self.tree.currentItem()
par = cur.parent() if cur else None
if not par or par.indexOfChild(cur) == 0:
return
above = par.child(par.indexOfChild(cur) - 1)
_, _, it = self._take(cur)
self._put(above, above.childCount(), it)
above.setExpanded(True)
self._touch()
def outdent(self):
cur = self.tree.currentItem()
par = cur.parent() if cur else None
if not par or not par.parent():
return
gp = par.parent()
_, _, it = self._take(cur)
self._put(gp, gp.indexOfChild(par) + 1, it)
self._touch()
+251
View File
@@ -0,0 +1,251 @@
"""The window chrome every Routine window shares (design.html #window, #titlebar), and SideWindow:
the base of the History, Statistics and Journal windows.
On macOS (system.native_frame) the windows keep the system's frame and title bar instead: Qt
can't resize a frameless window there. own_frame(win) says which; with the system's frame,
paint_tile() paints only the background and the header band, and there are no grips.
paint_tile() paints a window as design.html#window says: one rounded tile (10 px; square when
maximized, fullscreen or tiled) in the background gray, the header band in its own gray, the soft
emboss rims (one ring per pixel, fading inward) and the outline. Grip / place_grips: the resize
strips along every side and corner.
SideWindow(main, key, title) is a frameless, translucent top-level window with its own title bar,
a header band and a body, restyled whenever the main window's look changes. A subclass fills
self.body (a QVBoxLayout) and overrides reload(); see history.py for the smallest example.
self.main the main Window self.store / self.cfg / self.look (the main window's)
self.today the routine's today (a date) self.schedule the routine now
self.range the DateRange control in the header (routine/gui/daterange.py)
self.header a QVBoxLayout in the header band, under the range: add header widgets here
self.days(start, end) the day documents in start..end (ISO strings or dates; None = open)
self.history() model.history over every day up to today, with the cheat-day
setting: cached, dropped when a day changes or the setting does
reload() called (debounced) once shown, when the range changes, when days change
(from the main window: a tick, a note, a sync, a new day), on cheat-day changes
restyle(key) called when the look or a setting changes; the default repaints. Override to
rebuild things that baked in colours or fonts (call super().restyle(key)).
The window remembers its size in cfg["side_windows"][key].
"""
from routine.qt.QtCore import QRectF, Qt, QTimer
from routine.qt.QtGui import QBrush, QColor, QGuiApplication, QLinearGradient, QPainter, QPainterPath, QPen, QSurfaceFormat
from routine.qt.QtWidgets import QVBoxLayout, QWidget
from routine import model, paths, system
from routine.gui.chrome import TitleBar
EDGE = 4 # the resize strips
RADIUS = 10 # the window's corners
CORNER = 14 # the corner resize grips' size
class Grip(QWidget):
"""A 4 px resize strip along an edge, with its own cursor (so nothing else inherits it)."""
def __init__(self, window, edges, shape):
super().__init__(window)
self.edges = edges
self.setCursor(shape)
def mousePressEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton and self.window().windowHandle():
self.window().windowHandle().startSystemResize(self.edges)
def own_frame(win):
"""True when the app draws this window's frame (Linux; and popups everywhere), False when the
system does (macOS)."""
return not system.native_frame() or win.windowType() == Qt.WindowType.Popup
def make_grips(win):
if not own_frame(win):
return []
E, C = Qt.Edge, Qt.CursorShape
return [Grip(win, E.LeftEdge, C.SizeHorCursor), Grip(win, E.RightEdge, C.SizeHorCursor),
Grip(win, E.TopEdge, C.SizeVerCursor), Grip(win, E.BottomEdge, C.SizeVerCursor),
Grip(win, E.LeftEdge | E.TopEdge, C.SizeFDiagCursor), Grip(win, E.RightEdge | E.TopEdge, C.SizeBDiagCursor),
Grip(win, E.LeftEdge | E.BottomEdge, C.SizeBDiagCursor), Grip(win, E.RightEdge | E.BottomEdge, C.SizeFDiagCursor)]
def place_grips(win, grips):
w, h, k = win.width(), win.height(), CORNER
for g, r in zip(grips, ((0, k, EDGE, h - 2 * k), (w - EDGE, k, EDGE, h - 2 * k), (k, 0, w - 2 * k, EDGE),
(k, h - EDGE, w - 2 * k, EDGE), (0, 0, k, k), (w - k, 0, k, k), (0, h - k, k, k),
(w - k, h - k, k, k))):
g.setGeometry(*r)
g.raise_()
def square_corners(win):
"""Maximized, fullscreen, or tiled (Qt doesn't say: within 64 px of the screen's full height)."""
if win.isMaximized() or win.isFullScreen():
return True
scr = win.screen() or QGuiApplication.primaryScreen()
return bool(scr) and win.height() >= scr.geometry().height() - 64
def make_translucent(win):
"""Frameless and see-through, with an alpha channel on the native surface (design.html#window:
black corners otherwise). Call in the constructor, before the window can be shown. Does
nothing where the system draws the frame (own_frame)."""
if not own_frame(win):
return
win.setWindowFlag(Qt.WindowType.FramelessWindowHint)
win.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
h = win.windowHandle()
if h is not None and h.format().alphaBufferSize() < 8:
f = QSurfaceFormat(h.format())
f.setAlphaBufferSize(8)
h.setFormat(f)
win.destroy()
win.create()
def paint_tile(p, win, look, head):
"""The window's tile, header band (down to y = head; 0 = none), rims and outline."""
p.setRenderHint(QPainter.RenderHint.Antialiasing)
if not own_frame(win): # the system's frame: just the surfaces
p.fillRect(win.rect(), look.bg)
if head:
p.fillRect(0, 0, win.width(), head, look.header)
return
r = 0 if square_corners(win) else RADIUS
full = QRectF(win.rect())
path = QPainterPath()
path.addRoundedRect(full.adjusted(0.5, 0.5, -0.5, -0.5), r, r)
p.fillPath(path, look.bg)
if head:
band = QPainterPath()
band.addRect(QRectF(0, 0, win.width(), head))
p.fillPath(path.intersected(band), look.header)
# the soft emboss: a 2.5 px band just inside the outline, one ring per whole pixel (strength
# 1, 0.6, 0.2 going in), light at the top fading by 6 %, dark at the bottom from 94 %
for inset, width, strength in ((1.5, 1.0, 1.0), (2.5, 1.0, 0.6), (3.25, 0.5, 0.2)):
g = QLinearGradient(0, 0, 0, win.height())
top, bot = QColor(look.header.lighter(112)), QColor(look.bg.darker(112))
top.setAlphaF(strength)
bot.setAlphaF(strength)
g.setColorAt(0, top)
g.setColorAt(0.06, QColor(255, 255, 255, 0))
g.setColorAt(0.94, QColor(0, 0, 0, 0))
g.setColorAt(1, bot)
ring = QPainterPath()
ring.addRoundedRect(full.adjusted(inset, inset, -inset, -inset), max(0.0, r - inset + 0.5), max(0.0, r - inset + 0.5))
p.setPen(QPen(QBrush(g), width))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawPath(ring)
p.setPen(QPen(look.bg.darker(128), 1)) # outline
p.drawPath(path)
class SideWindow(QWidget):
SIZE = (720, 640) # the first size (then remembered)
def __init__(self, main, key, title):
super().__init__(None) # a window of its own: not kept above the main one
self.main, self.key = main, key
self.cfg, self.store = main.cfg, main.store
make_translucent(self)
self.setWindowTitle("Routine – " + title)
col = QVBoxLayout(self)
col.setContentsMargins(EDGE, 0, EDGE, EDGE)
col.setSpacing(0)
self.titlebar = TitleBar(self, self.look, title)
col.addWidget(self.titlebar)
self.head = QWidget() # the header band: the range, then extras
self.header = QVBoxLayout(self.head)
self.header.setContentsMargins(0, 0, 0, 6)
self.header.setSpacing(4)
from routine.gui.daterange import DateRange
self.range = DateRange(self.look, self.cfg, key, lambda: self.today, self._first_date)
self.range.changed.connect(lambda *_: self.reload())
self.range.saved.connect(lambda: paths.save_config(self.cfg))
self.header.addWidget(self.range)
col.addWidget(self.head)
self.body = QVBoxLayout()
self.body.setContentsMargins(0, 0, 0, 0)
self.body.setSpacing(0)
col.addLayout(self.body, 1)
self.grips = make_grips(self)
size = self.cfg.get("side_windows", {}).get(key) or self.SIZE
self.resize(int(size[0]), int(size[1]))
self._history = None
self._reload = QTimer(self, singleShot=True, interval=250, timeout=self.reload)
main.days_changed.connect(self._days_changed)
main.restyled.connect(self._restyled)
self._loaded = False
# ── the data ──
@property
def look(self):
return self.main.look
@property
def today(self):
return self.main.today
@property
def schedule(self):
return self.main.schedule
def _first_date(self):
return self.store.meta("first_date") or self.today.isoformat()
def days(self, start=None, end=None):
return self.store.range(start, end)
def history(self):
if self._history is None:
today = self.today.isoformat()
self._history = model.history(self.store.range(None, today), today, paths.cheat_after(self.cfg))
return self._history
def reload(self):
"""Redraw for self.range.start / .end. Subclasses override this."""
def _days_changed(self, dates):
self._history = None
self.range.refresh() # "last 30 days" moves with today
if self.isVisible():
self._reload.start()
def _restyled(self, key):
if key in ("cheat_day", "cheat_after"):
self._history = None
if self.isVisible():
self._reload.start()
self.restyle(key)
def restyle(self, key):
self.range.restyle()
self.titlebar.update()
self.update()
# ── the window ──
def showEvent(self, e):
super().showEvent(e)
if not self._loaded:
self._loaded = True
self.reload()
def header_bottom(self):
return self.head.geometry().bottom() + 1
def resizeEvent(self, e):
super().resizeEvent(e)
place_grips(self, self.grips)
def paintEvent(self, _):
p = QPainter(self)
paint_tile(p, self, self.look, self.header_bottom())
p.end()
def changeEvent(self, e):
if e.type() == e.Type.ActivationChange:
self.titlebar.update()
super().changeEvent(e)
def closeEvent(self, e):
self.cfg.setdefault("side_windows", {})[self.key] = [self.width(), self.height()]
paths.save_config(self.cfg)
super().closeEvent(e)
File diff suppressed because it is too large Load Diff
+193
View File
@@ -0,0 +1,193 @@
"""The History window's data, without Qt: which columns, in what order, and what each one draws.
groups(schedule, days, hist, start, end) -> [Group]
days: the day documents in start..end. Every block / task that appears in the range (in a
day's snapshot, suggestions left out), ordered by the routine now (every weekday's items),
with ones since removed placed after the neighbour they last followed.
Group: .id .label .color .removed .streak (the block's Streak) .items [Col]
Col: .id .block .label .depth .removed .streak .path (its parents' labels, then its own)
dates_between(start, end) -> ISO dates newest first (row 0 = end)
Marks(streak, dates, levels=False): what a column draws, as row intervals (row 0 = dates[0];
rows -1 and len(dates) are the days just outside, so a streak can run off either edge)
.pills [(r0, r1)] done / cheat days of one streak in a row (r0 <= r1)
.bridges [(r0, r1)] off days inside a streak (not scheduled: the streak goes on)
.cheats [r] .misses [r] .opens [r]
.pale [(r0, r1)] blocks: days some (not all) of the tasks were done, outside a streak
.code(r) -> S_* (S_OFF for off days) .run(r) -> the Run row r is part of, or None
"""
import datetime as dt
from routine import model
class Col:
def __init__(self, iid, block, label, depth, removed, streak, path):
self.id, self.block, self.label, self.depth = iid, block, label, depth
self.removed, self.streak, self.path = removed, streak, path
class Group:
def __init__(self, bid, label, color, removed, streak):
self.id, self.label, self.color, self.removed, self.streak = bid, label, color, removed, streak
self.items = []
def merge_order(order, seq):
"""Add seq's ids missing from order (a list, changed in place): each right after the id it
follows in seq (the nearest earlier one already placed), or first if none is."""
have = set(order)
prev = None
for x in seq:
if x not in have:
at = order.index(prev) + 1 if prev is not None else 0
order.insert(at, x)
have.add(x)
prev = x
return order
def _schedule_items(block):
"""A schedule block's items on every weekday, merged in order: [(id, label, depth, hint)]."""
order, info = [], {}
for wd in range(7):
out = []
model._flatten(block.get("items", []), wd, block["id"], 0, out)
for it in out:
info.setdefault(it["id"], it)
merge_order(order, [it["id"] for it in out])
return order, info
def groups(schedule, days, hist, start, end):
now_blocks, now_items, labels, depth, color = [], {}, {}, {}, {}
in_now = set()
for b in schedule.get("blocks", []):
order, info = _schedule_items(b)
now_blocks.append(b["id"])
now_items[b["id"]] = [i for i in order if not info[i].get("hint")]
labels[b["id"]], color[b["id"]] = b["label"], b["color"]
in_now.add(b["id"])
for i in order:
labels[i], depth[i] = info[i]["label"], info[i].get("depth", 0)
in_now.add(i)
seen_items = {} # block id -> ids that appear in the range
block_order = list(now_blocks)
item_order = {k: list(v) for k, v in now_items.items()}
for day in sorted(days, key=lambda d: d["date"], reverse=True): # the newest says where
bseq = []
for b in day.get("blocks", []):
ids = [it["id"] for it in b.get("items", []) if not it.get("hint")]
labels.setdefault(b["id"], b["label"])
color.setdefault(b["id"], b["color"])
for it in b.get("items", []):
labels.setdefault(it["id"], it["label"])
depth.setdefault(it["id"], it.get("depth", 0))
if ids:
bseq.append(b["id"])
seen_items.setdefault(b["id"], set()).update(ids)
merge_order(item_order.setdefault(b["id"], []), [it["id"] for it in b.get("items", [])])
merge_order(block_order, bseq)
out = []
for bid in block_order:
seen = seen_items.get(bid)
if not seen:
continue
g = Group(bid, labels.get(bid, bid), color.get(bid, "#cccccc"), bid not in in_now, hist.blocks.get(bid))
for iid in item_order[bid]:
if iid not in seen:
continue
path, p = [], iid
while "/" in p:
path.insert(0, labels.get(p, p.rpartition("/")[2]))
p = p.rpartition("/")[0]
st = hist.items.get(iid)
g.items.append(Col(iid, bid, labels.get(iid, iid), depth.get(iid, 0), iid not in in_now, st,
[labels.get(bid, bid)] + path))
if g.items:
out.append(g)
return out
def dates_between(start, end):
a, b = dt.date.fromisoformat(str(start)), dt.date.fromisoformat(str(end))
return [(b - dt.timedelta(days=k)).isoformat() for k in range((b - a).days + 1)]
def _shift(date, k):
return (dt.date.fromisoformat(date) + dt.timedelta(days=k)).isoformat()
class Marks:
def __init__(self, streak, dates, levels=False):
self.streak, self.dates = streak, dates
n = len(dates)
self.pills, self.bridges, self.cheats, self.misses, self.opens, self.pale = [], [], [], [], [], []
self._codes, self._runs = {}, {}
if streak is None or not n:
return
ext = [_shift(dates[0], 1)] + list(dates) + [_shift(dates[-1], -1)] # rows -1 .. n
rows = {d: r - 1 for r, d in enumerate(ext)}
runrow = {} # row -> run index (done, cheat and bridged off days)
index = {id(run): k for k, run in enumerate(streak.runs)}
for run in streak.runs_in(ext[-1], ext[0]):
idx = index[id(run)]
a, b = max(run.start, ext[-1]), min(run.last(), ext[0])
for r in range(rows[b], rows[a] + 1):
runrow[r] = idx
st, lv = streak.status, streak.levels
cur, kind = None, None
for r, d in enumerate(ext, -1):
s = st.get(d, model.S_OFF)
if s != model.S_OFF:
self._codes[r] = s
run = runrow.get(r)
if run is not None:
self._runs[r] = run
if s == model.S_CHEAT:
self.cheats.append(r)
elif s == model.S_MISS and not (levels and lv.get(d) == model.LEVEL_SOME):
self.misses.append(r)
elif s == model.S_OPEN and not (levels and lv.get(d) == model.LEVEL_SOME):
self.opens.append(r)
if run is not None:
k = ("pill", run) if s in (model.S_DONE, model.S_CHEAT) else ("bridge", run)
elif levels and s in (model.S_MISS, model.S_OPEN) and lv.get(d) == model.LEVEL_SOME:
k = ("pale", None)
else:
k = None
if k != kind or cur is None:
if cur is not None and kind is not None:
self._close(kind, cur)
cur, kind = [r, r], k
else:
cur[1] = r
if cur is not None and kind is not None:
self._close(kind, cur)
def _close(self, kind, rr):
{"pill": self.pills, "bridge": self.bridges, "pale": self.pale}[kind[0]].append((rr[0], rr[1]))
def code(self, r):
return self._codes.get(r, model.S_OFF)
def run(self, r):
k = self._runs.get(r)
return self.streak.runs[k] if k is not None else None
def day_in_run(self, r):
"""Which done day of its streak row r is (counting from the streak's start), or 0."""
run = self.run(r)
if run is None:
return 0
date, n, d = self.dates_at(r), 0, run.start
st = self.streak.status
while d <= date:
n += st.get(d) == model.S_DONE
d = _shift(d, 1)
return n
def dates_at(self, r):
n = len(self.dates)
if 0 <= r < n:
return self.dates[r]
return _shift(self.dates[0], -r) if r < 0 else _shift(self.dates[-1], -(r - n + 1))
+447
View File
@@ -0,0 +1,447 @@
"""The Journal window (View → Journal, Ctrl+J): the days' notes over the chosen range, newest first,
read like a journal. Each entry: its date (the date header's font and style), a button with the %
of that day's tasks done (done / the day's tasks, suggestions left out) that opens a pop-up of what
got done, by block, and what didn't, below it; then the note, read-only, on the note's panel.
The tiles at the bottom (cfg "journal_all_days"): only the days with a note (the default), or every
day, a day without one saying so in the note title's font. Double-click an entry to open that day in
the main window; right-click to copy its note.
One QListView with a painting delegate, so years of days stay smooth (no widget per entry).
"""
import datetime as dt
from routine.qt.QtCore import QAbstractListModel, QModelIndex, QPoint, QRect, QRectF, QSize, Qt, Signal
from routine.qt.QtGui import QColor, QFontMetrics, QGuiApplication, QPainter
from routine.qt.QtWidgets import (QAbstractItemView, QApplication, QFrame, QHBoxLayout, QLabel, QListView, QMenu,
QPushButton, QScrollArea, QStyledItemDelegate, QToolTip, QVBoxLayout, QWidget)
from routine import model, paths, tally
from routine.gui.frame import EDGE, SideWindow, make_translucent, paint_tile
from routine.gui.look import display_font, paint_emboss
from routine.gui.prefs import tiles
BIGGER = 1.69 # the bottom bar's tiles, as the main window's
M = 12 # the side margins (the day view's)
DATE_PT = 23 # the entries' dates, in the header's font
NOTE_PAD = (10, 8) # the note text's padding inside its panel
def entry_date(look, date, today):
"""The header's style (Sunday, November 8th), with the year when it isn't this year's."""
d = dt.date.fromisoformat(date)
text = look.date_text(d)
if d.year != today.year and not look.show_year:
text += d.strftime(", %Y")
return text
def pct_label(e):
return "–" if e["pct"] is None else "%d %%" % round(e["pct"])
class Entries(QAbstractListModel):
"""The entries shown, newest first: {"date", "text", "done", "tasks", "pct", "day"}."""
def __init__(self):
super().__init__()
self.rows = []
def set_rows(self, rows):
self.beginResetModel()
self.rows = rows
self.endResetModel()
def rowCount(self, parent=QModelIndex()):
return 0 if parent.isValid() else len(self.rows)
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
return None # the painter reads .rows directly (a dict through
# QVariant costs a millisecond a call)
class EntryPainter(QStyledItemDelegate):
"""Lays out and paints one entry: the date and its % button on one line, the note under them."""
def __init__(self, win, view):
super().__init__(view)
self.win, self.view = win, view
self.cache = {}
self.restyle()
def restyle(self):
lk = self.win.look
self.date_font = lk.chrome_font(DATE_PT)
self.pct_font = display_font(11.5)
self.text_font = QApplication.font()
self.empty_font = lk.note_font(17)
self.cache.clear()
# ── geometry ──
def _line_h(self):
return max(QFontMetrics(self.date_font).height(), 28)
def _text_h(self, text, width):
fm = QFontMetrics(self.text_font)
r = fm.boundingRect(QRect(0, 0, max(10, width - 2 * NOTE_PAD[0]), 10 ** 6),
Qt.TextFlag.TextWordWrap | Qt.TextFlag.TextExpandTabs, text)
return r.height()
def layout(self, e, rect):
"""{"date", "pct", "panel" or "empty"}: QRects within rect (the entry's)."""
x, w = rect.x() + M, rect.width() - 2 * M
top = rect.y() + 14
lh = self._line_h()
fm = QFontMetrics(self.pct_font)
pw = fm.horizontalAdvance("100 %") + 22
out = {"date": QRect(x, top, w - pw - 8, lh), "pct": QRect(x + w - pw, top + (lh - 26) // 2, pw, 26)}
y = top + lh + 4
if e["text"]:
out["panel"] = QRect(x, y, w, self._text_h(e["text"], w) + 2 * NOTE_PAD[1])
else:
out["empty"] = QRect(x + 2, y - 4, w, QFontMetrics(self.empty_font).height())
return out
def sizeHint(self, option, index):
e = index.model().rows[index.row()]
w = self.view.viewport().width()
key = (e["date"], w)
if key not in self.cache:
lay = self.layout(e, QRect(0, 0, w, 0))
last = lay.get("panel") or lay["empty"]
self.cache[key] = last.bottom() + 1 + 6
return QSize(w, self.cache[key])
# ── painting ──
def paint(self, p, option, index):
e = index.model().rows[index.row()]
lk = self.win.look
lay = self.layout(e, option.rect)
p.save()
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setRenderHint(QPainter.RenderHint.TextAntialiasing)
p.setFont(self.date_font)
p.setPen(lk.text)
text = QFontMetrics(self.date_font).elidedText(entry_date(lk, e["date"], self.win.today),
Qt.TextElideMode.ElideRight, lay["date"].width())
p.drawText(lay["date"], Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, text)
# the % button (design.html#states: hover darker(107), held darker(125) and sunk)
r = QRectF(lay["pct"]).adjusted(0.5, 0.5, -0.5, -0.5)
hov = self.view.hover == (index.row(), "pct")
held = hov and self.view.held == index.row()
c = lk.button.darker(125) if held else lk.button.darker(107) if hov else lk.button
paint_emboss(p, r, c, 4, sunk=held)
p.setFont(self.pct_font)
p.setPen(lk.text if e["pct"] is not None else lk.mid)
p.drawText(r, Qt.AlignmentFlag.AlignCenter, pct_label(e))
if "panel" in lay: # the note, on the note's panel (debossed: it shows)
pr = QRectF(lay["panel"]).adjusted(0.5, 0.5, -0.5, -0.5)
paint_emboss(p, pr, lk.panel, 8, sunk=True, rim_px=62)
p.setFont(self.text_font)
p.setPen(lk.panel_text)
p.drawText(lay["panel"].adjusted(NOTE_PAD[0], NOTE_PAD[1], -NOTE_PAD[0], -NOTE_PAD[1]),
Qt.TextFlag.TextWordWrap | Qt.TextFlag.TextExpandTabs, e["text"])
else:
p.setFont(self.empty_font)
p.setPen(lk.mid)
p.drawText(lay["empty"], Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, "no note")
p.restore()
def helpEvent(self, ev, view, option, index):
e = index.model().rows[index.row()]
lay = self.layout(e, option.rect)
if lay["pct"].contains(ev.pos()):
tip = "%d of %d tasks done: click for the list" % (e["done"], e["tasks"]) if e["tasks"] else "No tasks that day"
else:
tip = "Double-click to open this day; right-click to copy its note"
QToolTip.showText(ev.globalPos(), tip, view)
return True
class JournalView(QListView):
"""The list: tracks the % button under the mouse, opens the pop-up on a click of it."""
pct_clicked = Signal(int, QPoint) # row, where to put the pop-up (global)
open_day = Signal(str)
copy_note = Signal(int)
def __init__(self):
super().__init__()
self.hover, self.held = None, None
self.setMouseTracking(True)
self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setResizeMode(QListView.ResizeMode.Adjust)
self.setFrameShape(QFrame.Shape.NoFrame)
self.verticalScrollBar().setSingleStep(24)
def _hit(self, pos):
idx = self.indexAt(pos)
if not idx.isValid():
return None, idx
lay = self.itemDelegate().layout(idx.model().rows[idx.row()], self.visualRect(idx))
return (idx.row(), "pct" if lay["pct"].contains(pos) else "entry"), idx
def _set_hover(self, h):
if h != self.hover:
self.hover = h
self.viewport().update()
def mouseMoveEvent(self, e):
self._set_hover(self._hit(e.position().toPoint())[0])
super().mouseMoveEvent(e)
def leaveEvent(self, e):
self._set_hover(None)
self.held = None
super().leaveEvent(e)
def mousePressEvent(self, e):
h, _ = self._hit(e.position().toPoint())
if e.button() == Qt.MouseButton.LeftButton and h and h[1] == "pct":
self.held = h[0]
self.viewport().update()
return
super().mousePressEvent(e)
def mouseReleaseEvent(self, e):
h, idx = self._hit(e.position().toPoint())
was, self.held = self.held, None
if was is not None:
self.viewport().update()
if h == (was, "pct"):
lay = self.itemDelegate().layout(idx.model().rows[idx.row()], self.visualRect(idx))
self.pct_clicked.emit(was, self.viewport().mapToGlobal(lay["pct"].bottomRight()))
return
super().mouseReleaseEvent(e)
def mouseDoubleClickEvent(self, e):
h, idx = self._hit(e.position().toPoint())
if h and h[1] == "entry":
self.open_day.emit(idx.model().rows[idx.row()]["date"])
return
if h and h[1] == "pct": # a quick second click on the button: no double-click
return
super().mouseDoubleClickEvent(e)
def contextMenuEvent(self, e):
idx = self.indexAt(e.pos())
if not idx.isValid() or not idx.model().rows[idx.row()]["text"]:
return
m = QMenu(self)
a = m.addAction("Copy note")
if m.exec(e.globalPos()) is a:
self.copy_note.emit(idx.row())
class DayPopup(QWidget):
"""What got done one day, by block; below a line, what didn't (quieter). Closes on a click outside."""
def __init__(self, win, e):
super().__init__(None, Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint)
self.look = win.look
make_translucent(self)
lk = self.look
today = win.today.isoformat()
got, rest = tally.day_lists(e["day"], today)
col = QVBoxLayout(self)
col.setContentsMargins(EDGE + 10, 10, EDGE + 4, EDGE + 6)
col.setSpacing(0)
self.head = QWidget()
hl = QVBoxLayout(self.head)
hl.setContentsMargins(2, 0, 6, 8)
hl.setSpacing(0)
title = QLabel(entry_date(lk, e["date"], win.today))
title.setFont(lk.chrome_font(19))
hl.addWidget(title)
sub = QLabel("%d of %d tasks done · %s" % (e["done"], e["tasks"], pct_label(e)) if e["tasks"] else "no tasks")
sub.setStyleSheet("color: %s;" % lk.mid.name())
hl.addWidget(sub)
col.addWidget(self.head)
scroll = self.scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
scroll.setFrameShape(QFrame.Shape.NoFrame)
scroll.setStyleSheet("QScrollArea, QWidget#popbody { background: transparent; }")
body = QWidget()
body.setObjectName("popbody")
bl = QVBoxLayout(body)
bl.setContentsMargins(2, 6, 10, 4)
bl.setSpacing(1)
colors = {b["id"]: b["color"] for b in win.schedule.get("blocks", [])}
if not got:
none = QLabel("nothing ticked")
none.setFont(lk.note_font(16))
none.setStyleSheet("color: %s;" % lk.mid.name())
bl.addWidget(none)
self._groups(bl, got, colors, quiet=False)
if rest:
line = QFrame()
line.setFixedHeight(1)
line.setStyleSheet("background: %s;" % lk.mid.name())
bl.addSpacing(10)
bl.addWidget(line)
open_ = e["date"] >= today
lab = QLabel("still to do" if open_ else "not done")
lab.setFont(lk.note_font(17))
lab.setStyleSheet("color: %s;" % lk.mid.name())
lab.setContentsMargins(0, 4, 0, 0)
bl.addWidget(lab)
self._groups(bl, rest, colors, quiet=True)
bl.addStretch(1)
scroll.setWidget(body)
col.addWidget(scroll, 1)
body.adjustSize()
want = self.head.sizeHint().height() + body.sizeHint().height() + 34
self.resize(330, max(160, min(440, want)))
def _groups(self, lay, groups, colors, quiet):
lk = self.look
for b, items in groups:
row = QHBoxLayout()
row.setContentsMargins(0, 8, 0, 2)
row.setSpacing(7)
chip = QLabel()
chip.setFixedSize(11, 11)
c = QColor(colors.get(b["id"], b["color"]))
chip.setStyleSheet("background: %s; border: 1px solid %s; border-radius: 3px;"
% (c.name(), c.darker(135).name()))
row.addWidget(chip, 0, Qt.AlignmentFlag.AlignVCenter)
name = QLabel(b["label"])
name.setFont(display_font(11.5, bold=True))
if quiet:
name.setStyleSheet("color: %s;" % lk.mid.name())
row.addWidget(name, 1)
lay.addLayout(row)
for it, s in items:
lab = QLabel(it["label"])
lab.setWordWrap(True)
f = display_font(10.5 if it.get("depth", 0) else 11)
f.setStrikeOut(s == model.SKIPPED)
lab.setFont(f)
lab.setContentsMargins(18 + 16 * it.get("depth", 0), 0, 0, 0)
if quiet:
lab.setStyleSheet("color: %s;" % lk.mid.name())
if s == model.SKIPPED:
lab.setToolTip("Skipped")
lay.addWidget(lab)
def place(self, at):
"""Under the button, its right edge at at.x(); kept on the screen."""
scr = QGuiApplication.screenAt(at) or QGuiApplication.primaryScreen()
x, y = at.x() - self.width() + 6, at.y() + 2
if scr is not None:
a = scr.availableGeometry()
if y + self.height() > a.bottom():
y = max(a.top(), at.y() - 30 - self.height())
x = max(a.left(), min(x, a.right() - self.width()))
self.move(x, y)
def paintEvent(self, _):
p = QPainter(self)
paint_tile(p, self, self.look, self.head.geometry().bottom() + 1)
p.end()
class JournalWindow(SideWindow):
SIZE = (560, 900)
def __init__(self, main):
super().__init__(main, "journal", "Journal")
self.popup = None
self.entries = Entries()
self.view = JournalView()
self.view.setModel(self.entries)
self.painter = EntryPainter(self, self.view)
self.view.setItemDelegate(self.painter)
self.view.pct_clicked.connect(self.open_popup)
self.view.open_day.connect(self._open_day)
self.view.copy_note.connect(lambda row: QApplication.clipboard().setText(self.entries.rows[row]["text"]))
self.body.addWidget(self.view, 1)
self.empty = QLabel("")
self.empty.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop)
self.empty.setContentsMargins(12, 60, 12, 12)
self.empty.setObjectName("scrollbody")
self.body.addWidget(self.empty, 1)
bar = QWidget()
bl = QHBoxLayout(bar)
bl.setContentsMargins(8, 4, 8, 3)
self.all_days = bool(self.cfg.get("journal_all_days", False))
self.mode_tiles = tiles([("notes", "With a note"), ("all", "Every day")],
"all" if self.all_days else "notes", self._pick)
self.mode_tiles.setToolTip("Only the days with a note, or every day in the range")
h = round(QPushButton("All").sizeHint().height() * BIGGER)
pt = QPushButton().font().pointSizeF() * 1.3
for b in self.mode_tiles.findChildren(QPushButton):
b.setFixedHeight(h)
b.setFont(display_font(pt))
bl.addWidget(self.mode_tiles)
bl.addStretch(1)
self.count = QLabel("")
bl.addWidget(self.count)
self.body.addWidget(bar)
self._style()
def _style(self):
lk = self.look
self.view.setStyleSheet("QListView { background: %s; border: none; }" % lk.tasks.name())
self.empty.setFont(lk.note_font(20))
self.empty.setStyleSheet("color: %s;" % lk.mid.name())
self.count.setStyleSheet("color: %s;" % lk.mid.name())
self.painter.restyle()
def restyle(self, key):
super().restyle(key)
self._style()
if self._loaded:
self.reload()
def _pick(self, key):
self.all_days = key == "all"
self.cfg["journal_all_days"] = self.all_days
paths.save_config(self.cfg)
self.reload()
def reload(self):
start, end = self.range.start, self.range.end
if not start:
return
y = self.view.verticalScrollBar().value()
today = self.today.isoformat()
rows = []
notes = 0
for day in reversed(self.days(start, end)):
text = day.get("note", {}).get("text", "").strip("\n")
has = bool(text.strip())
notes += has
if not has and not self.all_days:
continue
done, tasks, pct = tally.day_score(day, today)
rows.append({"date": day["date"], "text": text if has else "", "done": done, "tasks": tasks,
"pct": pct, "day": day})
self.painter.cache.clear()
self.entries.set_rows(rows)
self.view.verticalScrollBar().setValue(y)
self.view.setVisible(bool(rows))
self.empty.setVisible(not rows)
self.empty.setText("no notes in this range" if not self.all_days else "no days in this range")
self.count.setText("%d %s" % (notes, "note" if notes == 1 else "notes"))
def open_popup(self, row, at):
if self.popup is not None:
self.popup.close()
self.popup.deleteLater()
self.popup = DayPopup(self, self.entries.rows[row])
self.popup.place(at)
self.popup.show()
def _open_day(self, date):
m = self.main
if date in m.store.dates():
m.go(date, now=date == m.today.isoformat())
if m.isMinimized():
m.showNormal()
m.raise_()
m.activateWindow()
+299
View File
@@ -0,0 +1,299 @@
"""The house look (shared-resources design.html): user grays, emboss/deboss, scrollbars, fonts."""
from routine.qt.QtCore import QRect, QRectF, Qt
from routine.qt.QtGui import QColor, QFont, QLinearGradient, QPainter, QPainterPath, QPalette, QPen
from routine.qt.QtWidgets import QProxyStyle, QStyle, QStyleFactory
GRAYS = { # design.html#colors defaults, plus this app's own surface: the tasks area
"light": {"bg": 239, "b": 247, "np": 255, "npt": 0, "stripe": 247, "base": 255, "tasks": 247, "header": 239},
"dark": {"bg": 48, "b": 72, "np": 30, "npt": 225, "stripe": 40, "base": 32, "tasks": 58, "header": 48},
}
# The sliders in Settings → Appearance (Stripes is left out: nothing here is striped).
GRAY_ROWS = [("header", "Header (window bar, date)"), ("bg", "Background (note, buttons bar)"),
("tasks", "Tasks area"), ("b", "Buttons"),
("np", "Info panels (the note)"), ("npt", "Info panel text"), ("base", "Lists")]
TINT_DEFAULT = "#3584E4"
TEXT = {"light": "#000000", "dark": "#e6e6e6"}
GLYPH = {"light": "#4A4A4A", "dark": "#c8c8c8"}
MID = {"light": "#808080", "dark": "#909090"}
HIGHLIGHT = "#3584E4"
DISPLAY_FONTS = ["Century Gothic", "URW Gothic", "URW Gothic L", "URW Gothic Book", "TeX Gyre Adventor",
"Questrial", "Didact Gothic", "Jost", "Josefin Sans", "Poppins", "Futura", "Avant Garde",
"Montserrat", "Nunito Sans", "Nunito",
"Avenir Next", "Avenir"] # past design.html#font's chain: a Mac always has these
# (A Mac without Office has no Century Gothic and stops at Futura, which every Mac has.)
SCROLL_EXTENT = 14 # medium UI size
CHROME_FONT = "Edition" # the header (the date): a Settings choice
NOTE_FONT = "Caveat" # the note's title: a slightly rough handwritten script (shared/fonts, OFL)
BLOCK_STYLES = [("chip", "Swatch"), ("heading", "Heading row"), ("block", "Whole block")]
def gray(v):
return QColor(v, v, v)
def hexc(c):
return c.name()
def display_font(pt=None, bold=False):
f = QFont()
f.setFamilies(DISPLAY_FONTS)
if pt:
f.setPointSizeF(pt)
f.setBold(bold)
return f
def gray_value(cfg, mode, key):
"""A surface's 0..255 gray in mode: the user's, else the default."""
try:
return max(0, min(255, int(cfg.get("grays", {}).get(mode, {})[key])))
except (KeyError, TypeError, ValueError):
return GRAYS[mode][key]
def tint_of(cfg, mode):
"""(colour, level 0..1) of mode's tint; level 0 = none."""
t = cfg.get("tint", {}).get(mode, {})
c = QColor(str(t.get("color") or TINT_DEFAULT))
if not c.isValid():
c = QColor(TINT_DEFAULT)
try:
level = max(0.0, min(1.0, float(t.get("level") or 0) / 100))
except (TypeError, ValueError):
level = 0.0
return c, level
def tinted(v, color, level):
"""design.html#colors: the gray's lightness, with the tint's hue at level × its saturation."""
plain = gray(v)
if level <= 0:
return plain
h, s, _l, _a = color.getHslF()
if h < 0: # a gray tint has no hue
return plain
return QColor.fromHslF(h, s * level, plain.lightnessF())
class Look:
def __init__(self, mode, cfg=None):
self.mode = mode # "light" | "dark"
cfg = cfg or {}
tc, tl = tint_of(cfg, mode)
def surf(k):
return tinted(gray_value(cfg, mode, k), tc, tl)
self.bg, self.button, self.panel = surf("bg"), surf("b"), surf("np")
self.base, self.stripe, self.tasks = surf("base"), surf("stripe"), surf("tasks")
self.header = surf("header")
self.panel_text = gray(gray_value(cfg, mode, "npt")) # text is never tinted
self.text, self.glyph, self.mid = QColor(TEXT[mode]), QColor(GLYPH[mode]), QColor(MID[mode])
self.highlight = QColor(HIGHLIGHT)
self.chrome_family = cfg.get("chrome_font") or CHROME_FONT
self.note_family = cfg.get("note_font") or NOTE_FONT
self.block_style = cfg.get("block_style") if cfg.get("block_style") in dict(BLOCK_STYLES) else "chip"
self.show_year = bool(cfg.get("show_year", False))
self.emboss_blocks = bool(cfg.get("emboss_blocks", False))
self.show_now = bool(cfg.get("show_now", True))
# embossed block colours: their edge this many % darker than the colour (0 = no edge)
self.block_outline = 100 + int(cfg.get("block_outline", {}).get(mode, 0))
def date_text(self, d):
"""The date as the header shows it: Sunday, November 8th (, 2026)."""
n = d.day
th = "th" if 11 <= n % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
return d.strftime("%A, %B ") + str(n) + th + (d.strftime(", %Y") if self.show_year else "")
@staticmethod
def _font(family, pt):
f = QFont()
f.setFamilies([family] + DISPLAY_FONTS) # missing? fall back to the display fonts
f.setPointSizeF(pt)
return f
def chrome_font(self, pt):
"""The header's font (the date)."""
return self._font(self.chrome_family, pt)
def note_font(self, pt):
"""The note title's font."""
return self._font(self.note_family, pt)
def block_fill(self, color):
"""A block's colour as a background: as is in light mode; in dark, mostly the tasks gray
so light text stays readable."""
c = QColor(color)
if not self.dark:
return c
t, k = self.tasks, 0.35
return QColor(int(t.red() + (c.red() - t.red()) * k), int(t.green() + (c.green() - t.green()) * k),
int(t.blue() + (c.blue() - t.blue()) * k))
@property
def dark(self):
return self.mode == "dark"
def palette(self):
p = QPalette()
R = QPalette.ColorRole
for role, c in ((R.Window, self.bg), (R.Button, self.button), (R.Base, self.base),
(R.AlternateBase, self.stripe), (R.WindowText, self.text), (R.Text, self.text),
(R.ButtonText, self.text), (R.Highlight, self.highlight),
(R.HighlightedText, QColor("#ffffff")), (R.ToolTipBase, self.bg.lighter(130)),
(R.ToolTipText, self.text), (R.PlaceholderText, self.mid), (R.Mid, self.mid)):
p.setColor(role, c)
p.setColor(QPalette.ColorGroup.Disabled, R.Text, self.mid)
p.setColor(QPalette.ColorGroup.Disabled, R.ButtonText, self.mid)
return p
# ── gradients as QSS ──
@staticmethod
def emboss_qss(c):
return ("qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 %s, stop:0.08 %s, stop:0.5 %s, stop:0.92 %s, stop:1 %s)"
% (hexc(c.lighter(116)), hexc(c.lighter(103)), hexc(c), hexc(c.darker(103)), hexc(c.darker(116))))
@staticmethod
def deboss_qss(c):
return ("qlineargradient(x1:0,y1:0,x2:0,y2:1, stop:0 %s, stop:0.08 %s, stop:0.5 %s, stop:0.92 %s, stop:1 %s)"
% (hexc(c.darker(116)), hexc(c.darker(103)), hexc(c), hexc(c.lighter(103)), hexc(c.lighter(116))))
def qss(self):
b = self.button
hov, prs, sunk = b.darker(107), b.darker(125), b.darker(112)
np = self.panel
return f"""
QPushButton {{ color: {hexc(self.text)}; background: {self.emboss_qss(b)}; border: 1px solid {hexc(b.darker(135))};
border-bottom-color: {hexc(b.darker(155))}; border-radius: 4px; padding: 4px 12px; }}
QPushButton:hover {{ background: {self.emboss_qss(hov)}; }}
QPushButton:pressed {{ background: {self.deboss_qss(prs)}; border-top-color: {hexc(prs.darker(155))};
border-bottom-color: {hexc(prs.darker(135))}; }}
QPushButton:disabled {{ background: {hexc(b.lighter(104))}; border-color: {hexc(b.darker(112))}; color: {hexc(self.mid)}; }}
QPushButton[big="true"] {{ border-radius: 8px; }}
QPushButton[glyph="true"] {{ color: {hexc(self.glyph)}; }}
QPushButton[tile="left"] {{ border-top-right-radius: 0; border-bottom-right-radius: 0; }}
QPushButton[tile="right"] {{ border-top-left-radius: 0; border-bottom-left-radius: 0; border-left: none; }}
QPushButton[tile="mid"] {{ border-radius: 0; border-left: none; }}
QPushButton[chosen="true"] {{ background: {self.deboss_qss(sunk)}; border-top-color: {hexc(sunk.darker(155))};
border-bottom-color: {hexc(sunk.darker(135))}; }}
QPushButton[flat="true"] {{ background: transparent; border-color: transparent; color: {hexc(self.mid)}; padding: 2px 8px; }}
QPushButton[flat="true"]:hover {{ background: {self.emboss_qss(hov)}; border: 1px solid {hexc(b.darker(135))};
border-bottom-color: {hexc(b.darker(155))}; color: {hexc(self.text)}; }}
QPushButton[flat="true"]:pressed {{ background: {self.deboss_qss(prs)}; border: 1px solid {hexc(prs.darker(135))}; }}
QPlainTextEdit, QLineEdit {{ color: {hexc(self.panel_text)}; background: {hexc(np)}; border: 1px solid {hexc(np.darker(135))};
border-top-color: {hexc(np.darker(155))}; border-radius: 8px; padding: 6px; selection-background-color: {HIGHLIGHT}; }}
QLineEdit {{ border-radius: 4px; padding: 3px 6px; }}
QPlainTextEdit:focus, QLineEdit:focus {{ border-color: {HIGHLIGHT}; }}
QListWidget {{ background: {hexc(self.base)}; border: 1px solid {hexc(self.bg.darker(140).lighter(108))}; border-radius: 8px; }}
QMenuBar {{ background: {hexc(self.header)}; }}
QToolTip {{ color: {hexc(self.text)}; background: {hexc(self.bg.lighter(130))}; border: 1px solid {hexc(self.bg.darker(135))}; }}
QScrollArea {{ background: {hexc(self.tasks)}; border: none; }}
QWidget#scrollbody {{ background: {hexc(self.tasks)}; }}
"""
class HouseStyle(QProxyStyle):
"""Fusion, plus design.html#scrollbars: no arrows, click jumps, thumb drawn as a button."""
def __init__(self, look):
super().__init__(QStyleFactory.create("Fusion"))
self.look = look
def styleHint(self, hint, opt=None, widget=None, ret=None):
if hint == QStyle.StyleHint.SH_ScrollBar_LeftClickAbsolutePosition:
return 1
if hint == QStyle.StyleHint.SH_Slider_AbsoluteSetButtons: # design.html#sliders: click to jump
return Qt.MouseButton.LeftButton.value
if hint == QStyle.StyleHint.SH_ScrollBar_Transient:
return 0
return super().styleHint(hint, opt, widget, ret)
def pixelMetric(self, m, opt=None, widget=None):
if m == QStyle.PixelMetric.PM_ScrollBarExtent:
return SCROLL_EXTENT
if m == QStyle.PixelMetric.PM_ScrollBarSliderMin:
return 2 * SCROLL_EXTENT
if m in (QStyle.PixelMetric.PM_SliderThickness, QStyle.PixelMetric.PM_SliderControlThickness):
return 2 * super().pixelMetric(m, opt, widget) # design.html#sliders: double height
return super().pixelMetric(m, opt, widget)
def _slider(self, opt):
r = opt.rect
horiz = opt.orientation == Qt.Orientation.Horizontal
length = r.width() if horiz else r.height()
span = opt.maximum - opt.minimum
if span <= 0:
return QRect(r)
thumb = max(2 * SCROLL_EXTENT, int(length * opt.pageStep / (span + opt.pageStep)))
pos = QStyle.sliderPositionFromValue(opt.minimum, opt.maximum, opt.sliderPosition, length - thumb,
opt.upsideDown)
return QRect(r.x() + pos, r.y(), thumb, r.height()) if horiz else QRect(r.x(), r.y() + pos, r.width(), thumb)
def subControlRect(self, cc, opt, sc, widget=None):
if cc == QStyle.ComplexControl.CC_Slider and sc == QStyle.SubControl.SC_SliderGroove:
g = super().subControlRect(cc, opt, sc, widget)
c = g.center()
if opt.orientation == Qt.Orientation.Horizontal:
g.setHeight(g.height() * 2)
else:
g.setWidth(g.width() * 2)
g.moveCenter(c)
return g
if cc == QStyle.ComplexControl.CC_ScrollBar:
SC = QStyle.SubControl
if sc in (SC.SC_ScrollBarAddLine, SC.SC_ScrollBarSubLine, SC.SC_ScrollBarFirst, SC.SC_ScrollBarLast):
return QRect()
if sc == SC.SC_ScrollBarGroove:
return QRect(opt.rect)
s = self._slider(opt)
if sc == SC.SC_ScrollBarSlider:
return s
r = opt.rect
horiz = opt.orientation == Qt.Orientation.Horizontal
if sc == SC.SC_ScrollBarSubPage:
return QRect(r.x(), r.y(), s.x() - r.x(), r.height()) if horiz else \
QRect(r.x(), r.y(), r.width(), s.y() - r.y())
if sc == SC.SC_ScrollBarAddPage:
return QRect(s.right() + 1, r.y(), r.right() - s.right(), r.height()) if horiz else \
QRect(r.x(), s.bottom() + 1, r.width(), r.bottom() - s.bottom())
return super().subControlRect(cc, opt, sc, widget)
def drawComplexControl(self, cc, opt, p, widget=None):
if cc != QStyle.ComplexControl.CC_ScrollBar:
return super().drawComplexControl(cc, opt, p, widget)
lk = self.look
p.save()
p.setRenderHint(QPainter.RenderHint.Antialiasing, True)
p.fillRect(opt.rect, lk.bg.darker(104))
s = QRectF(self._slider(opt)).adjusted(1.5, 1.5, -1.5, -1.5)
sunk = bool(opt.state & QStyle.StateFlag.State_Sunken) and \
opt.activeSubControls & QStyle.SubControl.SC_ScrollBarSlider
hover = bool(opt.state & QStyle.StateFlag.State_MouseOver) and \
opt.activeSubControls & QStyle.SubControl.SC_ScrollBarSlider
c = lk.button.darker(125) if sunk else lk.button.darker(107) if hover else lk.button
paint_emboss(p, s, c, 4, sunk=bool(sunk))
p.restore()
def paint_emboss(p, r, c, radius, sunk=False, rim_px=26, outline=135):
"""A button face in r (QRectF). Rims sized like a rim_px-tall button however tall r is.
outline: how much darker than the face its 1 px edge is (a button's 135); 100 or less, none."""
g = QLinearGradient(r.topLeft(), r.bottomLeft())
h = max(1.0, r.height())
f = min(0.5, rim_px * 0.08 / h)
top, bot = (c.darker(116), c.lighter(116)) if sunk else (c.lighter(116), c.darker(116))
ftop, fbot = (c.darker(103), c.lighter(103)) if sunk else (c.lighter(103), c.darker(103))
g.setColorAt(0, top)
g.setColorAt(f, ftop)
g.setColorAt(min(0.5, f * 6), c)
g.setColorAt(max(0.5, 1 - f * 6), c)
g.setColorAt(1 - f, fbot)
g.setColorAt(1, bot)
path = QPainterPath()
path.addRoundedRect(r, radius, radius)
p.fillPath(path, g)
if outline > 100:
p.setPen(QPen(c.darker(outline), 1))
p.drawPath(path)
+197
View File
@@ -0,0 +1,197 @@
"""Plays a check-off animation (and its sound) out of the box that was just ticked.
A mouse-transparent layer over the whole window. Frames are held for 1/12 s each: the
choppiness is the point. Which animations can play depends on how many tasks the day
already has ticked (model.anim_set): each 5 ticks move on to the next set, picked
from purely at random (nothing remembers what has played, so repeats happen). Past the last set, the star plays as well.
A task marked calm plays one of the calm set instead (and never the star).
A tick that reaches a streak level (model.streak_level) plays one of that level's streak
animations instead (a calm task: a calm streak one), drawn with the streak number; a level with
none yet falls back to the nearest lower level that has some. A streak play also shows the
caption "<n> days!" (anim_paint.paint_caption) under the animation, or over it when that keeps it
bigger or nearer the box, from the frame its number first shows (caption_start) to the end; placement fits the animation and its caption together.
"""
import json
import os
import random
import subprocess
import time
from routine.qt.QtCore import QPoint, QTimer, QUrl, Qt
from routine.qt.QtWidgets import QWidget
from routine import model, paths, system
from routine.gui.anim_paint import bounds, caption_h, caption_place, caption_start, fit, paint_caption, paint_frame
UNIT = 22 # px per box size (the box is 22 px)
EDGE = 6 # an animation stays this far inside the window
class Sounds:
"""QSoundEffect when Qt Multimedia works here, otherwise pw-play / paplay (afplay on a Mac).
A fresh effect per play, deleted once it has finished: a QSoundEffect keeps its audio
stream open for as long as it lives, and after a suspend / resume (or an output change)
a long-lived stream can be left linked to nothing, so its sound plays silently. Qt
caches the decoded samples, so making a new one each time is cheap.
Qt's own PipeWire audio backend (the default since 6.10) is the one that strands its
streams, and it can hang a new process outright while listing the outputs; the pulse
backend, through pipewire-pulse, follows the output across wakes. Set before Qt
Multimedia loads (Linux only: system.audio_env); QT_AUDIO_BACKEND in the environment still wins.
On macOS Qt plays through CoreAudio; the fresh effect per play does the same job after a sleep.
"""
def __init__(self):
self.player = system.sound_player()
self.live = set() # effects playing now (kept from the GC)
system.audio_env()
try:
from routine.qt.QtMultimedia import QSoundEffect
self.QSoundEffect = QSoundEffect
except ImportError:
self.QSoundEffect = None
def play(self, name):
path = os.path.join(paths.SOUNDS, name)
if self.QSoundEffect is None:
self._spawn(path)
return
e = self.QSoundEffect()
e.setVolume(0.7)
self.live.add(e)
Status = e.Status
def on_status():
st = e.status()
if st == Status.Ready and not e.isPlaying():
QTimer.singleShot(0, e.play) # not from inside setSource's signal: that hangs
elif st == Status.Error:
self._spawn(path)
self._drop(e)
def on_playing():
if not e.isPlaying():
self._drop(e)
e.statusChanged.connect(on_status)
e.playingChanged.connect(on_playing)
e.setSource(QUrl.fromLocalFile(path))
def _drop(self, e):
if e in self.live:
self.live.discard(e)
e.deleteLater()
def _spawn(self, path):
if self.player:
subprocess.Popen([self.player, path],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
class AnimOverlay(QWidget):
def __init__(self, parent, cfg):
super().__init__(parent)
self.cfg = cfg
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)
with open(paths.ANIMATIONS) as f:
data = json.load(f)
self.fps, self.colors, self.anims = data["fps"], data["colors"], data["animations"]
self.star = data.get("star")
self.calm = data.get("calm") or []
self.sets = data.get("sets") or [len(self.anims)]
st = data.get("streak") or {}
self.streak_sets = st.get("sets") or []
self.streak_calm = st.get("calm") or []
self.playing = [] # [anim, t0, widget, last centre, streak number or None,
# (bounds incl. the caption, caption place) once worked out]
self.sounds = Sounds()
self.timer = QTimer(self, interval=1000 // self.fps, timeout=self._tick)
def streak_choices(self, level, calm=False):
"""The streak animations for a level index: its own, else the nearest lower level's that
has some (else the nearest higher); a calm task's: the calm streak ones. [] = none at all."""
if calm and self.streak_calm:
return self.streak_calm
sets = self.streak_sets
for k in list(range(min(level, len(sets) - 1), -1, -1)) + list(range(level + 1, len(sets))):
if sets[k]:
return sets[k]
return []
def play(self, box, done_before, calm=False, streak=0):
"""Play out of box; returns [(animation name, set number)] for the day's log.
streak: the streak this tick reached; a rewarded one plays a streak animation instead."""
level = model.streak_level(streak) if streak else None
pool = self.streak_choices(level, calm) if level is not None else []
number = None
if pool:
chosen = [random.choice(pool)]
set_no = model.STREAK_CALM_SET if calm and self.streak_calm else model.STREAK_SET
number = streak
elif calm and self.calm:
chosen, set_no = [random.choice(self.calm)], model.CALM_SET
else:
lo, hi, set_no, star = model.anim_set(done_before, self.sets)
chosen = [random.choice(self.anims[lo:hi])]
if star and self.star:
chosen.append(self.star)
now = time.monotonic()
for a in chosen:
self.playing.append([a, now, box, self._centre(box), number, None])
if self.cfg.get("sounds", True):
self.sounds.play(a["sound"])
self.raise_()
self.timer.start()
self.update()
return [(a["name"], set_no) for a in chosen]
def _centre(self, w):
return w.mapTo(self.window(), QPoint(w.width() // 2, w.height() // 2)) - self.pos()
def _tick(self):
now = time.monotonic()
self.playing = [p for p in self.playing if (now - p[1]) * self.fps < len(p[0]["frames"])]
if not self.playing:
self.timer.stop()
self.update()
def paintEvent(self, _):
from routine.qt.QtGui import QPainter
p = QPainter(self)
now = time.monotonic()
for item in self.playing:
a, t0, w, last, number, cap = item
i = int((now - t0) * self.fps)
if i >= len(a["frames"]):
continue
if w is not None and w.isVisible():
item[3] = last = self._centre(w)
key = "_bounds_%s" % number
b = a.get(key)
if b is None:
b = a[key] = bounds(a, number)
if number and cap is None: # the caption: under, or over if that fits it better
best = None
ch = a.get("_caption_h")
if ch is None:
ch = a["_caption_h"] = caption_h(a)
for above in (False, True):
cx, top, ub = caption_place(b, number, above, ch)
u, x, y = self._placed(ub, last)
score = (-u, abs(x - last.x()) + abs(y - last.y()))
if best is None or score < best[0]:
best = (score, (ub, (cx, top), ch, caption_start(a)))
cap = item[5] = best[1]
u, x, y = self._placed(cap[0] if cap else b, last)
paint_frame(p, a["frames"][i], self.colors[a["color"]], x, y, u, self.colors, number)
if cap:
paint_caption(p, number, self.colors[a["color"]], x, y, u, cap[1], i, cap[2], cap[3])
p.end()
def _placed(self, b, last):
"""(unit, x, y): bounds b drawn all in view, as near the box (last) as can be, smaller only if it must be."""
u = UNIT * min(1.0, (self.width() - 2 * EDGE) / max(1e-6, (b[2] - b[0]) * UNIT),
(self.height() - 2 * EDGE) / max(1e-6, (b[3] - b[1]) * UNIT))
return u, fit(last.x(), b[0] * u, b[2] * u, self.width(), EDGE), fit(last.y(), b[1] * u, b[3] * u, self.height(), EDGE)
+472
View File
@@ -0,0 +1,472 @@
"""Preferences, laid out like VLC's (design.html#prefs): categories left, the page right, Close."""
import os
import threading
import time
from routine.qt.QtCore import QObject, Qt, QTimer, Signal
from routine.qt.QtGui import QFont
from routine.qt.QtWidgets import (QButtonGroup, QCheckBox, QColorDialog, QDialog, QDialogButtonBox, QFileDialog, QFormLayout,
QGroupBox, QHBoxLayout, QLabel, QLineEdit, QListWidget, QMessageBox, QPushButton,
QFontComboBox, QScrollArea, QSlider, QSpinBox, QStackedWidget, QStyle, QToolButton, QVBoxLayout,
QWidget)
from routine import __version__, paths, r1, system
from routine.gui.editor import RoutineEditor, swatch
from routine.gui.look import BLOCK_STYLES, CHROME_FONT, GRAY_ROWS, NOTE_FONT, gray_value, tint_of
from routine.gui.tabs import MacTab, TabStrip
class _Relay(QObject):
text = Signal(str)
def _page(*groups):
body = QWidget()
col = QVBoxLayout(body)
for g in groups:
col.addWidget(g)
col.addStretch(1)
sa = QScrollArea()
sa.setWidgetResizable(True)
sa.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
sa.setWidget(body)
return sa
def _soon():
lab = QLabel(system.COMING_SOON)
f = lab.font()
f.setBold(True)
lab.setFont(f)
return lab
def tiles(options, current, on_pick):
"""A pick-one tile group: touching buttons, the chosen one sunk."""
row = QWidget()
lay = QHBoxLayout(row)
lay.setContentsMargins(0, 0, 0, 0)
lay.setSpacing(0)
btns = []
def show(key): # sink the tile for key, without telling anyone
for k, b in btns:
b.setProperty("chosen", k == key)
b.style().unpolish(b)
b.style().polish(b)
def pick(key):
show(key)
on_pick(key)
for n, (key, label) in enumerate(options):
b = QPushButton(label)
b.setProperty("tile", "left" if n == 0 else "right" if n == len(options) - 1 else "mid")
b.setProperty("chosen", key == current)
b.clicked.connect(lambda _=False, k=key: pick(k))
btns.append((key, b))
lay.addWidget(b)
lay.addStretch(1)
row.pick, row.show = pick, show
return row
class Preferences(QDialog):
def __init__(self, parent, cfg, syncer, on_change, get_schedule, on_schedule, mode="light", relocate=None):
super().__init__(parent)
self.cfg, self.syncer, self.on_change, self.relocate = cfg, syncer, on_change, relocate
self.setWindowTitle("Settings")
self.editor = RoutineEditor(get_schedule)
self.editor.saved.connect(on_schedule)
cats = QListWidget()
stack = QStackedWidget()
# Appearance
look = QGroupBox("Look")
f = QFormLayout(look)
f.addRow("Mode:", tiles([("system", "System"), ("light", "Light"), ("dark", "Dark")],
cfg.get("mode", "system"), lambda k: self._set("mode", k)))
def font_row(key, default, tip):
row = QHBoxLayout()
box = QFontComboBox()
box.setCurrentFont(QFont(cfg.get(key) or default))
box.setToolTip(tip)
box.currentFontChanged.connect(lambda font: self._set(key, font.family()))
dflt = QPushButton("Default")
dflt.setToolTip("Back to " + default)
dflt.clicked.connect(lambda: box.setCurrentFont(QFont(default)))
row.addWidget(box, 1)
row.addWidget(dflt)
return row, box
row, self.font_box = font_row("chrome_font", CHROME_FONT, "The date at the top")
f.addRow("Header font:", row)
row, self.note_font_box = font_row("note_font", NOTE_FONT, "The title above the day's note")
f.addRow("Note title font:", row)
f.addRow("Block colours:", tiles(BLOCK_STYLES, cfg.get("block_style", "chip"),
lambda k: self._set("block_style", k)))
year = QCheckBox("Show the year in the date")
year.setToolTip("Sunday, November 8th, 2026 instead of Sunday, November 8th (the R1 picks it up at install)")
year.setChecked(bool(cfg.get("show_year", False)))
year.toggled.connect(lambda on: self._set("show_year", on))
f.addRow("Date:", year)
emb = QCheckBox("Emboss the block colours")
emb.setToolTip("The swatch, heading row or whole block drawn as a button, lighter on top (desktop only)")
emb.setChecked(bool(cfg.get("emboss_blocks", False)))
emb.toggled.connect(lambda on: self._set("emboss_blocks", on))
f.addRow("", emb)
now = QCheckBox("Say \u201cnow\u201d on the current block")
now.setToolTip("The word beside the heading of the block the clock is in")
now.setChecked(bool(cfg.get("show_now", True)))
now.toggled.connect(lambda on: self._set("show_now", on))
f.addRow("", now)
beh = QGroupBox("Behaviour")
v = QVBoxLayout(beh)
toggles = [("sounds", "Play a sound with each check-off animation"), ("tooltips", "Show tooltips")]
if not system.global_menubar(): # a Mac's menu bar is always at the top of the screen
toggles.append(("hide_menubar", "Hide the menu bar until Alt is pressed"))
for key, label in toggles:
cb = QCheckBox(label)
cb.setChecked(bool(cfg.get(key, True)))
cb.toggled.connect(lambda on, k=key: self._set(k, on))
v.addWidget(cb)
v.addWidget(QLabel("Routine %s" % __version__))
colors = self._colors_group(mode)
# Streaks
streaks = QGroupBox("Streaks")
sv = QVBoxLayout(streaks)
sa = QCheckBox("Celebrate streaks with their own animations")
sa.setToolTip("Ticking a task that reaches a 7, 21, 42, 66, 100, 150, 254 or 365 day streak (then every "
"100 more) plays a streak animation instead")
sa.setChecked(bool(cfg.get("streak_anims", True)))
sa.toggled.connect(lambda on: self._set("streak_anims", on))
sv.addWidget(sa)
cheat_row = QHBoxLayout()
cheat = QCheckBox("Allow a cheat day after")
cheat.setToolTip("One missed day is forgiven, and the streak goes on, once you've earned it with this many "
"days in a row (one held at a time)")
cheat.setChecked(bool(cfg.get("cheat_day", True)))
self.cheat_n = QSpinBox()
self.cheat_n.setRange(1, 365)
self.cheat_n.setValue(int(cfg.get("cheat_after", 7) or 7))
self.cheat_n.setEnabled(cheat.isChecked())
self.cheat_n.setToolTip("Days in a row that earn a cheat day")
self.cheat_n.valueChanged.connect(lambda v: self._set("cheat_after", v))
cheat.toggled.connect(lambda on: (self.cheat_n.setEnabled(on), self._set("cheat_day", on)))
cheat_row.addWidget(cheat)
cheat_row.addWidget(self.cheat_n)
cheat_row.addWidget(QLabel("days in a row"))
cheat_row.addStretch(1)
sv.addLayout(cheat_row)
hist = QGroupBox("History")
hv = QVBoxLayout(hist)
emb_h = QCheckBox("Emboss the history dots")
emb_h.setToolTip("Draw each day's dot in View → History as a little button")
emb_h.setChecked(bool(cfg.get("emboss_history", True)))
emb_h.toggled.connect(lambda on: self._set("emboss_history", on))
hv.addWidget(emb_h)
# Sync
sync = QGroupBox("Sync server")
f2 = QFormLayout(sync)
self.url = QLineEdit(cfg.get("sync_url", ""))
self.url.setPlaceholderText("http://host:8070")
self.token = QLineEdit(cfg.get("sync_token", ""))
self.token.setEchoMode(QLineEdit.EchoMode.Password)
self.url.editingFinished.connect(lambda: self._set_if_changed("sync_url", self.url.text().strip()))
self.token.editingFinished.connect(lambda: self._set_if_changed("sync_token", self.token.text().strip()))
f2.addRow("Address:", self.url)
f2.addRow("Token:", self.token)
self.sync_status = QLabel(self._sync_text())
self.sync_status.setWordWrap(True)
now = QPushButton("Sync now")
now.clicked.connect(syncer.sync_now)
syncer.status.connect(self.sync_status.setText) # a bound slot: dropped when Settings is rebuilt
f2.addRow(self.sync_status)
f2.addRow(now)
hint = QLabel("Optional: keeps the desktop and the R1 in step through your own server/routine_server.py. "
"scripts/deploy-server.sh --token prints its token.")
hint.setWordWrap(True)
f2.addRow(hint)
# Rabbit R1
rab = QGroupBox("Rabbit R1")
v3 = QVBoxLayout(rab)
v3.addWidget(QLabel("Installs or updates Routine on the R1 over USB (adb),\n"
"and gives it the sync server's address and token. Its data is kept."))
self.r1_status = QLabel("")
self.r1_status.setWordWrap(True)
inst = QPushButton("Install / update on the R1")
inst.clicked.connect(self._install)
v3.addWidget(inst)
v3.addWidget(self.r1_status)
self.relay = _Relay()
self.relay.text.connect(self.r1_status.setText)
data = self._data_group()
if not system.sync_supported(): # shown, so it's clear what's coming, but off
for g in (sync, rab):
g.setEnabled(False)
sync_page, rab_page = _page(_soon(), sync), _page(_soon(), rab)
else:
sync_page, rab_page = _page(sync), _page(rab)
for name, page in (("Routine", self.editor), ("Appearance", _page(look, colors, beh)),
("Streaks", _page(streaks, hist)), ("Data", _page(data)), ("Sync", sync_page),
("Rabbit R1", rab_page)):
cats.addItem(name)
stack.addWidget(page)
cats.setFixedWidth(cats.sizeHintForColumn(0) + 32)
cats.currentRowChanged.connect(stack.setCurrentIndex)
cats.setCurrentRow(0)
split = QHBoxLayout()
split.addWidget(cats)
split.addWidget(stack, 1)
bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
bb.button(QDialogButtonBox.StandardButton.Close).setIcon(
self.style().standardIcon(QStyle.StandardPixmap.SP_DialogCloseButton))
bb.rejected.connect(self.reject)
col = QVBoxLayout(self)
col.addLayout(split, 1)
col.addWidget(bb)
self.resize(900, 600)
self.cats = cats
def _may_close(self):
"""Unsaved routine edits: save, discard, or stay. True = go ahead and close."""
if not self.editor.dirty:
return True
B = QMessageBox.StandardButton
r = QMessageBox.question(self, "Routine", "Save the changes to the routine?",
B.Save | B.Discard | B.Cancel, B.Save)
if r == B.Cancel:
return False
if r == B.Save:
self.editor.save()
else:
self.editor.load()
return True
def closeEvent(self, e): # the title bar's ×; QDialog's own would call reject()
if self._may_close():
e.accept()
else:
e.ignore()
def reject(self): # Close button and Escape
if self._may_close():
super().reject()
def _sync_text(self):
s = self.syncer
if s.last_error:
return s.last_error
if s.last_ok:
return "synced " + time.strftime("%H:%M:%S", time.localtime(s.last_ok))
return "not synced yet" if self.cfg.get("sync_token") else "not set up: fill in the address and token above"
# ── where the routine and the history are kept ──
def _data_group(self):
g = QGroupBox("Where your data is kept")
form = QFormLayout(g)
note = QLabel("Your routine (schedule.json) and your history (routine.db, every day's ticks and notes). "
"Choosing another folder moves the file there; nothing is overwritten without asking.")
note.setWordWrap(True)
form.addRow(note)
self.loc_fields = {}
for kind, label in (("schedule", "Routine:"), ("db", "History:")):
path = QLineEdit()
path.setReadOnly(True)
pick = QPushButton("Choose folder…")
pick.clicked.connect(lambda _=False, k=kind: self._pick_location(k))
dflt = QPushButton("Default")
dflt.setToolTip("Back to " + paths.DATA)
dflt.clicked.connect(lambda _=False, k=kind: self._move_to(k, None))
row = QHBoxLayout()
row.addWidget(path, 1)
row.addWidget(pick)
row.addWidget(dflt)
form.addRow(label, row)
self.loc_fields[kind] = (path, dflt)
self.loc_status = QLabel("")
self.loc_status.setWordWrap(True)
form.addRow(self.loc_status)
self._show_locations()
return g
def _show_locations(self):
for kind, (field, dflt) in self.loc_fields.items():
p = paths.schedule_path(self.cfg) if kind == "schedule" else paths.db_path(self.cfg)
field.setText(p)
field.setToolTip(p)
dflt.setEnabled(bool(self.cfg.get(kind + "_dir")))
def _pick_location(self, kind):
cur = paths.schedule_dir(self.cfg) if kind == "schedule" else paths.db_dir(self.cfg)
d = QFileDialog.getExistingDirectory(self, "Keep the %s in" % ("routine" if kind == "schedule" else "history"),
cur)
if d:
self._move_to(kind, d)
def _move_to(self, kind, folder):
if self.relocate is None:
return
if folder and os.path.abspath(folder) == os.path.abspath(paths.DATA):
folder = None # the default folder picked by hand: keep it as "default"
msg = self.relocate(kind, folder, self._ask_taken)
if msg is not None:
self.loc_status.setText(msg)
self._show_locations()
def _ask_taken(self, target, backup_name):
"""The folder already has a schedule.json / routine.db: "use", "replace" or None."""
name = os.path.basename(target)
box = QMessageBox(self)
box.setWindowTitle("Routine")
box.setIcon(QMessageBox.Icon.Question)
box.setText("There's already a %s in %s." % (name, os.path.dirname(target)))
box.setInformativeText("Use that one: switch to it (yours stays where it is, untouched).\n"
"Replace it with mine: move yours there (that one is kept beside it as %s)."
% backup_name)
use = box.addButton("Use that one", QMessageBox.ButtonRole.AcceptRole)
mine = box.addButton("Replace it with mine", QMessageBox.ButtonRole.DestructiveRole)
cancel = box.addButton(QMessageBox.StandardButton.Cancel)
box.setDefaultButton(cancel)
box.exec()
return {use: "use", mine: "replace"}.get(box.clickedButton())
# ── grays and tint (design.html#colors): light and dark each have a full set ──
def _colors_group(self, mode):
g = QGroupBox("Colours")
form = QFormLayout(g)
note = QLabel("Each gray runs black → white and shows straight away. The tint colours every gray "
"but text, by its level.")
note.setWordWrap(True)
form.addRow(note)
strip = TabStrip()
group = QButtonGroup(self)
self.editing = mode
tabs = {}
for which in ("light", "dark"):
t = MacTab(which.capitalize())
group.addButton(t)
strip.add(t)
tabs[which] = t
t.toggled.connect(lambda on, w=which: on and self._edit_colors_of(w))
form.addRow(strip)
row = QHBoxLayout()
self.tint_btn = QToolButton()
self.tint_btn.setAutoRaise(True)
self.tint_btn.setToolTip("Choose the tint colour")
self.tint_btn.setAccessibleName("Tint colour")
self.tint_btn.clicked.connect(self._choose_tint)
self.tint_level = QSlider(Qt.Orientation.Horizontal)
self.tint_level.setRange(0, 100)
self.tint_label = QLabel("")
self.tint_label.setMinimumWidth(40)
self.tint_level.valueChanged.connect(self._tint_level_changed)
row.addWidget(self.tint_btn)
row.addWidget(self.tint_level, 1)
row.addWidget(self.tint_label)
form.addRow("Tint:", row)
self.gray_sliders = {}
for key, label in GRAY_ROWS:
sl = QSlider(Qt.Orientation.Horizontal)
sl.setRange(0, 255)
sl.valueChanged.connect(lambda v, k=key: self._gray_changed(k, v))
self.gray_sliders[key] = sl
form.addRow(label + ":", sl)
row = QHBoxLayout()
self.outline = QSlider(Qt.Orientation.Horizontal)
self.outline.setRange(0, 55)
self.outline.setToolTip("How much darker than its colour an embossed block's edge is: 0 % none, "
"35 % a button's (Look → Emboss the block colours)")
self.outline_label = QLabel("")
self.outline_label.setMinimumWidth(40)
self.outline.valueChanged.connect(self._outline_changed)
row.addWidget(self.outline, 1)
row.addWidget(self.outline_label)
form.addRow("Block edge:", row)
reset = QPushButton("Default grays")
reset.setToolTip("Put this set's grays, tint and block edge back to the defaults")
reset.clicked.connect(self._reset_colors)
form.addRow(reset)
tabs[mode].setChecked(True)
strip.finish()
self.color_save = QTimer(self, singleShot=True, interval=400, timeout=lambda: self.on_change("look_saved"))
self._show_colors()
return g
def _edit_colors_of(self, which):
if which != self.editing:
self.editing = which
self._show_colors()
def _show_colors(self):
w = self.editing
for k, sl in self.gray_sliders.items():
sl.blockSignals(True)
sl.setValue(gray_value(self.cfg, w, k))
sl.blockSignals(False)
c, level = tint_of(self.cfg, w)
self.tint_btn.setIcon(swatch(c.name(), 18))
self.tint_level.blockSignals(True)
self.tint_level.setValue(round(level * 100))
self.tint_level.blockSignals(False)
self.tint_label.setText("%d %%" % round(level * 100))
v = int(self.cfg.get("block_outline", {}).get(w, 0))
self.outline.blockSignals(True)
self.outline.setValue(v)
self.outline.blockSignals(False)
self.outline_label.setText("%d %%" % v)
def _changed_colors(self):
self.on_change("look") # live preview; saved once the drag settles
self.color_save.start()
def _gray_changed(self, k, v):
self.cfg.setdefault("grays", {}).setdefault(self.editing, {})[k] = v
self._changed_colors()
def _tint_level_changed(self, v):
self.tint_label.setText("%d %%" % v)
self.cfg.setdefault("tint", {}).setdefault(self.editing, {})["level"] = v
self._changed_colors()
def _outline_changed(self, v):
self.outline_label.setText("%d %%" % v)
self.cfg.setdefault("block_outline", {})[self.editing] = v
self._changed_colors()
def _choose_tint(self):
cur, _ = tint_of(self.cfg, self.editing)
c = QColorDialog.getColor(cur, self, "Tint colour",
QColorDialog.ColorDialogOption.DontUseNativeDialog) # GNOME's is very slow here
if not c.isValid():
return
self.cfg.setdefault("tint", {}).setdefault(self.editing, {})["color"] = c.name()
if self.tint_level.value() == 0:
self.tint_level.setValue(20) # a tint at 0 % wouldn't show
self._show_colors()
self._changed_colors()
def _reset_colors(self):
self.cfg.get("grays", {}).pop(self.editing, None)
self.cfg.get("tint", {}).pop(self.editing, None)
self.cfg.get("block_outline", {}).pop(self.editing, None)
self._show_colors()
self._changed_colors()
def _set(self, k, v):
self.cfg[k] = v
self.on_change(k)
def _set_if_changed(self, k, v):
if self.cfg.get(k, "") != v: # leaving the field unchanged doesn't restart the sync
self._set(k, v)
def _install(self):
if not system.sync_supported(): # never reached (the button is off): no adb on a Mac
return
self.r1_status.setText("Working…")
threading.Thread(target=lambda: self.relay.text.emit(r1.install(self.cfg)), daemon=True).start()
+447
View File
@@ -0,0 +1,447 @@
"""The Statistics window (View → Statistics, Ctrl+T): the routine laid out as the main window lays
out a day (the same blocks, headings, colours and indents), read-only, with a figure per task where
the checkbox would be, and a statistics panel at the bottom where the note is.
The tiles at the bottom pick the figure (cfg "stats_metric"): % of the days it was on that it got
done, its longest streak in the range (with the cheat days that streak used, and the streak going
now), or the days it got done. Clicking a task selects it and the panel shows its details; click it
again (or Escape, or the empty space) and the panel sums up the range. Block headings hide their
tasks on a click, remembered in cfg "stats_hidden_blocks" (apart from the main window's).
Every figure respects the range at the top: model.Streak.totals / longest_run / runs_in.
"""
import datetime as dt
import html
from routine.qt.QtCore import QRectF, Qt, QTimer, Signal
from routine.qt.QtGui import QColor, QFontMetricsF, QPainter
from routine.qt.QtWidgets import (QFrame, QHBoxLayout, QLabel, QPushButton, QScrollArea, QSizePolicy, QTextBrowser,
QVBoxLayout, QWidget)
from routine import paths, tally
from routine.gui.dayview import INDENT, BlockBox, BlockHeader, hour_label
from routine.gui.frame import SideWindow
from routine.gui.look import display_font, paint_emboss
from routine.gui.prefs import tiles
METRICS = [("pct", "% of days"), ("longest", "Longest streak"), ("total", "Days done")]
BIGGER = 1.69 # the bottom bar's tiles, as the main window's
def short_date(d, today):
"""Mar 3 (, 2025 when it isn't this year)."""
d = dt.date.fromisoformat(str(d))
return d.strftime("%b ") + str(d.day) + (d.strftime(", %Y") if d.year != today.year else "")
def span(a, b, today):
"""Mar 3 – Apr 20 (, 2025: once, when both are in the same other year)."""
if a == b:
return short_date(a, today)
ya, yb = str(a)[:4], str(b)[:4]
if ya == yb and int(ya) != today.year:
return short_date(a, dt.date(int(ya), 1, 1)) + " – " + short_date(b, today)
return short_date(a, today) + " – " + short_date(b, today)
def plural(n, word):
return "%s %s" % ("{:,}".format(n), word if n == 1 else word + "s")
def pct_text(p):
return "–" if p is None else "%d %%" % round(p)
class Figure(QWidget):
"""The task's number, where the main window has its checkbox: a little debossed readout (it
shows, it doesn't do: design.html#principles)."""
def __init__(self, look, width):
super().__init__()
self.look, self.text = look, ""
self.setFixedSize(width, 26)
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.setFont(display_font(11.5, bold=True))
def paintEvent(self, _):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
paint_emboss(p, QRectF(0.5, 2.5, self.width() - 1, 21), self.look.panel, 4, sunk=True)
p.setPen(self.look.panel_text if self.text != "–" else self.look.mid)
p.setFont(self.font())
p.drawText(QRectF(0, 2, self.width() - 7, 22), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
self.text)
class StatRow(QWidget):
"""One task: its figure, its name (indented as in the day view), a quieter second figure."""
clicked = Signal(str)
def __init__(self, look, item, fig_width):
super().__init__()
self.look, self.item = look, item
self.selected = self.hovered = False
lay = QHBoxLayout(self)
lay.setContentsMargins(12 + item["depth"] * INDENT, 3, 14, 3)
lay.setSpacing(10)
self.fig = Figure(look, fig_width)
self.label = QLabel(item["label"])
self.label.setWordWrap(True)
f = display_font(12.5 if item["depth"] == 0 else 11.5)
f.setItalic(item["removed"])
self.label.setFont(f)
self.label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
self.side = QLabel("")
self.side.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
for w in (self.label, self.side):
w.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
lay.addWidget(self.fig, 0, Qt.AlignmentFlag.AlignTop)
lay.addWidget(self.label, 1)
lay.addWidget(self.side, 0)
self._colours()
def _colours(self):
lk = self.look
text = QColor("#ffffff") if self.selected else lk.mid if self.item["removed"] else lk.text
quiet = QColor(255, 255, 255, 200) if self.selected else lk.mid
self.label.setStyleSheet("color: %s;" % text.name(QColor.NameFormat.HexArgb))
self.side.setStyleSheet("color: %s;" % quiet.name(QColor.NameFormat.HexArgb))
def set_selected(self, on):
self.selected = on
self._colours()
self.update()
def enterEvent(self, e):
self.hovered = True
self.update()
def leaveEvent(self, e):
self.hovered = False
self.update()
def mousePressEvent(self, e):
e.accept() # not the empty space behind it (that deselects)
def mouseReleaseEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton and self.rect().contains(e.position().toPoint()):
self.clicked.emit(self.item["id"])
def paintEvent(self, _):
if not (self.selected or self.hovered):
return
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
if self.selected: # design.html#highlight: the whole row
p.setBrush(self.look.highlight)
else:
p.setBrush(QColor(255, 255, 255, 22) if self.look.dark else QColor(0, 0, 0, 13))
p.drawRoundedRect(QRectF(self.rect()).adjusted(6, 0, -6, 0), 6, 6)
class StatsWindow(SideWindow):
SIZE = (540, 900) # the main window's shape: tall and narrow
def __init__(self, main):
super().__init__(main, "stats", "Statistics")
self.metric_key = self.cfg.get("stats_metric") if self.cfg.get("stats_metric") in dict(METRICS) else "pct"
self.selected = None
self.rows, self.headers = {}, []
self.tree = []
self.scroll = QScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.scroll.setFrameShape(QFrame.Shape.NoFrame)
self.body.addWidget(self.scroll, 1)
trow = QHBoxLayout()
trow.setContentsMargins(12, 10, 14, 6)
self.panel_title = QLabel("statistics")
self.panel_hint = QLabel("")
trow.addWidget(self.panel_title)
trow.addStretch(1)
trow.addWidget(self.panel_hint, 0, Qt.AlignmentFlag.AlignBottom)
self.body.addLayout(trow)
self.panel = QTextBrowser()
self.panel.setFixedHeight(168)
self.panel.setOpenLinks(False)
self.panel.setFocusPolicy(Qt.FocusPolicy.NoFocus)
wrap = QWidget()
wl = QVBoxLayout(wrap)
wl.setContentsMargins(12, 0, 12, 0)
wl.addWidget(self.panel)
self.body.addWidget(wrap)
bar = QWidget()
bl = QHBoxLayout(bar)
bl.setContentsMargins(8, 4, 8, 3)
self.metric_tiles = tiles(METRICS, self.metric_key, self._pick)
self.metric_tiles.setToolTip("What the number by each task shows: the % of its days it got done, "
"its longest streak in the range, or the days it got done")
h = round(QPushButton("All").sizeHint().height() * BIGGER)
pt = QPushButton().font().pointSizeF() * 1.3
for b in self.metric_tiles.findChildren(QPushButton):
b.setFixedHeight(h)
b.setFont(display_font(pt))
bl.addWidget(self.metric_tiles)
bl.addStretch(1)
self.body.addWidget(bar)
self._style()
# ── look ──
def _style(self):
lk = self.look
self.panel_title.setFont(lk.note_font(20))
self.panel_hint.setStyleSheet("color: %s; font-style: italic;" % lk.mid.name())
np = lk.panel
self.panel.setStyleSheet(
"QTextBrowser { color: %s; background: %s; border: 1px solid %s; border-top-color: %s; border-radius: 8px;"
" padding: 4px 6px; }" % (lk.panel_text.name(), np.name(), np.darker(135).name(), np.darker(155).name()))
def restyle(self, key):
super().restyle(key)
self._style()
if self._loaded:
self.reload()
# ── building ──
def _fig_width(self):
fm = QFontMetricsF(display_font(11.5, bold=True))
return int(max(fm.horizontalAdvance("100 %"), fm.horizontalAdvance("8888")) + 16)
def reload(self):
start, end = self.range.start, self.range.end
if not start:
return
y = self.scroll.verticalScrollBar().value()
self.hist = self.history()
self.range_days = self.days(start, end)
self.tree = tally.task_tree(self.schedule, self.hist, self.range_days, start, end)
ids = {it["id"] for b in self.tree for it in b["items"]}
if self.selected not in ids:
self.selected = None
inner = QWidget()
inner.setObjectName("scrollbody")
col = QVBoxLayout(inner)
col.setContentsMargins(0, 0, 0, 16)
col.setSpacing(0)
self.rows, self.headers, self.block_rows = {}, [], []
fw = self._fig_width()
for b in self.tree:
box = BlockBox(self.look, b)
h = BlockHeader(self.look, b)
h.clicked.connect(lambda bid=b["id"]: self._toggle_block(bid))
box.header = h
if b["removed"]:
h.title.setStyleSheet("color: %s;" % self.look.mid.name())
h.title.setToolTip("No longer in the routine")
box.lay.addWidget(h)
rows = []
for it in b["items"]:
r = StatRow(self.look, it, fw)
r.clicked.connect(self._select)
self.rows[it["id"]] = r
rows.append(r)
box.lay.addWidget(r)
self.headers.append(h)
self.block_rows.append(rows)
col.addWidget(box)
if not self.tree:
empty = QLabel("nothing recorded in this range")
empty.setFont(self.look.note_font(20))
empty.setStyleSheet("color: %s;" % self.look.mid.name())
empty.setAlignment(Qt.AlignmentFlag.AlignCenter)
empty.setContentsMargins(12, 40, 12, 12)
col.addWidget(empty)
col.addStretch(1)
inner.mousePressEvent = lambda e: self._select(None) # a click on nothing: the range again
old = self.scroll.takeWidget()
self.scroll.setWidget(inner)
if old is not None:
old.deleteLater()
self._fill()
self._apply_hidden()
QTimer.singleShot(0, lambda: self.scroll.verticalScrollBar().setValue(y))
def _apply_hidden(self):
hidden = set(self.cfg.get("stats_hidden_blocks", []))
learned = self.cfg.get("block_tap_learned", False)
for h, rows in zip(self.headers, self.block_rows):
gone = h.block["id"] in hidden
for r in rows:
r.setVisible(not gone)
h.helper.setText("" if learned else "click to show" if gone else "click to hide")
def _toggle_block(self, bid):
hidden = set(self.cfg.get("stats_hidden_blocks", []))
hidden ^= {bid}
self.cfg["stats_hidden_blocks"] = sorted(hidden)
self.cfg["block_tap_learned"] = True
paths.save_config(self.cfg)
self._apply_hidden()
def _pick(self, key):
self.metric_key = key
self.cfg["stats_metric"] = key
paths.save_config(self.cfg)
self._fill()
def _select(self, iid):
self.selected = None if iid == self.selected else iid
for k, r in self.rows.items():
r.set_selected(k == self.selected)
self._panel()
def keyPressEvent(self, e):
if e.key() == Qt.Key.Key_Escape and self.selected:
self._select(None)
return
super().keyPressEvent(e)
# ── the figures ──
def _fill(self):
start, end = self.range.start, self.range.end
today = self.today
for iid, r in self.rows.items():
st = self.hist.items[iid]
done, sched, pct = st.totals(start, end)
run = st.longest_run(start, end)
now = st.current
if self.metric_key == "pct":
r.fig.text = pct_text(pct if sched else None)
side = "%s of %s" % ("{:,}".format(done), plural(sched, "day")) if sched else "not yet"
elif self.metric_key == "longest":
r.fig.text = str(run.length) if run else "0"
bits = []
if run and run.cheats:
bits.append(plural(len(run.cheats), "cheat day"))
if now:
bits.append("now %d" % now)
side = " · ".join(bits)
else:
r.fig.text = "{:,}".format(done)
side = "of %s" % "{:,}".format(sched) if sched else ""
r.side.setText(side)
tip = ["%s: %s done, %s of %s" % (st.label, pct_text(pct if sched else None), "{:,}".format(done),
plural(sched, "day"))]
if run:
tip.append("Longest streak: %s (%s)%s" % (plural(run.length, "day"), span(run.start, run.last(), today),
", " + plural(len(run.cheats), "cheat day") + " used"
if run.cheats else ""))
tip.append("Streak now: %s" % plural(now, "day") if now else "No streak going now")
if r.item["removed"]:
tip.append("No longer in the routine")
r.setToolTip("\n".join(tip))
r.fig.update()
for h in self.headers: # each heading: its tasks together, quietly
done = sched = 0
for it in h.block["items"]:
d, n, _ = self.hist.items[it["id"]].totals(start, end)
done, sched = done + d, sched + n
tip = "Its tasks together: %s of %s task-days done" % ("{:,}".format(done), "{:,}".format(sched))
bs = self.hist.blocks.get(h.block["id"])
if bs is not None:
bd, bn, _ = bs.totals(start, end)
run = bs.longest_run(start, end)
tip += ("\nEvery task in it done: %s of %s; longest streak of those %s"
% ("{:,}".format(bd), plural(bn, "day"), plural(run.length if run else 0, "day")))
h.setToolTip(tip)
h.hours.setText("%s – %s" % (hour_label(h.block["start"]), hour_label(h.block["end"])))
h.note.setText(pct_text(100.0 * done / sched if sched else None) + " done")
h.note.setStyleSheet("color: %s;" % self.look.mid.name())
self._panel()
def _panel(self):
if not hasattr(self, "hist"):
return
self.panel.setHtml(self._task_html(self.selected) if self.selected else self._range_html())
self.panel_hint.setText("click it again for the whole range" if self.selected else "click a task for its details")
def _table(self, rows):
mid = self.look.mid.name()
out = ['<table cellspacing="0" cellpadding="1">']
for k, v in rows:
out.append('<tr><td style="color:%s; padding-right:12px;">%s</td><td>%s</td></tr>' % (mid, k, v))
out.append("</table>")
return "".join(out)
def _head(self, big, small=""):
return ('<div style="margin-bottom:4px;"><span style="font-size:13pt; font-weight:bold;">%s</span>'
'<span style="color:%s;">%s</span></div>' % (big, self.look.mid.name(), "&nbsp;&nbsp;" + small if small else ""))
def _name(self, st):
"""A task's name, with its block's when another task listed has the same one."""
twins = sum(1 for b in self.tree for it in b["items"] if self.hist.items[it["id"]].label == st.label)
if twins < 2:
return html.escape(st.label)
blk = self.hist.blocks.get(st.block)
return html.escape("%s (%s)" % (st.label, blk.label if blk else st.block))
def _range_html(self):
start, end, today = self.range.start, self.range.end, self.today
s = tally.summary(self.hist, self.range_days, start, end, today.isoformat())
e = self._name
rows = [("Routine done", "%s &nbsp;<span style='color:%s'>%s of %s tasks</span>"
% (pct_text(s["pct"]), self.look.mid.name(), "{:,}".format(s["done"]), "{:,}".format(s["scheduled"])))]
if s["best"]:
st, r = s["best"][0]
rows.append(("Longest streak", "%s &nbsp;%s <span style='color:%s'>(%s%s)</span>"
% (plural(r.length, "day"), e(st), self.look.mid.name(), span(r.start, r.last(), today),
", " + plural(len(r.cheats), "cheat day") if r.cheats else "")))
more = ", ".join("%s %d" % (e(x), y.length) for x, y in s["best"][1:4])
if more:
rows.append(("then", more))
if s["going"]:
rows.append(("Going now", ", ".join("%s %d" % (e(x), n) for x, n in s["going"][:3])))
rows.append(("Perfect days", "%s <span style='color:%s'>every task ticked</span>"
% ("{:,}".format(s["perfect"]), self.look.mid.name())))
ca = paths.cheat_after(self.cfg)
rows.append(("Cheat days used", ("%s <span style='color:%s'>by %s</span>"
% ("{:,}".format(s["cheats"]), self.look.mid.name(), plural(s["cheat_tasks"], "task"))
if s["cheats"] else "none") if ca else "off (Settings → Streaks)"))
small = "today still open" if s["days"] > s["counted"] else ""
return self._head(plural(s["days"], "day"), small) + self._table(rows)
def _task_html(self, iid):
start, end, today = self.range.start, self.range.end, self.today
st = self.hist.items[iid]
e = html.escape
mid = self.look.mid.name()
blk = next((b for b in self.tree if any(it["id"] == iid for it in b["items"])), None)
where = blk["label"] if blk else st.block
parent = self.hist.items.get(iid.rpartition("/")[0])
if parent is not None:
where += " › " + parent.label
done, sched, pct = st.totals(start, end)
run = st.longest_run(start, end)
rows = []
if run:
cheats = ""
if run.cheats:
cheats = " · " + plural(len(run.cheats), "cheat day")
if len(run.cheats) <= 3:
cheats += " (%s)" % ", ".join(short_date(c, today) for c in run.cheats)
rows.append(("Longest streak", "<b>%s</b> &nbsp;<span style='color:%s'>%s%s</span>"
% (plural(run.length, "day"), mid, span(run.start, run.last(), today), cheats)))
else:
rows.append(("Longest streak", "none in this range"))
now = st.current
if now:
r = st.runs[-1]
rows.append(("Streak now", "<b>%s</b> &nbsp;<span style='color:%s'>since %s%s</span>"
% (plural(now, "day"), mid, short_date(r.start, today),
" · " + plural(len(r.cheats), "cheat day") if r.cheats else "")))
else:
rows.append(("Streak now", "none going"))
rows.append(("Done", "<b>%s</b> &nbsp;<span style='color:%s'>%s of %s it was on</span>"
% (pct_text(pct if sched else None), mid, "{:,}".format(done), plural(sched, "day"))))
level, to_go = tally.next_level(now)
rows.append(("Next reward", "%s &nbsp;<span style='color:%s'>%s to go</span>" % (plural(level, "day"), mid,
plural(to_go, "day"))))
runs = st.runs_in(start, end)
used = tally.cheats_in(st, start, end)
rows.append(("In this range", "%s%s" % (plural(len(runs), "streak"),
" · %s used" % plural(used, "cheat day") if paths.cheat_after(self.cfg) else "")))
small = e(where) + (" · no longer in the routine" if iid not in {it["id"] for b in self.tree for it in b["items"]
if not it["removed"]} else "")
return self._head(e(st.label), small) + self._table(rows)
+177
View File
@@ -0,0 +1,177 @@
"""(Adapted from LinTunes' folder tabs; the apps don't share code.)
Folder tabs after classic Mac OS (the Platinum look of OS 8 and 9), in
the house style (shared-resources' design page, #tabs): slanted sides with
8 px top corners, the tabs behind are buttons (embossed in the button
gray, darker on hover, sunk while held), and the open tab in front is the
page's own color with only the top rim, open at the foot so it runs into
the page. All stand on one baseline, overlapping a little.
Each tab is a checkable QToolButton that paints itself, so the window's
QButtonGroup logic is unchanged; `TabStrip` holds them, overlapping a little
the way the real ones did, and draws the baseline they stand on. The tab
in front is raised above its neighbours, so its feet cover theirs."""
from __future__ import annotations
from routine.qt.QtCore import QPointF, QSize, Qt
from routine.qt.QtGui import QLinearGradient, QPainter, QPainterPath, QPalette, QPen
from routine.qt.QtWidgets import QToolButton, QWidget
def _emboss_stops(c, pressed=False):
"""design.html#emboss as gradient stops: rims lighter/darker(116) over 8 %, face 103."""
top, ftop, fbot, bot = (c.darker(116), c.darker(103), c.lighter(103), c.lighter(116)) if pressed else \
(c.lighter(116), c.lighter(103), c.darker(103), c.darker(116))
return [(0, top), (0.08, ftop), (0.5, c), (0.92, fbot), (1, bot)]
HOVER_DARKER, PRESSED_DARKER = 107, 125
OVERLAP = 9 # px adjacent tabs overlap at their slanted feet
RADIUS = 8 # the top corners: the big buttons' radius
SLANT = 0.28 # each side's run, as a share of the height
OUTLINE = 135 # the buttons' outline, darker(135)
def _slant(h: int) -> float:
return h * SLANT
def baseline_color(palette):
return palette.color(QPalette.ColorRole.Window).darker(OUTLINE)
class MacTab(QToolButton):
def __init__(self, text: str, parent=None):
super().__init__(parent)
self.setText(text)
self.setCheckable(True)
self.toggled.connect(lambda on: on and self.raise_())
def sizeHint(self) -> QSize:
fm = self.fontMetrics()
h = fm.height() + 12
return QSize(int(fm.horizontalAdvance(self.text()) + 2 * _slant(h) + 18), h)
def minimumSizeHint(self) -> QSize:
return self.sizeHint()
def _outline(self) -> QPainterPath:
"""Up the left slope, round the top corners, down the right slope;
open along the foot."""
w, h, s = self.width(), self.height(), _slant(self.height())
top, foot = 0.5, float(h)
side = ((s - 0.5) ** 2 + (foot - top) ** 2) ** 0.5
r = min(RADIUS, side / 2)
# where the curve starts, back down each slope
dx, dy = (s - 0.5) * r / side, (foot - top) * r / side
p = QPainterPath()
p.moveTo(0.5, foot)
p.lineTo(s - dx, top + dy)
p.quadTo(s, top, s + r, top)
p.lineTo(w - s - r, top)
p.quadTo(w - s, top, w - s + dx, top + dy)
p.lineTo(w - 0.5, foot)
return p
def _fill(self, color, front: bool) -> QLinearGradient:
"""A button's emboss, or (front) only its top rim, then the page."""
g = QLinearGradient(QPointF(0, 0), QPointF(0, self.height()))
stops = _emboss_stops(color, pressed=self.isDown() and not front)
for pos, c in (stops[:3] if front else stops):
g.setColorAt(pos, c)
if front:
g.setColorAt(1, color)
return g
def paintEvent(self, _) -> None:
front = self.isChecked()
pal = self.palette()
if front:
color = pal.color(QPalette.ColorRole.Window)
else:
color = pal.color(QPalette.ColorRole.Button)
if self.isDown():
color = color.darker(PRESSED_DARKER)
elif self.underMouse():
color = color.darker(HOVER_DARKER)
w, h = self.width(), self.height()
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
shape = self._outline()
p.fillPath(shape, self._fill(color, front))
p.setPen(QPen(color.darker(OUTLINE), 1))
p.drawPath(shape)
if not front: # behind: the baseline runs across its foot
p.setPen(QPen(baseline_color(pal), 1))
p.drawLine(QPointF(0, h - 0.5), QPointF(w, h - 0.5))
p.setPen(pal.color(QPalette.ColorRole.WindowText if front
else QPalette.ColorRole.ButtonText))
f = self.font()
f.setBold(front)
p.setFont(f)
p.drawText(self.rect().adjusted(0, 2, 0, 0), Qt.AlignmentFlag.AlignCenter, self.text())
p.end()
def enterEvent(self, e) -> None:
self.update()
super().enterEvent(e)
def leaveEvent(self, e) -> None:
self.update()
super().leaveEvent(e)
class TabStrip(QWidget):
"""A row of MacTabs (None in `add` = a gap) on a baseline across the
width. Placed by hand: a layout can't overlap its widgets."""
def __init__(self, parent=None):
super().__init__(parent)
self._items: list[MacTab | int] = [] # a tab, or a gap's width
def add(self, tab: MacTab | None, gap: int = 24) -> None:
if tab is None:
self._items.append(gap)
else:
tab.setParent(self)
self._items.append(tab)
def finish(self) -> None:
for t in self._tabs():
if t.isChecked():
t.raise_()
self._place()
def _tabs(self) -> list[MacTab]:
return [t for t in self._items if isinstance(t, MacTab)]
def sizeHint(self) -> QSize:
tabs = self._tabs()
h = max((t.sizeHint().height() for t in tabs), default=24)
w = 4 + sum(t.sizeHint().width() - OVERLAP if isinstance(t, MacTab) else t
for t in self._items) + OVERLAP
return QSize(w, h)
def minimumSizeHint(self) -> QSize:
return self.sizeHint()
def _place(self) -> None:
x, h = 4, self.height()
for item in self._items:
if isinstance(item, MacTab):
hint = item.sizeHint()
item.setGeometry(x, h - hint.height(), hint.width(), hint.height())
x += hint.width() - OVERLAP
else:
x += item
def resizeEvent(self, e) -> None:
self._place()
super().resizeEvent(e)
def paintEvent(self, _) -> None:
p = QPainter(self)
p.setPen(QPen(baseline_color(self.palette()), 1))
p.drawLine(0, self.height() - 1, self.width(), self.height() - 1)
p.end()
+510
View File
@@ -0,0 +1,510 @@
"""The routine's data: the schedule, a day's record, and how two copies of a day merge.
Standard library only: the sync server imports this file too (scripts/deploy-server.sh copies it).
The R1 app has a line-for-line Java port (android/.../Model.java); keep the two in step.
A day is one JSON document:
{"date": "2026-11-06",
"rev": 1, # schedule rev the snapshot below came from
"blocks": [{"id", "label", "start", "end", "color",
"items": [{"id": "night/file-notes/calendar-txt", "label", "depth", "hint"?, "calm"?}]}],
"states": {"<item id>": {"s": "done" | "skipped" | "", "t": <ms>}},
"note": {"text": "", "t": <ms>},
"plays": [{"t": <ms>, "a": "<animation name>", "i": "<item id>", "s": <set>, "n"?: <streak>}]}
# s: 0, 1, .. = that set; CALM_SET (-1) = the calm set; STREAK_SET (-2) = a streak
# animation, STREAK_CALM_SET (-3) = a calm streak one; those two carry "n", the streak reached
The blocks are a snapshot of the routine as it was that day, so editing the schedule later
never rewrites history. Merging is last-writer-wins per item and for the note, so two
devices can tick different things offline and both survive. plays (every check-off
animation that played) is a log: merging is the union of both.
Blocks and items can both have "days" (0 = Sunday .. 6 = Saturday; missing = every day): on
other days they, and everything under them, are left out of the snapshot. An item with
"hint": true is suggestion text, not a task: no checkbox, never ticked, skipped or counted.
An item with "calm": true plays one of the calm set when ticked (animations.json "calm")
instead of its set's, and never the star; the tick still counts toward the next set.
Animation sets: the first PER_SET ticks (model.ticks) of a day draw from set 0, the next PER_SET from set 1,
and so on (anim_set below; set sizes come from animations.json); past the last set the
last one keeps playing, with the special star as well.
Streaks (all pure; a task is followed across days by its item id, which survives renames):
For one item, each day is
off (S_OFF) it isn't in that day's snapshot, or is a hint: neutral (weekday-only tasks
keep their streak over the weekend);
done (S_DONE) ticked;
miss (S_MISS) pending or skipped on a day before today (skipped today too);
open (S_OPEN) today, still pending: neutral, breaks nothing yet;
cheat (S_CHEAT) a miss forgiven by a cheat day.
A streak (Run) is a run of done days, off and open days ignored; its number is its count of done
days. Cheat days (cheat_after = N > 0; 0 or None = off): N done days in a row, counted from the
run's start or from the last cheat day used, earn one held cheat day (at most one at a time). A
miss while one is held uses it (that day becomes S_CHEAT, the run goes on, the count starts
again); a miss with none held ends the run. A cheat day followed by another miss with no done day
between was no rescue: it turns back into an ordinary miss and the run ended at its last done
day. A trailing cheat day with only neutral days after it keeps the streak alive.
streak_level(n) -> level index or None n rewarded? STREAK_LEVELS, then every STREAK_EVERY past the top
day_marks(day, today) -> (items, blocks) one day's raw marks, the input to Streak.feed
history(days, today, cheat_after) -> History one pass over the days: .items / .blocks {id: Streak}, .dates
streak_ending(days, item_id, date, cheat_after) -> int the streak ticking item_id on date reaches
Streak: .status {date: S_*} (absent = off; status_on(date)), .run_of {date: run index},
.runs [Run], .levels {date: LEVEL_*} (blocks), .current, .longest, longest_run(start, end),
runs_in(start, end), totals(start, end) -> (done, scheduled, %)
Run: .start, .end (first/last done day), .length (the number), .cheats [dates], last()
A block is done on a day when all its tasks are, a miss when any isn't (before today), and has no
day at all (off) when it has no tasks that day; blocks get the same Streak, plus .levels.
Dates are ISO strings throughout ("2026-11-14"), so they compare in order.
streak_base(days, asof, cheat_after) -> every item's state after asof (Streak.base / seed), so
streak_ending(..., base=) needs only the days after asof: how the R1, which holds ~60 days, gets
the desktop's number (the desktop sends it through the sync server; see routine/sync.py).
Ticking a task by hand whose streak_ending is rewarded plays one of that level's streak
animations instead of its set's (animations.json "streak"; a calm task, one of the calm streak
ones); it is logged with s = STREAK_SET / STREAK_CALM_SET and n = the streak, and still counts
in ticks().
"""
import datetime as _dt
import json
import re
import time
DONE, SKIPPED, PENDING = "done", "skipped", ""
PER_SET = 5
def now_ms():
return int(time.time() * 1000)
def slug(label):
s = re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")
return s or "item"
def load_schedule(path, *more):
"""The first of the paths that holds a schedule: the user's own copy wins over the template
whatever their revs (the desktop's first-run logic is routine/storage.py)."""
for p in (path,) + more:
try:
with open(p, encoding="utf-8") as f:
s = json.load(f)
except (OSError, ValueError):
continue
if isinstance(s, dict) and isinstance(s.get("blocks"), list):
return s
raise FileNotFoundError(path)
def routine_date(schedule, when=None):
"""The routine day a moment belongs to: before dayStartsAt it is still yesterday."""
when = when or _dt.datetime.now()
return (when - _dt.timedelta(hours=schedule.get("dayStartsAt", 4))).date()
def _flatten(items, weekday, prefix, depth, out):
seen = set()
for it in items:
if not on_day(it, weekday):
continue
iid = prefix + "/" + it.get("id", slug(it["label"]))
while iid in seen: # two siblings with the same label
iid += "-2"
seen.add(iid)
row = {"id": iid, "label": it["label"], "depth": depth}
if it.get("hint"):
row["hint"] = True
if it.get("calm"):
row["calm"] = True
out.append(row)
_flatten(it.get("items", []), weekday, iid, depth + 1, out)
def on_day(x, weekday):
days = x.get("days")
return days is None or weekday in days
def snapshot(schedule, date):
"""The blocks and items for a date (day-of-week blocks and items resolved)."""
weekday = (date.weekday() + 1) % 7 # 0 = Sunday, as in schedule.json
blocks = []
for b in schedule["blocks"]:
if not on_day(b, weekday):
continue
items = []
_flatten(b.get("items", []), weekday, b["id"], 0, items)
blocks.append({"id": b["id"], "label": b["label"], "start": b["start"],
"end": b["end"], "color": b["color"], "items": items})
return blocks
def new_day(schedule, date):
return {"date": date.isoformat(), "rev": schedule.get("rev", 1),
"blocks": snapshot(schedule, date), "states": {}, "note": {"text": "", "t": 0}}
def refresh_snapshot(schedule, day):
"""Give a day the current routine if the schedule has a newer rev. True if it changed."""
rev = schedule.get("rev", 1)
if day.get("rev", 0) >= rev:
return False
day["rev"] = rev
day["blocks"] = snapshot(schedule, _dt.date.fromisoformat(day["date"]))
return True
def state(day, item_id):
return day["states"].get(item_id, {}).get("s", PENDING)
def set_state(day, item_id, s):
day["states"][item_id] = {"s": s, "t": now_ms()}
def set_with_children(day, item_id, s):
"""Tick or skip an item, and give its still-pending sub-items the same state.
Un-ticking (s = PENDING) only touches the item itself; suggestions are never given a state.
Returns the ids changed."""
changed = [item_id]
set_state(day, item_id, s)
if s != PENDING:
for b in day["blocks"]:
for it in b["items"]:
if it["id"].startswith(item_id + "/") and not it.get("hint") and state(day, it["id"]) == PENDING:
set_state(day, it["id"], s)
changed.append(it["id"])
return changed
STAR = "star_special"
def ticks(day):
"""How many tasks the day has had ticked by hand (and still ticked): the distinct items in
the play log that are done. Sub-tasks ticked along with a parent don't count; ticking the
same task again doesn't either; unticking one takes it back."""
return len({p["i"] for p in day.get("plays", []) if p.get("a") != STAR and state(day, p["i"]) == DONE})
def anim_set(done_before, sets):
"""sets: the size of each set, in order (animations.json "sets"; set 0 is the biggest).
Returns (first, last+1) of the animations to pick from, the set number, and whether the
star plays as well (every set used up)."""
k = done_before // PER_SET
star = k >= len(sets)
k = min(k, len(sets) - 1)
lo = sum(sets[:k])
return lo, lo + sets[k], k, star
CALM_SET = -1 # the play log's set number for the calm set
def add_play(day, name, item_id, set_no, streak=None):
p = {"t": now_ms(), "a": name, "i": item_id, "s": set_no}
if streak:
p["n"] = streak # a streak animation: the streak it celebrated
day.setdefault("plays", []).append(p)
def _play_key(p):
return (p.get("t", 0), str(p.get("a", "")), str(p.get("i", "")))
def set_note(day, text):
day["note"] = {"text": text, "t": now_ms()}
def _newer(a, b, key):
"""a or b, whichever was written later; ties broken by value so every device agrees."""
if a["t"] != b["t"]:
return a if a["t"] > b["t"] else b
return a if str(a.get(key, "")) >= str(b.get(key, "")) else b
def merge(a, b):
"""Merge two copies of the same day. Pure: returns a new dict."""
if a is None:
return json.loads(json.dumps(b))
if b is None:
return json.loads(json.dumps(a))
snap = a if a.get("rev", 0) >= b.get("rev", 0) else b
states = dict(a.get("states", {}))
for k, v in b.get("states", {}).items():
states[k] = _newer(states[k], v, "s") if k in states else v
note = _newer(a.get("note", {"text": "", "t": 0}), b.get("note", {"text": "", "t": 0}), "text")
plays = {_play_key(p): dict(p) for p in a.get("plays", []) + b.get("plays", [])}
return {"date": a["date"], "rev": snap.get("rev", 0),
"blocks": json.loads(json.dumps(snap["blocks"])),
"states": {k: dict(v) for k, v in states.items()}, "note": dict(note),
"plays": [plays[k] for k in sorted(plays)]}
# ── streaks ───────────────────────────────────────────────────────────────────
# (the module docstring's "Streaks" section is the reference; this is the code)
STREAK_LEVELS = [7, 21, 42, 66, 100, 150, 254, 365]
STREAK_EVERY = 100 # past the last level, every 100 more days is the top level again
CHEAT_AFTER = 7 # done days in a row that earn one cheat day (the default)
STREAK_SET = -2 # the play log's set number for a streak animation
STREAK_CALM_SET = -3 # ... and for a calm streak animation
S_DONE, S_MISS, S_OFF, S_CHEAT, S_OPEN = "done", "miss", "off", "cheat", "open"
LEVEL_ALL, LEVEL_SOME, LEVEL_NONE = "all", "some", "none"
def streak_level(n):
"""The level index (into STREAK_LEVELS) a streak number is rewarded at, or None."""
for k, v in enumerate(STREAK_LEVELS):
if n == v:
return k
top = STREAK_LEVELS[-1]
if n > top and (n - top) % STREAK_EVERY == 0:
return len(STREAK_LEVELS) - 1
return None
def day_marks(day, today):
"""One day's raw marks: ({item id: mark}, {block id: (mark, level)}), mark = S_DONE | S_MISS | S_OPEN.
Only the day's tasks are in it (suggestions and absent items are off days: left out); a block with
no tasks that day is left out too. Pending or skipped before today = S_MISS; today, pending =
S_OPEN (skipped today is a miss). A block is done when all its tasks are, a miss when any of them
is, else open; its level is LEVEL_ALL / LEVEL_SOME / LEVEL_NONE by how many of its tasks are done."""
past = str(day["date"]) < str(today)
items, blocks = {}, {}
for b in day.get("blocks", []):
n = got = miss = 0
for it in b.get("items", []):
if it.get("hint"):
continue
s = state(day, it["id"])
if s == DONE:
m = S_DONE
got += 1
elif past or s == SKIPPED:
m = S_MISS
miss += 1
else:
m = S_OPEN
items[it["id"]] = m
n += 1
if n:
mark = S_DONE if got == n else S_MISS if miss else S_OPEN
blocks[b["id"]] = (mark, LEVEL_ALL if got == n else LEVEL_SOME if got else LEVEL_NONE)
return items, blocks
class Run:
"""One streak: start / end = its first and last done day, length = its done days (its number),
cheats = the cheat days used in it (the last one may come after end: still alive)."""
def __init__(self, start):
self.start = start
self.end = start
self.length = 0
self.cheats = []
def last(self):
"""The last day the run covers: end, or a trailing cheat day after it."""
return self.cheats[-1] if self.cheats and self.cheats[-1] > self.end else self.end
def __repr__(self):
return "Run(%s..%s, %d, cheats=%s)" % (self.start, self.end, self.length, self.cheats)
class Streak:
"""The streak record of one item (or block), fed its marks day by day in date order.
status: {date: S_DONE | S_MISS | S_CHEAT | S_OPEN}; a date not in it is an off day (status_on).
run_of: {date: index into runs}, for done and cheat days. runs: [Run], oldest first.
levels: blocks only, {date: LEVEL_ALL | LEVEL_SOME | LEVEL_NONE}.
label / block / depth / calm: as last seen (items), label (blocks)."""
def __init__(self, key, cheat_after=CHEAT_AFTER):
self.key = key
self.cheat_after = cheat_after if cheat_after and cheat_after > 0 else 0
self.status, self.run_of, self.runs, self.levels = {}, {}, [], {}
self.label, self.block, self.depth, self.calm = key, key.split("/")[0], 0, False
self._run = None # the run going on (None: none)
self._since = 0 # done days since the run began or the last cheat day
self._held = False # a cheat day earned and not used yet
self._cheat = None # the date of a cheat day not yet followed by a done day
def feed(self, date, mark):
if mark == S_OPEN:
self.status[date] = S_OPEN
elif mark == S_DONE:
if self._run is None:
self._run = Run(date)
self.runs.append(self._run)
self._since, self._held = 0, False
self._cheat = None # a cheat day followed by a done day: a rescue
r = self._run
r.length += 1
r.end = date
self.status[date] = S_DONE
self.run_of[date] = len(self.runs) - 1
self._since += 1
if self.cheat_after and not self._held and self._since >= self.cheat_after:
self._held = True
else: # a miss
r = self._run
if r is not None and self._cheat is not None: # two misses running: no rescue after all
c = self._cheat
self.status[c] = S_MISS
del self.run_of[c]
r.cheats.remove(c)
self._cheat, self._run = None, None
self.status[date] = S_MISS
elif r is not None and self._held: # forgiven: the run goes on
self._held, self._since, self._cheat = False, 0, date
r.cheats.append(date)
self.status[date] = S_CHEAT
self.run_of[date] = len(self.runs) - 1
else:
self._run = None
self.status[date] = S_MISS
# ── a streak carried over from days not at hand (streak_base) ──
def base(self):
"""What carrying on from here needs: [length, since, held, cheat] (held / cheat 0 or 1:
a cheat day earned / one used and not yet followed by a done day), or None with no run going."""
if self._run is None:
return None
return [self._run.length, self._since, int(self._held), int(self._cheat is not None)]
def seed(self, state, asof):
"""Start from base() as it was after the days up to asof (state None: no run going).
A pending cheat day is put on asof itself, so a miss after it undoes it as usual."""
if not state:
return
r = self._run = Run(asof)
self.runs.append(r)
r.length, self._since, self._held = int(state[0]), int(state[1]), bool(state[2])
if state[3]:
self._cheat = asof
r.cheats.append(asof)
self.run_of[asof] = len(self.runs) - 1
# ── what the windows read ──
def status_on(self, date):
return self.status.get(str(date), S_OFF)
@property
def current(self):
"""The streak alive after the last day fed (a trailing cheat day keeps it alive), else 0."""
return self._run.length if self._run is not None else 0
def longest_run(self, start=None, end=None):
"""The longest run (the earliest of equals) ending within start..end (None = open), or None."""
best = None
for r in self.runs:
if (start is None or r.end >= str(start)) and (end is None or r.end <= str(end)):
if best is None or r.length > best.length:
best = r
return best
@property
def longest(self):
r = self.longest_run()
return r.length if r else 0
def runs_in(self, start=None, end=None):
"""The runs that overlap start..end (None = open)."""
return [r for r in self.runs if (start is None or r.last() >= str(start)) and (end is None or r.start <= str(end))]
def totals(self, start=None, end=None):
"""(done days, scheduled days, % of scheduled days done) within start..end (None = open).
Scheduled = done + missed + cheat days; today while still open isn't counted yet."""
done = sched = 0
for d, s in self.status.items():
if (start is None or d >= str(start)) and (end is None or d <= str(end)) and s != S_OPEN:
sched += 1
done += s == S_DONE
return done, sched, (100.0 * done / sched if sched else 0.0)
class History:
"""Every item's and block's Streak over a run of days: items {item id: Streak},
blocks {block id: Streak}, dates = the dates fed, in order."""
def __init__(self, cheat_after=CHEAT_AFTER):
self.cheat_after = cheat_after
self.items, self.blocks, self.dates = {}, {}, []
def add_day(self, day, today):
"""Feed one more day (dates must come in order, none after today)."""
date = str(day["date"])
self.dates.append(date)
items, blocks = day_marks(day, today)
for b in day.get("blocks", []):
for it in b.get("items", []):
if it["id"] in items:
st = self.items.get(it["id"])
if st is None:
st = self.items[it["id"]] = Streak(it["id"], self.cheat_after)
st.label, st.block, st.depth, st.calm = it["label"], b["id"], it.get("depth", 0), bool(it.get("calm"))
st.feed(date, items[it["id"]])
if b["id"] in blocks:
st = self.blocks.get(b["id"])
if st is None:
st = self.blocks[b["id"]] = Streak(b["id"], self.cheat_after)
st.label, st.block = b["label"], b["id"]
mark, level = blocks[b["id"]]
st.levels[date] = level
st.feed(date, mark)
def history(days, today, cheat_after=CHEAT_AFTER):
"""One pass over days (day documents, any order; days after today are left out) -> History.
Streaks need what came before, so feed from the first day there is, and narrow to a date range
afterwards (Streak.totals / runs_in / longest_run take start, end)."""
today = str(today)
h = History(cheat_after)
for day in sorted((d for d in days if str(d["date"]) <= today), key=lambda d: d["date"]):
h.add_day(day, today)
return h
STREAK_BASE_LAG = 30 # the desktop publishes streak_base as of this many days before its today
def streak_base(days, asof, cheat_after=CHEAT_AFTER):
"""Every item's streak state after the days up to asof, all of them past (as any later day sees
them): {"asof": date, "cheat_after": n, "items": {item id: Streak.base()}}, items with a run
going only. streak_ending(..., base=) carries on from it, so a device that holds only the days
after asof still gets the whole streak's number. The desktop sends it through the sync server to the R1
(which holds ~60 days: the server's window), as of STREAK_BASE_LAG days ago."""
asof = str(asof)
after = (_dt.date.fromisoformat(asof) + _dt.timedelta(days=1)).isoformat()
h = history([d for d in days if str(d["date"]) <= asof], after, cheat_after)
items = {}
for iid, st in h.items.items():
b = st.base()
if b:
items[iid] = b
return {"asof": asof, "cheat_after": cheat_after if cheat_after and cheat_after > 0 else 0, "items": items}
def streak_ending(days, item_id, date, cheat_after=CHEAT_AFTER, base=None):
"""The streak number item_id has on date if that day is done, counting only date and the days
before it (date treated as today): what ticking it on that day reaches. 0 if it isn't done.
base: a streak_base; when date is after its asof, only the days after asof are read, carrying
on from the base (whose cheat_after then counts, not the argument)."""
date = str(date)
st = Streak(item_id, cheat_after)
after = ""
if base and date > str(base.get("asof", "")):
after = str(base["asof"])
st = Streak(item_id, base.get("cheat_after", cheat_after))
st.seed(base.get("items", {}).get(item_id), after)
for day in sorted((d for d in days if after < str(d["date"]) <= date), key=lambda d: d["date"]):
m = day_marks(day, date)[0].get(item_id)
if m is not None:
st.feed(str(day["date"]), m)
return st.current if st.status.get(date) == S_DONE else 0
+122
View File
@@ -0,0 +1,122 @@
"""Where things live. ROUTINE_HOME overrides the data+config dir (tests and the dev data set).
The routine (schedule.json) and the history (routine.db) live in the data dir unless Settings →
Data points either somewhere else ("schedule_dir" / "db_dir" in the config: a folder, "" = the
default). With ROUTINE_HOME set, the defaults and the config file are all under it, so a test
never touches the real ones (a location set in that test config still applies).
"""
import json
import os
import sys
from routine import system
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SHARED = os.path.join(REPO, "shared")
SCHEDULE = os.path.join(SHARED, "schedule.json") # the template: a first run starts from it
ANIMATIONS = os.path.join(SHARED, "animations.json")
SOUNDS = os.path.join(SHARED, "sounds")
APK = os.path.join(REPO, "android", "apk", "routine.apk")
_home = os.environ.get("ROUTINE_HOME")
DATA = system.data_dir() # Linux ~/.local/share/routine, macOS ~/Library/Application Support/Routine
CONFIG_DIR = system.config_dir() # Linux ~/.config/routine, macOS the same folder as DATA
CONFIG = os.path.join(CONFIG_DIR, "config.json")
LOGS = system.log_dir() # errors.log: Linux ~/.local/state/routine, macOS ~/Library/Logs/Routine
SCHEDULE_NAME, DB_NAME = "schedule.json", "routine.db"
DB = os.path.join(DATA, DB_NAME) # the default places (schedule_path / db_path
SCHEDULE_LIVE = os.path.join(DATA, SCHEDULE_NAME) # give the ones in use)
DEFAULTS = {
"sync_url": "", # the sync server (server/routine_server.py), e.g. http://host:8070
"sync_token": "",
"schedule_dir": "", # where schedule.json is kept ("" = DATA)
"db_dir": "", # where routine.db is kept ("" = DATA)
"mode": "system", # system | light | dark
"sounds": True,
"tooltips": True,
"hide_menubar": True,
"filter": "all", # all | incomplete
"window": [458, 1050], # width, height (tall and narrow)
"streak_anims": True, # a tick that reaches a streak level plays a streak animation instead
"cheat_day": True, # streaks may hold one forgiven miss ...
"cheat_after": 7, # ... earned by this many done days in a row
"emboss_history": True, # the History window draws its dots as little buttons
}
# Config keys that were renamed: read once from an older config and written back under the new name.
RENAMED = {} # old key: new key (none at the moment)
def _folder(cfg, key):
d = (cfg.get(key) or "").strip()
return os.path.abspath(os.path.expanduser(d)) if d else DATA
def schedule_dir(cfg):
return _folder(cfg, "schedule_dir")
def db_dir(cfg):
return _folder(cfg, "db_dir")
def schedule_path(cfg):
"""The user's routine, as edited in Settings → Routine."""
return os.path.join(schedule_dir(cfg), SCHEDULE_NAME)
def db_path(cfg):
return os.path.join(db_dir(cfg), DB_NAME)
def cheat_after(cfg):
"""The cheat-day setting as model's cheat_after: N, or 0 when cheat days are off."""
if not cfg.get("cheat_day", True):
return 0
try:
return max(1, int(cfg.get("cheat_after", 7)))
except (TypeError, ValueError):
return 7
def migrate_config(saved):
"""Renamed keys in a config as read from disk, in place: the old value moves to the new key
(unless the new one is already set). Returns the old key names it moved (never the values)."""
moved = []
for old, new in RENAMED.items():
if old in saved:
v = saved.pop(old)
if new not in saved:
saved[new] = v
moved.append(old)
return moved
def load_config():
cfg = dict(DEFAULTS)
try:
with open(CONFIG) as f:
saved = json.load(f)
except (OSError, ValueError):
saved = {}
if not isinstance(saved, dict):
saved = {}
moved = migrate_config(saved)
cfg.update(saved)
if moved:
try:
save_config(cfg)
print("routine: config keys renamed (%d)" % len(moved), file=sys.stderr)
except OSError:
pass
return cfg
def save_config(cfg):
os.makedirs(CONFIG_DIR, exist_ok=True)
tmp = CONFIG + ".tmp"
with open(tmp, "w") as f:
json.dump(cfg, f, indent=2)
os.chmod(tmp, 0o600) # holds the sync token
os.replace(tmp, CONFIG)
+12
View File
@@ -0,0 +1,12 @@
"""QtCore from the binding routine.qt picked."""
from routine.qt import PYSIDE
if PYSIDE:
from PySide6.QtCore import * # noqa: F401,F403
else:
from PyQt6.QtCore import * # noqa: F401,F403
if PYSIDE:
from PySide6.QtCore import Signal, Slot # noqa: F401
else:
from PyQt6.QtCore import pyqtSignal as Signal, pyqtSlot as Slot # noqa: F401
+8
View File
@@ -0,0 +1,8 @@
"""QtGui from the binding routine.qt picked."""
from routine.qt import PYSIDE
if PYSIDE:
from PySide6.QtGui import * # noqa: F401,F403
else:
from PyQt6.QtGui import * # noqa: F401,F403
+8
View File
@@ -0,0 +1,8 @@
"""QtMultimedia from the binding routine.qt picked."""
from routine.qt import PYSIDE
if PYSIDE:
from PySide6.QtMultimedia import * # noqa: F401,F403
else:
from PyQt6.QtMultimedia import * # noqa: F401,F403
+8
View File
@@ -0,0 +1,8 @@
"""QtNetwork from the binding routine.qt picked."""
from routine.qt import PYSIDE
if PYSIDE:
from PySide6.QtNetwork import * # noqa: F401,F403
else:
from PyQt6.QtNetwork import * # noqa: F401,F403
+8
View File
@@ -0,0 +1,8 @@
"""QtTest from the binding routine.qt picked."""
from routine.qt import PYSIDE
if PYSIDE:
from PySide6.QtTest import * # noqa: F401,F403
else:
from PyQt6.QtTest import * # noqa: F401,F403
+8
View File
@@ -0,0 +1,8 @@
"""QtWidgets from the binding routine.qt picked."""
from routine.qt import PYSIDE
if PYSIDE:
from PySide6.QtWidgets import * # noqa: F401,F403
else:
from PyQt6.QtWidgets import * # noqa: F401,F403
+26
View File
@@ -0,0 +1,26 @@
"""The Qt binding, in one place: PySide6 (LGPL, what the installers put in), else PyQt6.
Everything imports Qt from here, e.g. `from routine.qt.QtCore import Qt, Signal`: the same names
whichever binding is underneath (PyQt6's pyqtSignal / pyqtSlot are Signal / Slot here too).
ROUTINE_QT=pyside6 or ROUTINE_QT=pyqt6 picks one (for tests); otherwise PySide6 if it imports.
"""
import importlib
import os
_WANT = os.environ.get("ROUTINE_QT", "").strip().lower()
def _pick():
order = {"pyside6": ["PySide6"], "pyqt6": ["PyQt6"]}.get(_WANT, ["PySide6", "PyQt6"])
for name in order:
try:
importlib.import_module(name + ".QtCore")
return name
except ImportError:
continue
raise ImportError("Routine needs PySide6 (pip install PySide6-Essentials, or your system's "
"python3-pyside6 package)")
API = _pick() # "PySide6" | "PyQt6"
PYSIDE = API == "PySide6"
+65
View File
@@ -0,0 +1,65 @@
"""Install/update the R1 app over adb and hand it the sync server's address + token, the desktop's
block colouring for the R1's light look, and the streak settings. The streak
settings also travel through the sync server with the streak base (routine/sync.py), which wins once the R1
has one; this copy is for an R1 that can't get one yet (an older server).
Never uninstalls (that would delete the phone's data); `install -r` keeps it.
The config goes to the app's own external files dir, which adb can write with no permission.
"""
import json
import os
import shutil
import subprocess
import tempfile
from routine import paths
PKG = "me.teafry.routine"
REMOTE_CONFIG = "/sdcard/Android/data/%s/files/config.json" % PKG
def adb():
return shutil.which("adb") or "/usr/local/sbin/adb"
def _run(*args, timeout=60):
r = subprocess.run([adb(), *args], capture_output=True, text=True, timeout=timeout)
return r.returncode, (r.stdout + r.stderr).strip()
def device():
code, out = _run("devices", timeout=10)
lines = [l.split() for l in out.splitlines()[1:] if l.strip()]
ready = [l[0] for l in lines if len(l) > 1 and l[1] == "device"]
return ready[0] if ready else None
def push_config(cfg):
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
json.dump({"sync_url": cfg.get("sync_url", ""), "sync_token": cfg.get("sync_token", ""),
"block_style": cfg.get("block_style", "chip"), # the light look's block colours
"show_year": bool(cfg.get("show_year", False)),
"streak_anims": bool(cfg.get("streak_anims", True)),
"cheat_after": paths.cheat_after(cfg)}, f) # 0 = no cheat days
tmp = f.name
try:
_run("shell", "mkdir", "-p", os.path.dirname(REMOTE_CONFIG))
return _run("push", tmp, REMOTE_CONFIG)
finally:
os.unlink(tmp)
def install(cfg):
"""Returns a one-line outcome for the Preferences page."""
if not os.path.exists(paths.APK):
return "No APK in the repo yet (android/apk/routine.apk)."
if not device():
return "No R1 found over adb. Plug it in and unlock it."
code, out = _run("install", "-r", paths.APK, timeout=180)
if code != 0 or "Success" not in out:
return "Install failed: " + out.splitlines()[-1] if out else "Install failed."
code, out = push_config(cfg)
if code != 0:
return "Installed, but couldn't send the sync settings: " + out
_run("shell", "pm", "grant", PKG, "android.permission.POST_NOTIFICATIONS")
return "Installed and set up. Open Routine on the R1."
+296
View File
@@ -0,0 +1,296 @@
"""Where the routine and the history are kept, and moving them (no Qt: tested in tests/test_storage.py).
First run and the routine (load_schedule): the user's own schedule.json always wins when it exists.
Without one:
- a first run (no history yet) starts from the template, shared/schedule.json, copied into place;
- an existing user (a routine.db already there, from before the template replaced the routine
that used to ship in the repo) is never switched to the template: a schedule.from-repo*.json
beside it (a saved copy of that old routine) is adopted, else the routine is rebuilt from the
most recent day recorded in the history (days of the week can't be told from one day: whatever
was on that day is kept, on every day).
A schedule.json that exists but can't be read is set aside (renamed, never deleted) first.
Moving (move_file): copy to a temporary name beside the target, check the copy (same bytes, and
for a database, SQLite's integrity check), put it in place, check again, and only then remove the
original. Any failure leaves the original where it was. A file already at the target is never
overwritten silently: the caller picks "use" (switch to it; ours stays where it is, untouched) or
"replace" (it's kept beside as <name>.replaced-<time><ext>, then ours goes in).
"""
import datetime as dt
import glob
import hashlib
import json
import os
import shutil
import sqlite3
import sys
import urllib.request
from routine import paths
FROM_REPO = "schedule.from-repo" # schedule.from-repo.json, schedule.from-repo.1.json, ...
def _ro(path):
"""A read-only SQLite URI for path (opening it never changes or creates the file)."""
return "file:" + urllib.request.pathname2url(os.path.abspath(path)) + "?mode=ro"
def _log(msg):
print("routine: " + msg, file=sys.stderr)
# ── reading and writing a routine ──
def valid_schedule(s):
return isinstance(s, dict) and isinstance(s.get("blocks"), list)
def read_schedule(path):
with open(path, encoding="utf-8") as f:
s = json.load(f)
if not valid_schedule(s):
raise ValueError("not a routine")
return s
def write_schedule(path, sch):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(sch, f, indent=2, ensure_ascii=False)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
def _stamp():
return dt.datetime.now().strftime("%Y%m%d-%H%M%S")
def _free_name(path, tag):
"""path with ".<tag>" before its extension, made unique with -2, -3, ..."""
stem, ext = os.path.splitext(path)
out, n = "%s.%s%s" % (stem, tag, ext), 2
while os.path.exists(out):
out, n = "%s.%s-%d%s" % (stem, tag, n, ext), n + 1
return out
# ── the first run, and existing users ──
def schedule_from_day(day):
"""A routine rebuilt from one day's snapshot (its blocks, tasks, sub-tasks, hints and calm
marks, with their ids, so the history carries on). Days of the week aren't in a snapshot."""
blocks = []
for b in day.get("blocks", []):
top = []
stack = [] # (depth, full id, item dict)
for it in b.get("items", []):
depth = int(it.get("depth", 0))
while stack and stack[-1][0] >= depth:
stack.pop()
parent_id = stack[-1][1] if stack else b["id"]
full = it["id"]
own = full[len(parent_id) + 1:] if full.startswith(parent_id + "/") else full.rsplit("/", 1)[-1]
x = {"id": own, "label": it["label"]}
if it.get("hint"):
x["hint"] = True
if it.get("calm"):
x["calm"] = True
(stack[-1][2].setdefault("items", []) if stack else top).append(x)
stack.append((depth, full, x))
blocks.append({"id": b["id"], "label": b["label"], "start": b["start"], "end": b["end"],
"color": b["color"], "items": top})
return {"rev": day.get("rev", 1), "dayStartsAt": 4, "blocks": blocks}
def latest_day(db):
"""The most recent day in a routine.db that has any blocks, read without changing the file; None if none."""
try:
con = sqlite3.connect(_ro(db), uri=True)
except sqlite3.Error:
return None
try:
for (doc,) in con.execute("SELECT doc FROM days ORDER BY date DESC"):
day = json.loads(doc)
if day.get("blocks"):
return day
except (sqlite3.Error, ValueError):
return None
finally:
con.close()
return None
def from_repo_copies(*dirs):
"""Saved copies of the routine that used to ship in the repo, newest first."""
found = set()
for d in dirs:
found.update(glob.glob(os.path.join(d, FROM_REPO + "*.json")))
return sorted(found, key=lambda p: (os.path.getmtime(p), p), reverse=True)
def load_schedule(cfg, template=None):
"""The routine to use (see the module docstring), made into the user's own schedule.json when
there wasn't one. Returns (schedule, how): how is "yours", "template", "adopted" or "rebuilt"."""
template = template or paths.SCHEDULE
path, db = paths.schedule_path(cfg), paths.db_path(cfg)
if os.path.exists(path):
try:
return read_schedule(path), "yours"
except (OSError, ValueError):
aside = _free_name(path, "unreadable-" + _stamp())
try:
os.replace(path, aside)
_log("couldn't read the routine; set it aside as " + os.path.basename(aside))
except OSError:
_log("couldn't read the routine (left as it is); using the template for now")
return read_schedule(template), "template"
if os.path.exists(db): # an existing user, from before the template
for p in from_repo_copies(os.path.dirname(path), paths.DATA):
try:
sch = read_schedule(p)
except (OSError, ValueError):
continue
write_schedule(path, sch)
_log("routine taken from " + os.path.basename(p))
return sch, "adopted"
day = latest_day(db)
if day is not None:
sch = schedule_from_day(day)
write_schedule(path, sch)
_log("routine rebuilt from the history's most recent day")
return sch, "rebuilt"
sch = read_schedule(template)
write_schedule(path, sch)
return sch, "template"
# ── moving a file to another folder ──
class MoveError(Exception):
pass
class TargetTaken(MoveError):
"""There's already a file at the target: the caller has to pick "use" or "replace"."""
def _sha(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def check_db(path):
"""Raises MoveError unless path is a sound SQLite database."""
try:
con = sqlite3.connect(_ro(path), uri=True)
try:
ok = con.execute("PRAGMA integrity_check").fetchone()[0]
con.execute("SELECT count(*) FROM days").fetchone()
finally:
con.close()
except sqlite3.Error as e:
raise MoveError("not a routine database (%s)" % e)
if ok != "ok":
raise MoveError("the database failed its check (%s)" % ok)
def check_schedule(path):
try:
read_schedule(path)
except (OSError, ValueError) as e:
raise MoveError("not a routine (%s)" % e)
def _fsync_dir(d):
try:
fd = os.open(d, os.O_RDONLY)
except OSError:
return
try:
os.fsync(fd)
except OSError:
pass
finally:
os.close(fd)
def move_file(src, dst, taken=None, check=None, copy=shutil.copyfile):
"""Move src to dst safely (the module docstring). taken: None (raise TargetTaken if dst exists),
"use" (keep dst, leave src alone) or "replace". check(path) raises MoveError for a bad file.
Returns what happened: "same", "nothing" (no src: only the location changes), "used", "moved".
On any error src is untouched, and a file that was at dst is back there."""
if os.path.abspath(src) == os.path.abspath(dst) or \
(os.path.exists(src) and os.path.exists(dst) and os.path.samefile(src, dst)):
return "same"
if not os.path.exists(src): # nothing of ours to move
if os.path.exists(dst):
if check:
check(dst)
return "used"
try:
os.makedirs(os.path.dirname(dst), exist_ok=True)
except OSError as e:
raise MoveError("can't make the folder (%s)" % e)
return "nothing"
for side in ("-wal", "-journal"):
if os.path.exists(src + side):
raise MoveError("%s is still in use (%s)" % (os.path.basename(src), os.path.basename(src + side)))
if os.path.exists(dst):
if taken is None:
raise TargetTaken(dst)
if taken == "use":
if check:
check(dst)
return "used"
if taken != "replace":
raise ValueError(taken)
folder = os.path.dirname(dst)
partial = dst + ".partial"
backup, placed = None, False
try:
os.makedirs(folder, exist_ok=True)
want = _sha(src)
copy(src, partial)
with open(partial, "rb") as f:
os.fsync(f.fileno())
if _sha(partial) != want:
raise MoveError("the copy didn't match the original")
if check:
check(partial)
if os.path.exists(dst): # taken == "replace": keep theirs beside
backup = _free_name(dst, "replaced-" + _stamp())
os.replace(dst, backup)
os.replace(partial, dst)
placed = True
_fsync_dir(folder)
if _sha(dst) != want:
raise MoveError("the file in its new place didn't match the original")
except (OSError, MoveError) as e:
try:
os.remove(partial)
except OSError:
pass
try:
if backup: # put theirs back where it was
os.replace(backup, dst)
elif placed: # a bad copy of ours: take it away again
os.remove(dst)
except OSError:
pass
if isinstance(e, MoveError):
raise
raise MoveError(str(e))
os.remove(src)
_fsync_dir(os.path.dirname(src))
return "moved"
def replaced_name(dst):
"""What a "replace" will rename the file at dst to (for the question asked first)."""
return os.path.basename(_free_name(dst, "replaced-" + _stamp()))
+107
View File
@@ -0,0 +1,107 @@
"""The desktop's record of every day: the truth for the history (the sync server only relays 60 days).
SQLite at <the data folder>/routine.db (paths.DATA, or where Settings → Data puts it), one row per day:
days(date TEXT PRIMARY KEY, doc TEXT JSON, dirty INT, mod INT)
dirty = changed here and not yet accepted by the sync server; mod counts local writes so a sync that
raced an edit doesn't mark the newer edit clean.
"""
import datetime as dt
import json
import os
import sqlite3
from routine import model
class Store:
def __init__(self, path):
self.open(path)
def open(self, path):
"""(Re)connect to the database at path, made if missing. The Store object stays the same,
so everything holding it (the side windows, the syncer) follows a move."""
os.makedirs(os.path.dirname(path), exist_ok=True)
self.path = path
self.db = sqlite3.connect(path)
self.db.execute("CREATE TABLE IF NOT EXISTS days (date TEXT PRIMARY KEY, doc TEXT NOT NULL,"
" dirty INTEGER NOT NULL DEFAULT 1, mod INTEGER NOT NULL DEFAULT 0)")
self.db.execute("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)")
self.db.commit()
def close(self):
"""Commit, fold any write-ahead log back into the file, and let it go: after this the
file on its own is the whole database (safe to copy)."""
if self.db is None:
return
self.db.commit()
try:
self.db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
except sqlite3.DatabaseError:
pass
self.db.close()
self.db = None
# ── days ──
def get(self, date):
row = self.db.execute("SELECT doc FROM days WHERE date = ?", (str(date),)).fetchone()
return json.loads(row[0]) if row else None
def range(self, start=None, end=None):
"""The day documents from start to end inclusive (ISO dates or date objects; None = open),
oldest first, in one query."""
q, args = "SELECT doc FROM days", []
if start is not None or end is not None:
q += " WHERE " + " AND ".join(c for c, v in (("date >= ?", start), ("date <= ?", end)) if v is not None)
args = [str(v) for v in (start, end) if v is not None]
return [json.loads(r[0]) for r in self.db.execute(q + " ORDER BY date", args)]
def put(self, day, dirty=True):
self.db.execute(
"INSERT INTO days (date, doc, dirty, mod) VALUES (?, ?, ?, 1) ON CONFLICT(date) DO UPDATE"
" SET doc = excluded.doc, dirty = CASE WHEN excluded.dirty = 1 THEN 1 ELSE days.dirty END,"
" mod = days.mod + 1",
(day["date"], json.dumps(day, separators=(",", ":")), int(dirty)))
self.db.commit()
def dates(self):
return [r[0] for r in self.db.execute("SELECT date FROM days ORDER BY date")]
def dirty(self):
return [(json.loads(d), m) for d, m in self.db.execute("SELECT doc, mod FROM days WHERE dirty = 1")]
def is_dirty(self, date):
row = self.db.execute("SELECT dirty FROM days WHERE date = ?", (date,)).fetchone()
return bool(row and row[0])
def mark_clean(self, date, mod):
self.db.execute("UPDATE days SET dirty = 0 WHERE date = ? AND mod = ?", (date, mod))
self.db.commit()
def set_dirty(self, date, dirty):
self.db.execute("UPDATE days SET dirty = ? WHERE date = ?", (int(dirty), date))
self.db.commit()
# ── meta ──
def meta(self, k, default=None):
row = self.db.execute("SELECT v FROM meta WHERE k = ?", (k,)).fetchone()
return row[0] if row else default
def set_meta(self, k, v):
self.db.execute("INSERT OR REPLACE INTO meta (k, v) VALUES (?, ?)", (k, str(v)))
self.db.commit()
# ── history ──
def ensure_history(self, schedule, today):
"""Every date from the first one recorded up to today gets a record, ticked or not.
Today's record picks up a newer schedule rev; past days keep the routine they had."""
first = self.meta("first_date") or (self.dates() or [today.isoformat()])[0]
self.set_meta("first_date", first)
d = dt.date.fromisoformat(first)
have = set(self.dates())
while d <= today:
if d.isoformat() not in have:
self.put(model.new_day(schedule, d))
d += dt.timedelta(days=1)
t = self.get(today.isoformat())
if model.refresh_snapshot(schedule, t):
self.put(t)
+173
View File
@@ -0,0 +1,173 @@
"""Keeps the local days and the sync server (server/routine_server.py) in step: push what changed
here, pull what changed there.
The HTTP call runs on a worker thread; merging and writing happen on the GUI thread (the
Store is single-threaded). Can't reach the server is an ordinary outcome: it just tries again.
The R1 holds only ~60 days (the server's window), so the desktop also sends a streak base
(streak_doc: model.streak_base as of STREAK_BASE_LAG days ago, plus the streak settings) for the
R1 to count on from; it goes again whenever it changes, until the server's "streaks_t" says it has
it (an old server never does, and ignores it).
"""
import datetime as dt
import json
import threading
import time
import urllib.error
import urllib.request
from routine.qt.QtCore import QObject, QTimer, Signal
from routine import model, paths
PERIOD_MS = 30_000
SOON_MS = 1_500
STREAKS_REDO_S = 600 # the streak base is remade at least this often (days that old seldom change)
def streak_doc(days, today, cfg):
"""What the R1 needs to count streaks as the desktop does: model.streak_base of days as of
STREAK_BASE_LAG days before today, with "anims" (cfg streak_anims). No "t" yet (Syncer adds it)."""
asof = (dt.date.fromisoformat(str(today)) - dt.timedelta(days=model.STREAK_BASE_LAG)).isoformat()
doc = model.streak_base(days, asof, paths.cheat_after(cfg))
doc["anims"] = bool(cfg.get("streak_anims", True))
return doc
class Syncer(QObject):
_done = Signal(object, object, object) # pushed [(date, mod)], result | None, error | None
changed = Signal(list) # dates whose record changed from the server
schedule = Signal(dict) # a newer routine came from the server
status = Signal(str)
def __init__(self, store, cfg, get_schedule, enabled=True):
"""enabled=False (macOS for now, system.sync_supported): never starts, never sends."""
super().__init__()
self.store, self.cfg, self.get_schedule = store, cfg, get_schedule
self.enabled = enabled
self.busy = False
self.again = False
self.last_ok = 0.0
self.last_error = ""
self._streaks = None # (key, doc with its "t") last made
self._streaks_acked = 0 # the t the server said it holds
self._streaks_made = 0.0
self._pushing_streaks = None
self.epoch = 0 # bumped when the database is swapped: drop answers for the old one
self._sent_epoch = 0
self._done.connect(self._apply)
self.timer = QTimer(self, interval=PERIOD_MS, timeout=self.sync_now)
if enabled:
self.timer.start()
self.soon_timer = QTimer(self, singleShot=True, interval=SOON_MS, timeout=self.sync_now)
def database_swapped(self):
"""The Store now holds another file: an answer still on its way was for the old one, and
the streak base is made afresh."""
self.epoch += 1
self._streaks, self._streaks_acked, self._pushing_streaks = None, 0, None
self.soon()
def soon(self):
if self.enabled:
self.soon_timer.start()
def sync_now(self):
if not self.enabled:
self.status.emit("coming soon on macOS")
return
if not (self.cfg.get("sync_url") and self.cfg.get("sync_token")):
self.status.emit("not set up: add the server's address and token in Settings → Sync")
return
if self.busy:
self.again = True
return
self.busy = True
dirty = self.store.dirty()
sched = self.get_schedule()
body = {"since": int(self.store.meta("seq", 0)), "days": [d for d, _ in dirty],
"schedule_rev": sched.get("rev", 0)}
if int(self.store.meta("schedule_pushed", 0)) < sched.get("rev", 0):
body["schedule"] = sched
doc = self._streak_doc(sched)
self._pushing_streaks = None
if doc is not None and doc["t"] != self._streaks_acked:
body["streaks"] = doc
self._pushing_streaks = doc["t"]
pushed = [(d["date"], m) for d, m in dirty]
url, token = self.cfg["sync_url"].rstrip("/") + "/sync", self.cfg["sync_token"]
self._sent_epoch = self.epoch
self._pushing_rev = sched.get("rev", 0) if "schedule" in body else None
threading.Thread(target=self._post, args=(url, token, body, pushed), daemon=True).start()
def _streak_doc(self, sched):
"""The streak base, remade when its asof or the settings change, else every STREAKS_REDO_S
(an edit to a day that old is rare); its t is new only when its content is (and past any
t the server holds, so it takes it)."""
try:
today = model.routine_date(sched)
asof = (today - dt.timedelta(days=model.STREAK_BASE_LAG)).isoformat()
key = (asof, paths.cheat_after(self.cfg), bool(self.cfg.get("streak_anims", True)))
if self._streaks is None or self._streaks[0] != key or time.time() - self._streaks_made > STREAKS_REDO_S:
doc = streak_doc(self.store.range(None, asof), today, self.cfg)
self._streaks_made = time.time()
if self._streaks is not None and {k: v for k, v in self._streaks[1].items() if k != "t"} == doc:
doc["t"] = self._streaks[1]["t"]
else:
doc["t"] = max(model.now_ms(), self._streaks_acked + 1)
self._streaks = (key, doc)
return self._streaks[1]
except (KeyError, TypeError, ValueError):
return None
def _post(self, url, token, body, pushed):
try:
req = urllib.request.Request(url, json.dumps(body).encode(),
{"Authorization": "Bearer " + token, "Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=20) as r:
self._done.emit(pushed, json.load(r), None)
except urllib.error.HTTPError as e:
self._done.emit(pushed, None, "the server said %d%s" % (e.code, " (check the token)" if e.code == 401 else ""))
except (OSError, ValueError) as e:
self._done.emit(pushed, None, "can't reach the server (%s)" % getattr(e, "reason", e))
def _apply(self, pushed, result, error):
self.busy = False
if self._sent_epoch != self.epoch: # sent for a database that has since been swapped
error, result = None, None
self.again = True
if result is None and not error:
pass
elif error:
self.last_error = error
self.status.emit(error)
else:
for date, mod in pushed:
self.store.mark_clean(date, mod)
changed = []
for remote in result.get("days", []):
local = self.store.get(remote["date"])
merged = model.merge(local, remote)
if merged != local:
self.store.put(merged, dirty=False)
changed.append(remote["date"])
if merged != remote: # we know something the server doesn't
self.store.set_dirty(remote["date"], True)
self.store.set_meta("seq", result.get("seq", 0))
if self._pushing_rev is not None:
self.store.set_meta("schedule_pushed", self._pushing_rev)
got = result.get("streaks_t")
if isinstance(got, int):
if self._pushing_streaks is not None and got == self._pushing_streaks:
self._streaks_acked = got
elif self._streaks is not None and got > self._streaks[1]["t"]: # the server holds a later one
self._streaks[1]["t"] = got + 1 # (a clock went back): outbid it
if isinstance(result.get("schedule"), dict):
self.schedule.emit(result["schedule"])
self.last_ok, self.last_error = time.time(), ""
self.status.emit("synced " + time.strftime("%H:%M:%S"))
if changed:
self.changed.emit(changed)
if self.again:
self.again = False
self.soon()
+197
View File
@@ -0,0 +1,197 @@
"""What differs between Linux and macOS, in one place (no Qt here, so it's tested on its own).
Every function takes plat= (a sys.platform value) and, where it reads the environment, env=, so a
test can ask "what would this be on a Mac?" from Linux. Leave them out for the machine it runs on.
data_dir() / config_dir() / log_dir() where the data, the settings and the error log go
native_frame() the OS draws the windows' frame and title bar (macOS) instead of the app
global_menubar() one menu bar at the top of the screen (macOS), not one in the window
sync_supported() the sync server and the R1 parts (Linux only for now: "coming soon" on macOS)
sound_players() command-line players to fall back on when Qt Multimedia can't play
gnome_setting() a GNOME gsettings value, or "" (never asks anything off Linux)
cursor_env() Wayland's cursor theme for Qt (Linux only)
instance_name() the local socket that keeps it to one running app per data folder
shortcut(name) a menu shortcut where the platforms want different keys
mac_app_name() the name in the macOS menu bar and Dock instead of "Python"
"""
import hashlib
import os
import shutil
import subprocess
import sys
APP_ID = "me.teafry.routine"
COMING_SOON = "Coming soon on macOS."
def is_mac(plat=None):
return (plat or sys.platform) == "darwin"
def is_linux(plat=None):
return (plat or sys.platform).startswith("linux")
def _home(env):
return env.get("HOME") or os.path.expanduser("~")
def data_dir(plat=None, env=None):
"""The routine and the history, unless Settings → Data moved them. ROUTINE_HOME wins."""
env = os.environ if env is None else env
if env.get("ROUTINE_HOME"):
return env["ROUTINE_HOME"]
if is_mac(plat):
return os.path.join(_home(env), "Library", "Application Support", "Routine")
return os.path.join(_home(env), ".local", "share", "routine")
def config_dir(plat=None, env=None):
"""config.json (the settings). On macOS the same folder as the data, as Mac apps do."""
env = os.environ if env is None else env
if env.get("ROUTINE_HOME"):
return env["ROUTINE_HOME"]
if is_mac(plat):
return data_dir(plat, env)
return os.path.join(_home(env), ".config", "routine")
def log_dir(plat=None, env=None):
"""errors.log (tracebacks only, never routine contents)."""
env = os.environ if env is None else env
if env.get("ROUTINE_HOME"):
return os.path.join(env["ROUTINE_HOME"], "logs")
if is_mac(plat):
return os.path.join(_home(env), "Library", "Logs", "Routine")
state = env.get("XDG_STATE_HOME") or os.path.join(_home(env), ".local", "state")
return os.path.join(state, "routine")
def native_frame(plat=None):
"""macOS keeps its own title bar: Qt can't resize a frameless window there (startSystemResize
is X11/Wayland/Windows only), and the traffic lights are what a Mac user reaches for. The
app's own rounded frame and title bar are for GNOME on Wayland (design.html#titlebar)."""
return is_mac(plat)
def global_menubar(plat=None):
return is_mac(plat)
def sync_supported(plat=None):
"""The sync server and installing on the Rabbit R1: Linux only until they're tested on a Mac."""
return not is_mac(plat)
def sound_players(plat=None):
"""Fallback players, in order of preference, for when Qt Multimedia isn't there or fails."""
return ["afplay"] if is_mac(plat) else ["pw-play", "paplay"]
def sound_player(plat=None):
for p in sound_players(plat):
found = shutil.which(p)
if found:
return found
return None
def audio_env(plat=None, env=None):
"""Qt's PipeWire audio backend strands its streams after a suspend (see overlay.Sounds); the
pulse one doesn't. Linux only: macOS has one backend, CoreAudio. QT_AUDIO_BACKEND still wins."""
env = os.environ if env is None else env
if is_linux(plat):
env.setdefault("QT_AUDIO_BACKEND", "pulseaudio")
def gnome_setting(schema, key, plat=None, run=subprocess.run):
"""gsettings get schema key, unquoted; "" off Linux, without gsettings, or on any trouble."""
if not is_linux(plat):
return ""
try:
out = run(["gsettings", "get", schema, key], capture_output=True, text=True, timeout=2).stdout
except (OSError, subprocess.SubprocessError):
return ""
return (out or "").strip().strip("'")
def cursor_env(plat=None, env=None, run=subprocess.run):
"""Qt on Wayland draws cursors from XCURSOR_THEME/SIZE; without them it falls back to a
small theme that doesn't match GNOME's. Hand it GNOME's before the app starts (Linux only)."""
env = os.environ if env is None else env
if not is_linux(plat):
return
for var, key in (("XCURSOR_THEME", "cursor-theme"), ("XCURSOR_SIZE", "cursor-size")):
if env.get(var):
continue
v = gnome_setting("org.gnome.desktop.interface", key, plat, run)
if v:
env[var] = v
def instance_name(home=None):
"""The QLocalServer name: the app id, plus a short hash of ROUTINE_HOME when that's set (one
app per data folder). A plain name, never a path: macOS keeps socket paths under 104 bytes."""
if not home:
return APP_ID
return APP_ID + "-" + hashlib.sha1(home.encode("utf-8", "surrogateescape")).hexdigest()[:10]
# Shortcuts that can't be the same everywhere ("Ctrl" in a Qt key sequence is ⌘ on a Mac).
# ⌘H hides the app on a Mac, so History is ⌘Y there, as in Safari.
SHORTCUTS = {
"history": {"linux": "Ctrl+H", "darwin": "Ctrl+Y"},
}
def shortcut(name, plat=None):
keys = SHORTCUTS[name]
return keys["darwin"] if is_mac(plat) else keys["linux"]
def mac_app_name(name, plat=None):
"""Make macOS call the process `name` (menu bar, Dock, Force Quit) instead of "Python". Call
before the QApplication exists. Uses only NSProcessInfo's public setProcessName:, through the
Objective-C runtime with ctypes; any trouble and it quietly does nothing. True if it was set."""
if not is_mac(plat):
return False
try:
import ctypes
import ctypes.util
objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc"))
ctypes.cdll.LoadLibrary(ctypes.util.find_library("Foundation"))
objc.objc_getClass.restype = ctypes.c_void_p
objc.objc_getClass.argtypes = [ctypes.c_char_p]
objc.sel_registerName.restype = ctypes.c_void_p
objc.sel_registerName.argtypes = [ctypes.c_char_p]
send = ctypes.cast(objc.objc_msgSend, ctypes.c_void_p).value
def msg(restype, obj, sel, *args, argtypes=()):
# objc_msgSend called through an exact prototype (arm64 doesn't allow it variadic)
fn = ctypes.CFUNCTYPE(restype, ctypes.c_void_p, ctypes.c_void_p, *argtypes)(send)
return fn(obj, objc.sel_registerName(sel), *args)
ns_string, ns_process = objc.objc_getClass(b"NSString"), objc.objc_getClass(b"NSProcessInfo")
if not ns_string or not ns_process:
return False
s = msg(ctypes.c_void_p, ns_string, b"stringWithUTF8String:", name.encode(), argtypes=(ctypes.c_char_p,))
info = msg(ctypes.c_void_p, ns_process, b"processInfo")
if not s or not info:
return False
msg(None, info, b"setProcessName:", s, argtypes=(ctypes.c_void_p,))
return True
except Exception: # noqa: BLE001 — cosmetic only: never stop the app over it
return False
def describe():
"""One line for About and the error log: the OS and Python (no names, no paths)."""
import platform
if is_mac():
osname = "macOS " + (platform.mac_ver()[0] or "?")
else:
try:
osname = platform.freedesktop_os_release().get("PRETTY_NAME", "Linux")
except (OSError, AttributeError):
osname = platform.system()
return "%s, %s, Python %s" % (osname, platform.machine(), platform.python_version())
+149
View File
@@ -0,0 +1,149 @@
"""The figures the Statistics and Journal windows show, worked out from model.History and the day
documents (pure, no Qt, so tests can reach them). Dates are ISO strings, as in model.
task_tree(schedule, hist, days, start, end) -> [block] the tasks with a record in start..end, in
the current routine's order (every weekday's, hints left out); a task or block no longer in the
routine keeps its place from the last day it had, marked "removed": True.
block = {"id", "label", "start", "end", "color", "removed", "items": [{"id", "label", "depth", "removed"}]}
next_level(n) -> (level, to go) the next streak number that's rewarded, after n
day_score(day, today) -> (done, tasks, %) hints left out; % is None with no tasks
day_lists(day, today) -> (done, not done) each [(block, [(item, state)])], in the day's order
summary(hist, days, start, end, today) -> dict the range overall (see its docstring)
cheats_in(st, start, end) -> int the cheat days a task used in start..end
"""
from routine import model
def _schedule_items(items, prefix, depth, out):
"""Every item of the routine (all weekdays), ids as model.snapshot gives them."""
seen = set()
for it in items:
iid = prefix + "/" + it.get("id", model.slug(it["label"]))
while iid in seen:
iid += "-2"
seen.add(iid)
out.append({"id": iid, "label": it["label"], "depth": depth, "hint": bool(it.get("hint")), "removed": False})
_schedule_items(it.get("items", []), iid, depth + 1, out)
def _in_range(st, start, end):
return any(start <= d <= end for d in st.status)
def task_tree(schedule, hist, days, start, end):
start, end = str(start), str(end)
present = {iid for iid, st in hist.items.items() if _in_range(st, start, end)}
out, where = [], {} # where: item id -> its block in out
for b in schedule.get("blocks", []):
items = []
_schedule_items(b.get("items", []), b["id"], 0, items)
blk = {"id": b["id"], "label": b["label"], "start": b["start"], "end": b["end"], "color": b["color"],
"removed": False, "items": [it for it in items if it["id"] in present and not it["hint"]]}
out.append(blk)
for it in blk["items"]:
where[it["id"]] = blk
missing = present - set(where)
if missing:
# the last snapshot each one had, newest day first: it says where it sat
for day in sorted(days, key=lambda d: d["date"], reverse=True):
if not missing:
break
prev_block = None
for b in day.get("blocks", []):
ids = [it["id"] for it in b.get("items", []) if not it.get("hint")]
for k, it in enumerate(b.get("items", [])):
if it["id"] not in missing or it.get("hint"):
continue
blk = next((x for x in out if x["id"] == b["id"]), None)
if blk is None: # its block went too: bring that back, after the one before
blk = {"id": b["id"], "label": b["label"], "start": b["start"], "end": b["end"],
"color": b["color"], "removed": True, "items": []}
at = next((n + 1 for n, x in enumerate(out) if prev_block and x["id"] == prev_block), 0)
out.insert(at, blk)
st = hist.items[it["id"]]
row = {"id": it["id"], "label": st.label, "depth": st.depth, "removed": True}
pos = 0 # after the nearest task above it that's listed
for pid in reversed(ids[:ids.index(it["id"])] if it["id"] in ids else []):
n = next((n for n, x in enumerate(blk["items"]) if x["id"] == pid), None)
if n is not None:
pos = n + 1
break
blk["items"].insert(pos, row)
where[it["id"]] = blk
missing.discard(it["id"])
prev_block = b["id"]
return [b for b in out if b["items"]]
def next_level(n):
"""(the next rewarded streak number after n, days to go)."""
for v in model.STREAK_LEVELS:
if v > n:
return v, v - n
top = model.STREAK_LEVELS[-1]
v = top + ((n - top) // model.STREAK_EVERY + 1) * model.STREAK_EVERY
return v, v - n
def day_score(day, today):
marks = model.day_marks(day, today)[0]
done = sum(m == model.S_DONE for m in marks.values())
return done, len(marks), (100.0 * done / len(marks) if marks else None)
def day_lists(day, today):
"""([(block, [(item, state)])] done, the same for the rest), hints left out, empty blocks dropped."""
got, rest = [], []
for b in day.get("blocks", []):
g, r = [], []
for it in b.get("items", []):
if it.get("hint"):
continue
s = model.state(day, it["id"])
(g if s == model.DONE else r).append((it, s))
if g:
got.append((b, g))
if r:
rest.append((b, r))
return got, rest
def cheats_in(st, start, end):
return sum(1 for d, s in st.status.items() if s == model.S_CHEAT and start <= d <= end)
def summary(hist, days, start, end, today):
"""The range overall:
days (day documents in it), counted (those before today: today is still open),
done / scheduled / pct (task-days, as Streak.totals: done of done + missed + cheat days),
perfect (days every task got ticked), cheats (cheat days used) / cheat_tasks (tasks that used one),
best: [(Streak, Run)] the longest streaks ending in the range, longest first (ties: earliest first),
going: [(Streak, n)] the streaks alive now, longest first (tasks with a record in the range)."""
start, end, today = str(start), str(end), str(today)
inside = [d for d in days if start <= d["date"] <= end]
done = sched = cheats = cheat_tasks = 0
best, going = [], []
for st in hist.items.values():
if not _in_range(st, start, end):
continue
d, s, _ = st.totals(start, end)
done, sched = done + d, sched + s
c = cheats_in(st, start, end)
cheats += c
cheat_tasks += c > 0
r = st.longest_run(start, end)
if r:
best.append((st, r))
if st.current:
going.append((st, st.current))
best.sort(key=lambda x: (-x[1].length, x[1].end))
going.sort(key=lambda x: -x[1])
perfect = 0
for day in inside:
if day["date"] >= today:
continue
g, n, _ = day_score(day, today)
perfect += bool(n) and g == n
return {"days": len(inside), "counted": sum(d["date"] < today for d in inside), "done": done,
"scheduled": sched, "pct": 100.0 * done / sched if sched else None, "perfect": perfect,
"cheats": cheats, "cheat_tasks": cheat_tasks, "best": best, "going": going}
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env bash
# Build Routine.app and a drag-to-install Routine-<version>.dmg, on a Mac, from a checkout.
# UNTESTED ON A MAC so far: see docs/building-the-mac-app.md (what to run, what to send back).
#
# scripts/build-mac-app.sh → dist/Routine.app and dist/Routine-<version>.dmg
#
# Needs: macOS 13+, curl, an internet connection. No Xcode, no Homebrew, no admin password: like
# install-mac.sh it fetches uv, which fetches its own Python and the pinned packages, all under
# build/mac/. PyInstaller freezes the app (Python and Qt inside the bundle), the bundle is signed
# ad hoc (codesign -s -: no Apple developer account, so not notarized: macOS asks once before the
# first open, see the doc), and the .dmg holds the app beside a shortcut to /Applications.
# The app is for the build machine's kind of Mac: built on Apple silicon it runs on Apple silicon.
#
# BUILD_TEST=1 lets the PyInstaller part run off a Mac (to test the freezing; no .app, no .dmg).
set -euo pipefail
REPO="$(cd "$(dirname "$0")/.." && pwd)"
UV_VERSION="0.10.4"
PYTHON_VERSION="3.13"
PINS=(PySide6-Essentials==6.11.0 pyinstaller==6.22.3)
OUT="$REPO/dist"
WORK="$REPO/build/mac"
die() { printf 'build-mac-app: %s\n' "$*" >&2; exit 1; }
MAC=0
[ "$(uname -s)" = Darwin ] && MAC=1
[ "$MAC" = 1 ] || [ "${BUILD_TEST:-}" = 1 ] || die "run this on a Mac (BUILD_TEST=1 to try the freezing elsewhere)"
VERSION="$(sed -n 's/^__version__ = "\(.*\)"/\1/p' "$REPO/routine/__init__.py")"
[ -n "$VERSION" ] || die "no __version__ in routine/__init__.py"
rm -rf "$WORK/work" "$WORK/dist" "$WORK/dmg"
mkdir -p "$WORK" "$OUT"
# ── uv → Python → PySide6 + PyInstaller, all under build/mac ──
export UV_PYTHON_INSTALL_DIR="$WORK/python" UV_CACHE_DIR="$WORK/cache" UV_PYTHON_PREFERENCE=only-managed UV_NO_CONFIG=1
UV="${ROUTINE_UV:-$WORK/uv/uv}"
if [ ! -x "$UV" ]; then
echo "Downloading uv $UV_VERSION …"
curl -LsSf "https://astral.sh/uv/$UV_VERSION/install.sh" |
env UV_UNMANAGED_INSTALL="$WORK/uv" INSTALLER_NO_MODIFY_PATH=1 sh >/dev/null || die "couldn't download uv"
fi
[ -x "$WORK/venv/bin/python" ] || "$UV" venv --quiet --python "$PYTHON_VERSION" "$WORK/venv"
"$UV" pip install --quiet --python "$WORK/venv/bin/python" "${PINS[@]}"
PY="$WORK/venv/bin/python"
# ── freeze ──
echo "Freezing Routine $VERSION …"
ICON=()
[ "$MAC" = 1 ] && ICON=(--icon "$REPO/shared/icon.icns" --osx-bundle-identifier me.teafry.routine)
(cd "$REPO" && "$PY" -m PyInstaller --noconfirm --clean --log-level WARN --windowed --name Routine \
"${ICON[@]}" \
--add-data "$REPO/shared:shared" \
--exclude-module PyQt6 --exclude-module PyQt5 --exclude-module tkinter \
--paths "$REPO" \
--distpath "$WORK/dist" --workpath "$WORK/work" --specpath "$WORK" \
"$REPO/routine/__main__.py")
if [ "$MAC" != 1 ]; then
echo "BUILD_TEST: frozen into $WORK/dist/Routine (no .app or .dmg off a Mac)."
exit 0
fi
APP="$WORK/dist/Routine.app"
[ -d "$APP" ] || die "PyInstaller made no Routine.app"
PLIST="$APP/Contents/Info.plist"
plutil -replace CFBundleName -string Routine "$PLIST"
plutil -replace CFBundleDisplayName -string Routine "$PLIST"
plutil -replace CFBundleShortVersionString -string "$VERSION" "$PLIST"
plutil -replace CFBundleVersion -string "$VERSION" "$PLIST"
plutil -replace LSMinimumSystemVersion -string 13.0 "$PLIST"
plutil -replace NSHighResolutionCapable -bool true "$PLIST"
plutil -replace LSApplicationCategoryType -string public.app-category.productivity "$PLIST"
echo "Signing (ad hoc) …"
codesign --force --deep --sign - "$APP"
codesign --verify --deep --strict "$APP" || die "the signature doesn't verify"
echo "Making the .dmg …"
STAGE="$WORK/dmg"
mkdir -p "$STAGE"
cp -R "$APP" "$STAGE/"
ln -s /Applications "$STAGE/Applications"
DMG="$OUT/Routine-$VERSION.dmg"
rm -f "$DMG"
hdiutil create -quiet -volname "Routine $VERSION" -srcfolder "$STAGE" -ov -format UDZO "$DMG"
rm -rf "$OUT/Routine.app"
cp -R "$APP" "$OUT/"
echo
echo "Done: $DMG ($(du -h "$DMG" | cut -f1)), for $(uname -m) Macs."
echo "Try it: open the .dmg, drag Routine to Applications, open it from there."
+53
View File
@@ -0,0 +1,53 @@
#!/bin/bash
# Deploy routine-server (server/) to a machine you can ssh into, and (re)start it in a screen session.
#
# scripts/deploy-server.sh HOST copy the code and restart the server
# scripts/deploy-server.sh HOST --stop stop it
# scripts/deploy-server.sh HOST --token print the bearer token for the apps' Settings → Sync
#
# HOST is an ssh destination (user@host, or an alias from ~/.ssh/config); DEPLOY_HOST works too.
# The rest comes from the environment:
# DEPLOY_DIR folder on HOST, relative to its home or absolute (default routine-server)
# ROUTINE_SERVER_HOST address the server listens on (default 127.0.0.1: only HOST itself;
# use an address your devices reach privately, e.g. a VPN one)
# ROUTINE_SERVER_PORT port (default 8070)
# It needs ssh, rsync, and on HOST python3, screen and curl. To start it at boot, have HOST run
# DEPLOY_DIR/app/run.sh (it reads the settings this script leaves in DEPLOY_DIR/app/server.env).
set -euo pipefail
HOST=${DEPLOY_HOST:-}
ACTION=deploy
for a in "$@"; do
case "$a" in
--stop) ACTION=stop ;;
--token) ACTION=token ;;
-h|--help) sed -n '2,16p' "$0"; exit 0 ;;
*) HOST=$a ;;
esac
done
[ -n "$HOST" ] || { echo "usage: $0 HOST [--stop|--token] (or set DEPLOY_HOST)" >&2; exit 2; }
DIR=${DEPLOY_DIR:-routine-server}
BIND=${ROUTINE_SERVER_HOST:-127.0.0.1}
PORT=${ROUTINE_SERVER_PORT:-8070}
NAME=routine-server
cd "$(dirname "$0")/.."
case "$ACTION" in
token) ssh "$HOST" "cat '$DIR/data/token'"; echo; exit 0 ;;
stop) ssh "$HOST" "screen -S $NAME -X quit || true"; echo "stopped"; exit 0 ;;
esac
ssh "$HOST" "mkdir -p '$DIR/app' '$DIR/data' && chmod 700 '$DIR/data'"
rsync -a server/routine_server.py server/run.sh routine/model.py "$HOST:$DIR/app/"
printf 'ROUTINE_SERVER_HOST=%q\nROUTINE_SERVER_PORT=%q\n' "$BIND" "$PORT" | ssh "$HOST" "cat > '$DIR/app/server.env'"
CHECK=$BIND
[ "$CHECK" = "0.0.0.0" ] && CHECK=127.0.0.1
ssh "$HOST" bash -s <<REMOTE
set -e
cd '$DIR'
screen -S $NAME -X quit 2>/dev/null || true
sleep 1
screen -dmS $NAME bash -c "bash '\$PWD/app/run.sh' 2>&1 | tee '\$PWD/server.log'"
sleep 2
for pid in \$(pgrep -f routine_server.py); do echo 1000 > /proc/\$pid/oom_score_adj 2>/dev/null || true; done # first to go if memory runs out
curl -s -m 5 http://$CHECK:$PORT/health; echo
REMOTE
+36
View File
@@ -0,0 +1,36 @@
#!/bin/bash
# Put Routine in the app grid so it can be pinned to the dash. Re-run after moving the repo.
# (Runs this checkout as it is: for a copy of its own, updated by re-running, see install-linux.sh.)
set -euo pipefail
REPO="$(cd "$(dirname "$0")/.." && pwd)"
APPS=~/.local/share/applications
HICOLOR=~/.local/share/icons/hicolor
ICON="$HICOLOR/scalable/apps/me.teafry.routine.svg"
mkdir -p "$APPS" "$HICOLOR/scalable/apps"
cp "$REPO/shared/icon.svg" "$ICON"
# fixed sizes too, for whatever doesn't read SVG (rendered with Qt, which the app needs anyway)
for n in 48 64 128 256; do
mkdir -p "$HICOLOR/${n}x${n}/apps"
QT_QPA_PLATFORM=offscreen PYTHONPATH="$REPO" python3 -c "
import sys
from routine.qt.QtGui import QGuiApplication, QIcon
a = QGuiApplication(sys.argv)
QIcon(sys.argv[1]).pixmap(int(sys.argv[2]), int(sys.argv[2])).save(sys.argv[3])" \
"$REPO/shared/icon.svg" "$n" "$HICOLOR/${n}x${n}/apps/me.teafry.routine.png" 2>/dev/null
done
cat > "$APPS/me.teafry.routine.desktop" <<DESKTOP
[Desktop Entry]
Type=Application
Name=Routine
Comment=The day's routine, ticked off as you go
Exec=python3 -m routine
Path=$REPO
Icon=$ICON
Terminal=false
Categories=Utility;
StartupWMClass=me.teafry.routine
StartupNotify=true
DESKTOP
update-desktop-database "$APPS" 2>/dev/null || true
gtk-update-icon-cache -q -t -f "$HICOLOR" 2>/dev/null || true
echo "Installed: search for Routine in Activities, then right-click → Pin to Dash."
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""routine-server: the relay that keeps the desktop and R1 routine apps in step, on a machine of
your own that both can reach (a home server, a VPN address).
Standard library only, and model.py beside it (scripts/deploy-server.sh copies both). Every
request but /health needs "Authorization: Bearer <token>" (made on first start in <data>/token,
mode 600). It speaks plain HTTP: bind it to an address only your devices reach (a private network
or VPN), not the open internet.
GET /health -> {"ok": true}
POST /sync {"since": <seq>, "days": [<day>, ...], "schedule_rev": n, "schedule": {...}?,
"streaks": {...}?, "streaks_t": t?}
-> {"seq": <seq>, "days": [<every stored day changed after since>], "schedule": {...}?,
"streaks": {...}?, "streaks_t": t?}
The routine itself rides along: a client may send its schedule (the desktop does after an
edit); the server keeps the highest rev and hands it to any client whose schedule_rev is lower.
The streak base rides the same way (model.streak_base plus "t" and the desktop's streak
settings): the desktop sends it, the server keeps the one with the highest "t" and answers
every sync with that t as "streaks_t" (the desktop's receipt); a client that sends "streaks_t"
(the R1) gets the base back whenever the server's is newer. Clients that send neither (older
apps) never see it, and older servers ignore both: the R1 then counts from its own days.
A pushed day is merged into the stored copy with model.merge (last writer wins per item and
for the note), and gets a new seq only if the merge changed it. A client keeps the returned
seq and sends it as since next time; since > the server's seq (a fresh server) means "all".
The server is a relay, not the record: days older than KEEP_DAYS are dropped; the desktop keeps
everything.
python3 routine_server.py --host ADDRESS --port 8070 --data DIR
"""
import argparse
import datetime as dt
import json
import os
import secrets
import sqlite3
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import model # noqa: E402 (deployed beside this file)
KEEP_DAYS = 60
MAX_BODY = 4 * 1024 * 1024
LOCK = threading.Lock()
class Store:
def __init__(self, path):
self.db = sqlite3.connect(path, check_same_thread=False)
self.db.execute("CREATE TABLE IF NOT EXISTS days (date TEXT PRIMARY KEY, doc TEXT NOT NULL, seq INTEGER NOT NULL)")
self.db.execute("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)")
self.db.commit()
def seq(self):
return self.db.execute("SELECT COALESCE(MAX(seq), 0) FROM days").fetchone()[0]
def sync(self, since, pushed, schedule=None, schedule_rev=0, streaks=None, streaks_t=None):
with LOCK:
row = self.db.execute("SELECT v FROM meta WHERE k = 'streaks'").fetchone()
base = json.loads(row[0]) if row else None
if valid_streaks(streaks) and (base is None or streaks["t"] > base.get("t", 0)):
base = streaks
self.db.execute("INSERT OR REPLACE INTO meta (k, v) VALUES ('streaks', ?)", (json.dumps(base),))
row = self.db.execute("SELECT v FROM meta WHERE k = 'schedule'").fetchone()
stored = json.loads(row[0]) if row else None
if isinstance(schedule, dict) and isinstance(schedule.get("blocks"), list) and \
(stored is None or schedule.get("rev", 0) > stored.get("rev", 0)):
stored = schedule
self.db.execute("INSERT OR REPLACE INTO meta (k, v) VALUES ('schedule', ?)", (json.dumps(stored),))
cutoff = (dt.date.today() - dt.timedelta(days=KEEP_DAYS)).isoformat()
self.db.execute("DELETE FROM days WHERE date < ?", (cutoff,))
seq = self.seq()
for day in pushed:
date = day.get("date", "")
try:
dt.date.fromisoformat(date)
except (TypeError, ValueError):
continue
if date < cutoff:
continue
row = self.db.execute("SELECT doc FROM days WHERE date = ?", (date,)).fetchone()
old = json.loads(row[0]) if row else None
merged = model.merge(old, day)
if merged != old:
seq += 1
self.db.execute("INSERT OR REPLACE INTO days (date, doc, seq) VALUES (?, ?, ?)",
(date, json.dumps(merged, separators=(",", ":")), seq))
self.db.commit()
if since > seq:
since = 0
rows = self.db.execute("SELECT doc FROM days WHERE seq > ? ORDER BY date", (since,)).fetchall()
out = {"seq": seq, "days": [json.loads(r[0]) for r in rows]}
if stored is not None and stored.get("rev", 0) > schedule_rev:
out["schedule"] = stored
if base is not None:
out["streaks_t"] = base.get("t", 0)
if streaks_t is not None and base.get("t", 0) > streaks_t:
out["streaks"] = base
return out
def valid_streaks(s):
"""A streak base worth keeping: {"t": int, "asof": "YYYY-MM-DD", "items": {...}, ...}."""
if not isinstance(s, dict) or not isinstance(s.get("items"), dict) or type(s.get("t")) is not int:
return False
try:
dt.date.fromisoformat(s.get("asof"))
except (TypeError, ValueError):
return False
return True
class Handler(BaseHTTPRequestHandler):
server_version = "routine-server"
def _send(self, code, obj):
body = json.dumps(obj, separators=(",", ":")).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _authed(self):
got = self.headers.get("Authorization", "")
return secrets.compare_digest(got.encode(), ("Bearer " + self.server.token).encode())
def do_GET(self):
if self.path == "/health":
return self._send(200, {"ok": True})
self._send(404, {"error": "not found"})
def do_POST(self):
if self.path != "/sync":
return self._send(404, {"error": "not found"})
if not self._authed():
return self._send(401, {"error": "unauthorized"})
n = int(self.headers.get("Content-Length") or 0)
if n > MAX_BODY:
return self._send(413, {"error": "too large"})
try:
req = json.loads(self.rfile.read(n) or b"{}")
since = int(req.get("since", 0))
days = req.get("days", [])
if not isinstance(days, list):
raise ValueError("days")
sched, srev = req.get("schedule"), int(req.get("schedule_rev", 0))
st = int(req["streaks_t"]) if req.get("streaks_t") is not None else None
except (ValueError, TypeError) as e:
return self._send(400, {"error": "bad request: %s" % e})
self._send(200, self.server.store.sync(since, days, sched, srev, req.get("streaks"), st))
def log_message(self, fmt, *args):
sys.stderr.write("%s %s\n" % (self.log_date_time_string(), fmt % args))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, default=8070)
ap.add_argument("--data", required=True)
a = ap.parse_args()
os.makedirs(a.data, exist_ok=True)
tok_path = os.path.join(a.data, "token")
if not os.path.exists(tok_path):
fd = os.open(tok_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as f:
f.write(secrets.token_urlsafe(32))
srv = ThreadingHTTPServer((a.host, a.port), Handler)
srv.token = open(tok_path).read().strip()
srv.store = Store(os.path.join(a.data, "routine.db"))
print("routine-server on %s:%d" % (a.host, a.port), flush=True)
srv.serve_forever()
if __name__ == "__main__":
main()
Executable
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
# The one command line for routine-server (scripts/deploy-server.sh runs it; so can a boot script).
# Settings come from server.env beside this file (written by deploy-server.sh) or the environment:
# ROUTINE_SERVER_HOST address to listen on (default 127.0.0.1)
# ROUTINE_SERVER_PORT port (default 8070)
# ROUTINE_SERVER_DATA data folder: routine.db + token (default ../data next to this folder)
cd "$(dirname "$0")" || exit 1
[ -f server.env ] && . ./server.env
exec python3 routine_server.py --host "${ROUTINE_SERVER_HOST:-127.0.0.1}" --port "${ROUTINE_SERVER_PORT:-8070}" \
--data "${ROUTINE_SERVER_DATA:-$(cd .. && pwd)/data}"
+265
View File
@@ -0,0 +1,265 @@
# The check-off animations
Generated by `tools/gen_animations.py` (don't edit by hand). The first 5 ticks of a day draw at random
from set 0, the next 5 from set 1, and so on; past the last set, the last set keeps playing and
**the star** plays as well, which means it's time to ask for more animations. Picks are purely random
within a set: nothing remembers what has played, so repeats can happen.
Every name and every sound is used once; the generator refuses duplicates.
## Set 0 (ticks 1–5, 40 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| 1 | bloom | red | plip | A stem shoots up and a five-petal flower pops open, then sheds a petal. |
| 2 | rocket | blue | whoosh | Wobbles in the box, then blasts off upward with a flickering flame and puffs. |
| 3 | starburst | yellow | chime | Rays shoot out of the box, grow, then fly off as dashes. |
| 4 | bounce | red | boing | A ball pops out and bounces off to the right, squashing on every landing. |
| 5 | jack | blue | sproing | A jack-in-the-box spring boings up and wobbles side to side. |
| 6 | balloon | red | pop | A balloon floats up out of the box, swaying, then pops. |
| 7 | firework | yellow | fizzbang | A rocket trail climbs, then bursts into a dandelion of sparks that droop. |
| 8 | bird | blue | tweet | A little bird flaps out of the box and away up to the right. |
| 9 | sprout | yellow | kalimba | A vine climbs out of the box in fits and starts, sprouting leaves left and right. |
| 10 | confetti | red | rattle | A cannon of tumbling paper squares that arcs out and flutters down. |
| 11 | worm | blue | wobble | A worm wriggles out of the box and inches off to the right. |
| 12 | lightning | yellow | zap | A bolt cracks up out of the box, flashes twice, and leaves sparks. |
| 13 | spiral | red | slide | A spiral unwinds out of the box, turning a notch each frame, then springs away. |
| 14 | heart | red | thump | A heart thumps its way up out of the box, big-small-big. |
| 15 | fish | blue | splash | A fish leaps out of the box in an arc and dives back in with a splash. |
| 16 | sun | yellow | rise | The sun rises out of the box; its rays click round one notch per frame. |
| 17 | ripples | blue | drip | Rings spread out of the box, a new one every few frames, thinning as they go. |
| 18 | tentacle | red | bloop | A tentacle reaches out of the box, curls its tip, waves and uncurls. |
| 19 | butterfly | yellow | flutter | A butterfly flutters up out of the box, wings snapping open and shut. |
| 20 | ghost | blue | boo | A little ghost bobs up out of the box, says boo with a wide mouth, then fades to dots. |
| 21 | popcorn | yellow | popple | Kernels pop out of the box one after another, puff up and tumble down. |
| 22 | yoyo | red | zipzip | A yo-yo is flung up out of the box on its string, spins at the top, and zips back down. |
| 23 | jellyfish | blue | wubwub | A jellyfish pulses its way up out of the box, bell squeezing, tentacles trailing. |
| 24 | comet | yellow | streak | A comet bursts out of the box and streaks across, its tail breaking into dust. |
| 25 | flag | red | flap | A flagpole shoots up out of the box and its flag ripples out in the wind. |
| 26 | exclaim | red | ding | A big exclamation mark springs up out of the box and wobbles, delighted. |
| 27 | robot | blue | beepboop | A boxy robot head rises out of the box, antenna blinking, eyes looking about. |
| 28 | helicopter | blue | chop | A little helicopter lifts out of the box, rotor chopping, and buzzes away. |
| 29 | sailboat | blue | lapping | A sailboat bobs out of the box onto the waves and sails off to the right. |
| 30 | lollipop | red | twirl | A lollipop pops up out of the box and its swirl spins round in clicks. |
| 31 | cupcake | red | toot | A cupcake rises out of the box, a candle on top flickers, and puffs out. |
| 32 | planet | yellow | orbit | A ringed planet rises out of the box while a little moon whips round it. |
| 33 | hammer | yellow | bonk | A toy hammer swings down on the box three times: bonk, bonk, BONK, with stars. |
| 34 | boxingglove | red | punch | A boxing glove on a zigzag spring punches out of the box: POW. |
| 35 | turtle | blue | plod | A turtle pokes its head and feet out of its shell and plods out of the box. |
| 36 | owl | yellow | hoot | An owl pops up out of the box, blinks its big eyes, and swivels its head. |
| 37 | icecream | red | plop | An ice-cream cone pops out of the box and scoops drop onto it, plop plop plop. |
| 38 | sparkler | yellow | crackle | A sparkler pops up out of the box, fizzing, and writes a loop in the air. |
| 39 | spider | blue | dangle | A spider drops from above on its thread, bounces on the box, and climbs back up. |
| 40 | parachute | blue | floaty | A parachute pops open high above and floats a little crate gently down onto the box. |
## Set 1 (ticks 6–10, 20 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| 41 | frog | blue | ribbit | A frog crouches in the box, leaps up and over, flicks its tongue at a fly, lands. |
| 42 | snail | yellow | squelch | A snail slides out of the box, its eye stalks waving, leaving a trail. |
| 43 | cat | red | mew | A cat pops its head up out of the box, looks about, winks, twitches its whiskers. |
| 44 | umbrella | blue | fwump | An umbrella shoots up out of the box and pops open; raindrops bounce off it. |
| 45 | paperplane | yellow | swish | A paper plane darts out of the box and does a loop-the-loop, trailing dashes. |
| 46 | kite | red | breeze | A kite climbs out of the box in a zigzag, its bow tail flapping. |
| 47 | snowflake | blue | tinkle | A snowflake crystallises out of the box arm by arm, ticking round as it drifts up. |
| 48 | raincloud | blue | patter | A cloud puffs up out of the box and rains a little shower on it. |
| 49 | moon | yellow | lullaby | A crescent moon rises out of the box; little stars blink on around it. |
| 50 | tree | red | creak | A tree grows out of the box: trunk, then branches split, then a canopy pops on. |
| 51 | mushroom | red | pomp | A mushroom pushes up out of the box, its spotted cap boinging. |
| 52 | volcano | red | rumble | A volcano heaves up out of the box and spits blobs of lava that arc and fall. |
| 53 | whale | blue | spout | A whale's back rolls up out of the box and blows a fan-shaped spout. |
| 54 | ufo | yellow | warble | A flying saucer swoops down over the box, beams at it, and zips away. |
| 55 | crab | red | clack | A crab scuttles sideways out of the box, snapping its claws. |
| 56 | notes | blue | tune | Music notes bubble up out of the box, one after another, swaying. |
| 57 | pinwheel | yellow | whirr | A pinwheel on a stick pops up and spins in big 45-degree clicks. |
| 58 | bubbles | blue | blub | Soap bubbles wobble up out of the box and pop one by one. |
| 59 | target | red | thunk | A target appears; an arrow flies out of the box and thunks into the bullseye. |
| 60 | dice | yellow | clatter | Two dice tumble out of the box, clatter, and land showing double six. |
## Set 2 (ticks 11–15, 10 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| 61 | hourglass | blue | trickle | An hourglass rises out of the box, flips over in clicks, and sand trickles down. |
| 62 | gem | red | sparkle | A cut gem flips up out of the box, facets and all, and throws off sparkles. |
| 63 | padlock | yellow | click | A padlock rises out of the box; its shackle springs open and it hops for joy. |
| 64 | trophy | yellow | fanfare | A trophy cup rises out of the box on its plinth and shines. |
| 65 | crown | red | regal | A crown drops from above onto the box, bounces, and its jewels glint. |
| 66 | rainbow | red | shimmer | A rainbow of nested arcs grows out of the box and lands to the right. |
| 67 | tornado | blue | howl | A little twister spins up out of the box and wanders off to the right. |
| 68 | bee | yellow | buzz | A bee buzzes out of the box in a figure of eight, leaving a dotted trail. |
| 69 | bat | blue | squeak | A bat flaps out of the box in jerky swoops. |
| 70 | chick | yellow | cheep | An egg pops out of the box, wobbles, cracks, and a chick peeks out. |
## The calm set (2 s each, 40 animations)
Only for tasks marked *calm animation*: one of these plays instead of the set's, never the star.
The tick still counts toward the next set.
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| c1 | fog | blue | hush | Banks of fog drift slowly across the box in soft layers, then thin away. |
| c2 | canoe | red | paddle | A canoe glides out across still water, the paddle dipping in slow strokes. |
| c3 | yarn | red | unspool | A ball of yarn rolls lazily out of the box, unwinding a loose thread behind it. |
| c4 | candle | yellow | glow | A candle rises out of the box and its flame sways, slow and steady. |
| c5 | grass | yellow | rustle | Tufts of grass grow up around the box and lean, all together, in a soft wind. |
| c6 | stream | blue | babble | A little stream flows past the box, its ripples sliding steadily along. |
| c7 | catnap | red | purr | A cat settles down beside the box, curls its tail round, and dozes off. |
| c8 | squirrel | red | nibble | A squirrel scampers along a branch above the box, sits up, and nibbles an acorn. |
| c9 | dove | blue | coo | A bird glides out of the box and away, with only a couple of slow wingbeats. |
| c10 | cake | yellow | warmth | A freshly baked cake rises out of the box, still warm, with steam drifting off it. |
| c11 | pie | red | waft | A pie slides out of the oven onto the box, its lattice golden, steam curling up. |
| c12 | teacup | blue | steep | A teacup on its saucer; the teabag's tag sways on its string while the tea steeps. |
| c13 | lantern | red | flicker | A paper lantern lowers on its cord and sways gently, glowing. |
| c14 | leaf | yellow | drift | A single leaf drifts down from above, rocking side to side, and settles on the box. |
| c15 | wateringcan | blue | sprinkle | A watering can tips over the box and a sprinkle of drops falls on a little bud. |
| c16 | firefly | yellow | crickets | A few fireflies drift about over the box, each glowing and dimming in its own time. |
| c17 | dandelion | yellow | airy | A dandelion clock stands by the box; one by one its seeds float off on the air. |
| c18 | lotus | red | still | On still water beside the box, a lotus opens its petals, slowly, one ring at a time. |
| c19 | hammock | blue | sway | A hammock strung between two posts sways, slow as breathing. |
| c20 | windchime | yellow | tingle | A wind chime turns a little in the breeze, its tubes swinging out of step. |
| c21 | cumulus | blue | airflow | A puffy cloud drifts slowly over the box, its puffs swelling and settling. |
| c22 | aurora | blue | drone | Curtains of light ripple above the box, folding and unfolding. |
| c23 | tide | blue | surf | A wave washes gently up toward the box, lays down a shell, and slides back out. |
| c24 | lighthouse | red | foghorn | A lighthouse stands by the box, its beam sweeping slowly round. |
| c25 | moth | yellow | flit | A small moth loops slowly round a lamp above the box. |
| c26 | breath | blue | inhale | A ring swells slowly out of the box for one breath in, then shrinks back for the breath out. |
| c27 | rake | yellow | sand | Lines are raked, one after another, into a little sand garden beside the box. |
| c28 | cairn | blue | stack | Smooth stones settle one onto another in a little stack on the box. |
| c29 | fern | yellow | dew | A fern frond uncurls from a tight spiral beside the box, leaflet by leaflet. |
| c30 | sloth | red | yawn | A sloth hangs from a branch over the box and, very slowly, turns its head to look. |
| c31 | koi | red | glide | A koi swims a slow circle round the box, its tail sweeping. |
| c32 | constellation | yellow | celesta | Stars wink on one by one above the box and are joined, softly, into a constellation. |
| c33 | honey | yellow | ooze | A honey dipper above the box lets a slow golden thread fall and pool. |
| c34 | quilt | red | stitch | Patches are laid down one by one into a little quilt above the box, then stitched. |
| c35 | book | blue | page | A book lies open above the box and a page turns over, slowly. |
| c36 | campfire | red | embers | A small campfire burns low beside the box; embers drift up and fade. |
| c37 | bowl | yellow | hum | A singing bowl sits on the box; the striker circles its rim and soft rings rise off it. |
| c38 | nest | red | nestle | Twigs weave into a nest on the box, and three eggs settle into it. |
| c39 | ink | blue | seep | A drop of ink falls into water above the box and blooms into slow curling clouds. |
| c40 | rockingchair | red | rocker | An empty rocking chair rocks to and fro beside the box, slower and slower. |
## The star (2 s, all three colours)
| name | sound | what happens |
|---|---|---|
| star_special | twinkle | THE STAR: a big star spins up out of the box, pulses, flies up and bursts into little stars. |
## Streak animations (2 s each, each shows the streak number)
A task ticked by hand whose streak reaches a level plays one of that level's instead of its set's
(a calm task, one of the calm streak ones). A level with none yet falls back to the nearest lower one.
Modules: `tools/streak_anims/levelK.py` and `calm.py`, sounds beside them in `*_sounds.py`.
### Level 0: streak 7 (8 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| s0.1 | megaphone | yellow | blare | A megaphone pops up out of the box and blares: sound waves pulse out and the number bursts from its mouth, bigger with every pulse. |
| s0.2 | slotmachine | red | jackpot | A slot machine rises beside the box; its lever is pulled, the reel whirs, and it lands on the number as lights flash and coins spill out. |
| s0.3 | bannerplane | blue | propeller | A little plane buzzes across above the box towing a banner with the number on it, the banner rippling in its wake. |
| s0.4 | cannon | red | kaboom | A little cannon rolls out by the box, its fuse fizzes, and BOOM: the number is fired high in an arc and lands with a bounce. |
| s0.5 | drum | blue | drumroll | A drum stands on the box and gets a rapid drumroll, then a cymbal CRASH and the number leaps out of the drum. |
| s0.6 | pinata | yellow | whack | A star pinata swings over the box; a stick whacks it, whacks it again, and the third time it bursts: sweets fly and the number drops out. |
| s0.7 | champagne | blue | uncork | A bottle rises out of the box, shakes, and POP: the cork flies, a fountain of fizz sprays up, and the number rides up on the bubbles. |
| s0.8 | stamp | red | kachunk | A big rubber stamp hovers, rears up and comes down above the box with a KACHUNK, then lifts away: the number left stamped inside a jagged seal. |
### Level 1: streak 21 (8 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| s1.1 | highstriker | red | dingaling | A fairground high striker by the box: a mallet winds up and slams the pad, the puck shoots up the tower, rings the bell, and the number pops out as the lights chase. |
| s1.2 | slamdunk | blue | swoosh | A basketball bounces up out of the box, arcs high and drops through the hoop with a swish; the backboard lights up with the number while the ball bounces away. |
| s1.3 | strike | yellow | pinfall | A bowling ball rolls out of the box down a lane into ten pins: STRIKE, the pins fly every which way and the number bursts up where they stood. |
| s1.4 | gumball | red | crankle | A gumball machine sits on the box; its crank clicks round, a big capsule rolls out of the chute, wobbles, and pops open with the number springing out. |
| s1.5 | sealion | blue | arf | A circus sea lion rises up on its striped stand, flips its ball sky-high, catches the number on its nose instead and balances it, clapping its flippers. |
| s1.6 | slinky | blue | slinkety | A slinky walks itself down a staircase of toy blocks, end over end, lands by the box, and boings up tall to fling the number high. |
| s1.7 | present | red | unwrap | A wrapped present sits on the box and hops, once, twice; then its lid blasts off and curly streamers shoot out with the number rising in the middle. |
| s1.8 | blowout | yellow | razz | A party blower toots: its striped paper curl unrolls straight out, rolls half back, then shoots out fully with the number printed along it and its tassel flicking. |
### Level 2: streak 42 (8 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| s2.1 | shootinggallery | yellow | plinkety | A fairground shooting gallery opens over the box: tin ducks glide along, ping, ping, PING, three go down, and the prize board flips up with the number as the bulbs chase. |
| s2.2 | pinball | red | bumpers | A pinball table stands over the box: the ball is plunged, cracks off the bumpers, the flipper sends it back up, and MULTIBALL: three balls ricochet as the number lights up in the middle. |
| s2.3 | candyfloss | red | spindle | A candyfloss tub whirls on the box; the stick twirls and a great pink cloud spins up on it, then it's held up high, huge and fluffy, with the number in the floss and sugar sparkling. |
| s2.4 | penalty | blue | crowdroar | A penalty kick: the ball sits on the spot by the box, the keeper dives the wrong way, the shot rockets into the top corner, the net bulges, and the number bursts out with confetti. |
| s2.5 | bumpercars | blue | dodgem | Two dodgem cars zoom in from either side, poles sparking on the ceiling grid, crash head-on over the box, bounce apart, and the number jumps up out of the bump in a shower of sparks. |
| s2.6 | lionhoop | yellow | rawr | A circus lion crouches on its drum, bounds through a flaming hoop to the other drum and roars, and the number blazes in the middle of the ring of fire. |
| s2.7 | tiercake | red | fizzle | A party cake builds itself on the box tier by tier, bump, bump, bump, gets its icing and sparkler candles, which light up fizzing, the number piped big across the bottom tier. |
| s2.8 | pancakes | blue | sizzle | A pan by the box flips pancakes, one, two, three, onto a stack; the last flip sends the number spinning sky-high to land on top, and syrup runs down the stack. |
### Level 3: streak 66 (8 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| s3.1 | ferriswheel | blue | skyride | A big wheel rises over the box and turns, its cars swinging and the lights chasing round; fireworks go up behind it and the number lights up in its hub. |
| s3.2 | rollercoaster | red | clackety | A roller coaster: the cars clank up the lift hill, plunge, whip round the loop with arms in the air, and the number bursts out in the middle of the loop with fireworks. |
| s3.3 | trapeze | yellow | hupla | High above the box, a flyer swings out on the trapeze, lets go, somersaults three times through the air and is caught by the catcher; a spotlight snaps on and the number blazes up in it. |
| s3.4 | finishline | red | photofinish | A sprinter tears along to the finish line by the box and bursts through the tape, arms up; the chequered flag waves, the cameras flash and the number goes up in lights. |
| s3.5 | carousel | red | calliope | A carousel turns over the box, painted horses rising and falling on their poles under a striped, scalloped canopy; the bulbs chase round and the number rises up to crown its top. |
| s3.6 | fieldgoal | yellow | airhorn | A football on its tee by the box is booted end over end, high and long, straight through the uprights; the stadium erupts in fireworks and the number blazes between the posts. |
| s3.7 | juggler | yellow | tossup | A clown on a unicycle by the box juggles clubs and balls faster and faster, flings the lot sky-high, and catches the number overhead while the balls whirl round it like stars. |
| s3.8 | dunktank | blue | kersplash | A clown sits on the plank over a dunk tank by the box; a ball smacks the target, SPLOOSH, he drops in, a towering splash throws up the number, and he bobs up grinning. |
### Level 4: streak 100 (8 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| s4.1 | curtaincall | red | ovation | Red stage curtains sweep open, a spotlight snaps on, and the number rises centre stage, takes a bow and is showered with roses. |
| s4.2 | marquee | yellow | showtime | A cinema marquee rises out of the box, its bulbs chasing round the frame, and the number drops onto the board in lights. |
| s4.3 | filmleader | blue | projector | A projector clatters by the box and throws a countdown onto a big screen: the hand sweeps round, round, round, then the number fills the screen. |
| s4.4 | grandpiano | blue | arpeggio | A grand piano rises by the box, its lid swings open, the keys ripple and a fountain of notes sprays out, carrying the number high. |
| s4.5 | gong | yellow | bwong | A great gong hangs in its frame over the box; a mallet winds back, strikes, and the gong shudders out rings as the number glows on its face. |
| s4.6 | hotairballoon | red | burner | A striped hot-air balloon swells up out of the box and climbs past the clouds, burner roaring, the number emblazoned on its band. |
| s4.7 | lunarlander | blue | quindar | A lunar lander rides its rocket flame down onto a moonscape by the box, touches down in a puff of dust, and the number springs up under the Earth. |
| s4.8 | meteorshower | yellow | starfall | Meteors begin to streak down the night sky above the box, then pour, and one great fireball blazes in and bursts into the number. |
### Level 5: streak 150 (8 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| s5.1 | supernova | yellow | nova | A star above the box swells and throbs, collapses to a point, then explodes: a blinding flash, shockwaves racing out, and the number blazing in the glowing remnant. |
| s5.2 | eclipse | yellow | totality | The moon slides across the sun above the box; at totality the corona flares out, a diamond ring flashes, and the number shines from the black disc. |
| s5.3 | galaxy | blue | cosmos | A spiral galaxy winds itself out of the dark above the box, arms of stars sweeping round a blazing core that holds the number. |
| s5.4 | hyperspace | red | warpjump | A starship above the box jumps to light speed: the stars stretch into streaks, it vanishes in a flash, and the number hurtles out of the vanishing point. |
| s5.5 | pipeorgan | yellow | toccata | A cathedral organ rises behind the box, rank on rank of golden pipes, and thunders three great chords that shake the number out above it. |
| s5.6 | headliner | red | powerchord | A rock stage by the box: speaker stacks thump, the lights strobe, pyro columns roar up off the stacks and the number takes the stage. |
| s5.7 | diva | red | aria | An opera diva rises by the box and sings one soaring note: her song ripples out, a row of glasses shatters, and the number swells out of the aria. |
| s5.8 | premiere | yellow | klieg | It's opening night by the box: searchlights sweep the sky, cameras flash along the red carpet, and the beams swing in to cross over the number. |
### Level 6: streak 254 (8 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| s6.1 | dragon | red | scorch | A dragon rears up behind the box, beats a wing, draws a breath and roars a great cone of fire; the number glows in the flames and is left smouldering. |
| s6.2 | excavator | yellow | hydraulic | A big excavator by the box swings its arm down, bites deep into the ground and heaves up a scoop of earth; the number rises out of the hole it dug while the digger shakes its loaded bucket in triumph. |
| s6.3 | geyser | blue | gush | The ground by the box rumbles and spits, then a geyser blasts up in a towering column and holds the number high on its crown of spray. |
| s6.4 | pyramid | yellow | quarry | A pyramid builds itself above the box, one course of stone blocks thudding down at a time; a capstone lands on top and the number is carved into its face in a blaze of light. |
| s6.5 | eagle | blue | screech | An eagle stoops out of the sky onto the box, snatches the number up in its talons and climbs away on huge wingbeats, then soars, the number hanging below it. |
| s6.6 | drawbridge | red | clank | A castle springs up over the box; its drawbridge clanks down on its chains and slams flat, banners unroll down the towers and the number stands in the lit gateway. |
| s6.7 | crane | yellow | winch | A tower crane over the box runs its hook down, hoists a great sign with the number up out of the box and swings it into place, cables singing. |
| s6.8 | longship | red | oarstroke | A longship rows up a great swell, its striped sail bursting full with the number on it, crests, and crashes down in a burst of spray before riding on. |
### Level 7: streak 365, 465, 565, ... (every 100 more) (8 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| s7.1 | phoenix | red | ignite | Embers in the box catch, flames roar up, and a phoenix bursts out of them, wings blazing open, and soars above the number burning in the fire below. |
| s7.2 | clocktower | blue | toll | A great clock tower rises over the box; its hands whirl round and round, a whole year spinning by, stop at twelve, and the bell tolls the number onto the clock face as pigeons scatter. |
| s7.3 | archway | red | keystone | A triumphal arch builds itself over the box: stones fly in from both sides one pair at a time, the keystone drops in with a thunderous clunk, and the number stands beneath it in glory. |
| s7.4 | glacier | blue | calving | A towering ice cliff stands over the sea by the box; cracks race down its face, a huge slab breaks off and crashes into the water, and the number bobs up on a gleaming iceberg. |
| s7.5 | pegasus | yellow | gallop | A winged horse gallops up to the box, leaps, and soars in a great arc over it, leaving a trail of stars around the number that blazes up inside the arc. |
| s7.6 | waterfall | blue | cascade | A mighty waterfall thunders down a gorge over the box; the falling water splits apart at the lip and the number shines out of the glowing cave behind it. |
| s7.7 | titan | red | quake | The ground splits by the box and boulders fly up out of it, stacking themselves into a stone giant; its eyes kindle, and it heaves the number high over its head in both hands. |
| s7.8 | genie | blue | wisp | A brass lamp by the box jiggles, smoke curls out of its spout and swirls up into a genie, who flings out his arms: in a whirl of sparkles, the number appears, granted. |
### Calm streak animations (any level, calm tasks; 4 animations)
| # | name | colour | sound | what happens |
|---|---|---|---|---|
| sc1 | snowglobe | blue | settle | A snow globe sits on the box with the number inside; its flakes swirl slowly round and settle at the bottom. |
| sc2 | slate | red | chalk | A little framed slate rises by the box; a stick of chalk taps the number onto it, then rests on the ledge in a puff of dust. |
| sc3 | sundial | yellow | noon | A sundial by the box with the number on its face; the sun crosses the sky slowly and the gnomon's shadow sweeps round beneath it. |
| sc4 | abacus | red | beads | A small abacus stands by the box; beads slide across one by one, unhurried, and the number settles in above it. |
File diff suppressed because one or more lines are too long
+93
View File
@@ -0,0 +1,93 @@
Copyright 2014 The Caveat Project Authors (https://github.com/googlefonts/caveat)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
BIN
View File
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
<!-- the same drawing as android/src/main/res/drawable/ic_launcher.xml: keep the two in step -->
<path fill="#FFFFFF" d="M32,8h64a24,24 0 0 1 24,24v64a24,24 0 0 1 -24,24h-64a24,24 0 0 1 -24,-24v-64a24,24 0 0 1 24,-24z"/>
<path fill="none" stroke="#000000" stroke-width="5" d="M38,56h26a8,8 0 0 1 8,8v26a8,8 0 0 1 -8,8h-26a8,8 0 0 1 -8,-8v-26a8,8 0 0 1 8,-8z"/>
<path fill="none" stroke="#3584E4" stroke-width="7" stroke-linecap="round" stroke-linejoin="round" d="M39,77l9,9l16,-20"/>
<path fill="none" stroke="#E8202A" stroke-width="6" stroke-linecap="round" d="M80,48L94,34M66,40L68,22M88,62L106,60"/>
<circle cx="100" cy="24" r="6" fill="#FFC400"/>
</svg>

After

Width:  |  Height:  |  Size: 758 B

+70
View File
@@ -0,0 +1,70 @@
{
"_help": [
"The template routine: a first run starts from a copy of it (your own copy then lives in the data folder; see Settings → Data).",
"Change it in Settings → Routine (Ctrl+,), or delete it all and start your own: it's only there to show what a routine can hold.",
"Each block: id, label, start/end (24h hour), color, items, optional days (0=Sun .. 6=Sat; omit = every day).",
"Each item: label, optional id, optional items (nested sub-tasks), optional days (as for blocks),",
"optional hint: true (a suggestion shown as text, with no checkbox: never ticked, skipped or counted).",
"optional calm: true (ticking it plays one of the calm animations instead; it still counts).",
"An item without an id gets one from its label (and its parents'): give it an explicit id to rename it and keep its history.",
"rev goes up each time the routine is saved; dayStartsAt is the hour a new day begins (before it, it's still last night)."
],
"rev": 0,
"dayStartsAt": 4,
"blocks": [
{
"id": "morning",
"label": "Morning",
"start": 7,
"end": 9,
"color": "#FFE08A",
"items": [
{"id": "tick-me", "label": "Tick me off: every tick plays a little animation"},
{"id": "with-sub-tasks", "label": "A task with sub-tasks (ticking it ticks the ones still open)", "items": [
{"id": "first-step", "label": "A sub-task"},
{"id": "second-step", "label": "Another sub-task, with one of its own", "items": [
{"id": "deeper", "label": "A sub-sub-task: nest as deep as you like"}
]}
]},
{"id": "stretch", "label": "Stretch for a few minutes", "items": [
{"id": "idea", "label": "Just a suggestion: quiet text with no checkbox, like an idea for the task above", "hint": true}
]}
]
},
{
"id": "day",
"label": "Daytime",
"start": 9,
"end": 17,
"color": "#B8DAFF",
"items": [
{"id": "weekdays", "label": "Only on weekdays: a task can be left off some days", "days": [1, 2, 3, 4, 5]},
{"id": "skip-me", "label": "Skip me: skip hides a task without ticking it off"},
{"id": "hide-me", "label": "Click a block's heading to hide its tasks"}
]
},
{
"id": "weekend",
"label": "Weekend",
"start": 10,
"end": 12,
"color": "#B5EBC8",
"days": [0, 6],
"items": [
{"id": "whole-block", "label": "This whole block is only there on Saturday and Sunday"}
]
},
{
"id": "evening",
"label": "Evening",
"start": 20,
"end": 23,
"color": "#D9C2FF",
"items": [
{"id": "calm", "label": "A calm task: its animation is slower and quieter, for late nights", "calm": true},
{"id": "make-it-yours", "label": "Make it yours: Settings → Routine (Ctrl+,) changes or deletes all of this"},
{"id": "note", "label": "Write a line in the day's note at the bottom"}
]
}
]
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More