Add Pause: break reminder with eye exercises and scratchpad #1

Merged
reudy merged 1 commit from initial-app into main 2026-09-28 16:24:35 +02:00
18 changed files with 1383 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
__pycache__/
*.pyc

81
README.md Normal file
View file

@ -0,0 +1,81 @@
# Pause
Every 25 minutes Pause fills the screen and walks you through a short break:
a few guided eye exercises, then a couple of minutes to get up and move.
You can snooze the break for 2 minutes or skip it. There's also a scratchpad
where you can write down what you were in the middle of. It gets focus as
soon as the break starts, so you can just type, and it's shown back to you
when the break ends.
Built for GNOME on Fedora (tested with GNOME Shell 50 on Wayland) with
Python, GTK 4 and libadwaita, all of which Fedora Workstation already ships.
## Install
```sh
git clone ssh://git@git.reudy.net:14922/reudy-net/pause.git ~/src/pause
~/src/pause/install.sh
pause &
```
`install.sh` doesn't need root. It adds:
- `~/.local/bin/pause`, a launcher that runs from the checkout, so `git pull` updates it
- an app-grid entry (open it to see the time left; right-click for *Take a Break Now* / *Turn Off for an Hour*)
- an autostart entry, so Pause starts when you log in
If it complains about missing modules: `sudo dnf install python3-gobject gtk4 libadwaita`.
Remove it with `./install.sh --uninstall` (your notes are kept).
## The break
1. A notification a minute before (**Snooze** / **Take it now**).
2. A fullscreen screen on every monitor with a countdown. The cursor is already in the scratchpad.
3. Eye exercises (look into the distance, blinking, near/far focus, eye circles,
figure eight, palming), with a chime between steps.
4. The rest of the break is for walking around. A chime tells you it's over.
5. **Welcome back** shows your note again. **Back to work** (or Ctrl+Enter)
saves it to `~/.local/share/pause/notes.md` and leaves it in the notification list.
**Snooze** keeps your note as a draft for next time. **Skip** saves the note
and restarts the 25 minutes. Alt+F4 and Escape don't close the break screen.
If you Alt+Tab away, the break screen comes back after a few seconds.
Pause also notices when you're not there. If the laptop sleeps, or you don't
touch it for 5 minutes, that counts as a break and the timer starts over. A
break that comes due while you're away waits until you're back.
## Commands
```
pause start (or show status if already running)
pause now break right now
pause snooze [MIN] postpone the next break
pause skip skip the next break
pause off [MIN] no breaks, for MIN minutes or until `pause on`
pause on
pause status
pause notes [N] your last N scratchpad notes
pause stats breaks taken / snoozed / skipped this week
pause config create ~/.config/pause/config.toml and print its path
pause quit
```
Tip: bind `pause now` or `pause off 60` to a key in *Settings → Keyboard →
Custom Shortcuts*.
## Configuration
`pause config` creates `~/.config/pause/config.toml` with every setting documented:
work/break/snooze length, warning time, idle reset, whether the break screen
pulls itself back to the front, and sounds. Restart Pause after editing it.
## Development
```sh
python3 -m unittest # scheduler, notes and exercise-plan tests
python3 -m pause # run from the checkout
```
The timing logic lives in `pause/scheduler.py` and has no GTK dependency, so
it can be tested with a fake clock. The break screen is in `pause/overlay.py`.

View file

@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=Pause
Comment=Regular breaks for your eyes and legs
Exec=@BIN@/pause
Icon=net.reudy.Pause
Terminal=false
NoDisplay=true
X-GNOME-Autostart-enabled=true

View file

@ -0,0 +1,24 @@
[Desktop Entry]
Type=Application
Name=Pause
Comment=Regular breaks for your eyes and legs
Exec=@BIN@/pause show
Icon=net.reudy.Pause
Terminal=false
Categories=Utility;
Keywords=break;timer;eyes;pomodoro;rest;
StartupNotify=false
X-GNOME-UsesNotifications=true
Actions=break-now;off-hour;on;
[Desktop Action break-now]
Name=Take a Break Now
Exec=@BIN@/pause now
[Desktop Action off-hour]
Name=Turn Off for an Hour
Exec=@BIN@/pause off 60
[Desktop Action on]
Name=Turn Breaks Back On
Exec=@BIN@/pause on

13
data/net.reudy.Pause.svg Normal file
View file

@ -0,0 +1,13 @@
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#3fb68b"/>
<stop offset="1" stop-color="#1f7a5c"/>
</linearGradient>
</defs>
<rect x="8" y="8" width="112" height="112" rx="28" fill="url(#bg)"/>
<path d="M24 64 C40 38 88 38 104 64 C88 90 40 90 24 64 Z" fill="#fff"/>
<circle cx="64" cy="64" r="20" fill="#1f7a5c"/>
<rect x="56" y="54" width="6" height="20" rx="2" fill="#fff"/>
<rect x="66" y="54" width="6" height="20" rx="2" fill="#fff"/>
</svg>

After

Width:  |  Height:  |  Size: 610 B

48
install.sh Executable file
View file

@ -0,0 +1,48 @@
#!/bin/sh
# Install Pause for the current user, running straight from this checkout
# (so `git pull` updates it). Use --uninstall to remove it again.
set -eu
REPO=$(cd "$(dirname "$0")" && pwd)
BIN=${XDG_BIN_HOME:-$HOME/.local/bin}
DATA=${XDG_DATA_HOME:-$HOME/.local/share}
CONFIG=${XDG_CONFIG_HOME:-$HOME/.config}
APP_ID=net.reudy.Pause
DESKTOP=$DATA/applications/$APP_ID.desktop
AUTOSTART=$CONFIG/autostart/$APP_ID.desktop
ICON=$DATA/icons/hicolor/scalable/apps/$APP_ID.svg
if [ "${1:-}" = "--uninstall" ]; then
"$BIN/pause" quit 2>/dev/null || true
rm -f "$BIN/pause" "$DESKTOP" "$AUTOSTART" "$ICON"
echo "Pause removed. Your notes are still in $DATA/pause/."
exit 0
fi
if ! python3 -c 'import gi; gi.require_version("Gtk", "4.0"); gi.require_version("Adw", "1")' 2>/dev/null; then
echo "GTK 4 / libadwaita for Python are missing. On Fedora:" >&2
echo " sudo dnf install python3-gobject gtk4 libadwaita" >&2
exit 1
fi
mkdir -p "$BIN" "$(dirname "$DESKTOP")" "$(dirname "$AUTOSTART")" "$(dirname "$ICON")"
cat > "$BIN/pause" <<EOF
#!/bin/sh
PYTHONPATH="$REPO\${PYTHONPATH:+:\$PYTHONPATH}" exec python3 -m pause "\$@"
EOF
chmod +x "$BIN/pause"
sed "s|@BIN@|$BIN|g" "$REPO/data/$APP_ID.desktop" > "$DESKTOP"
sed "s|@BIN@|$BIN|g" "$REPO/data/$APP_ID.autostart.desktop" > "$AUTOSTART"
cp "$REPO/data/$APP_ID.svg" "$ICON"
update-desktop-database "$DATA/applications" 2>/dev/null || true
gtk-update-icon-cache -q "$DATA/icons/hicolor" 2>/dev/null || true
echo "Installed. Pause starts automatically when you log in."
echo "Start it now with: pause &"
case ":$PATH:" in
*":$BIN:"*) ;;
*) echo "Note: $BIN is not in your PATH; use $BIN/pause" ;;
esac

3
pause/__init__.py Normal file
View file

@ -0,0 +1,3 @@
"""Pause: regular screen breaks for your eyes and legs."""
APP_ID = "net.reudy.Pause"

79
pause/__main__.py Normal file
View file

@ -0,0 +1,79 @@
import sys
from . import APP_ID
USAGE = """\
usage: pause [command]
(no command) start Pause in the background (or show its status)
now take a break right now
snooze [MIN] postpone the next break (default: snooze_minutes)
skip skip the next break and restart the work timer
off [MIN] stop breaks, for MIN minutes or until `pause on`
on turn breaks back on
status show when the next break is
quit stop Pause
notes [N] print the last N scratchpad notes (default 5)
stats breaks taken / snoozed / skipped over the last week
config create the config file if needed and print its path
"""
def main(argv=None):
argv = sys.argv if argv is None else argv
cmd = argv[1] if len(argv) > 1 else None
# Commands that only read files don't need the running app (or GTK).
if cmd in ("help", "-h", "--help"):
print(USAGE, end="")
return 0
if cmd == "notes":
from . import notes
n = int(argv[2]) if len(argv) > 2 else 5
entries = notes.recent(n)
if not entries:
print("No notes yet.")
for heading, text in entries:
print(f"── {heading}\n{text}\n")
print(f"All notes: {notes.notes_path()}")
return 0
if cmd == "stats":
from . import notes
print("day taken snoozed skipped")
for day, c in notes.stats():
print(f"{day:%a %d %b} {c['taken']:5} {c['snoozed']:7} {c['skipped']:7}")
return 0
if cmd == "config":
from . import config
print(config.write_default())
return 0
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
# Don't start a new instance just to ask it for its status.
if cmd not in (None, "now", "show") and not _is_running():
print("Pause is not running. Start it with `pause`.", file=sys.stderr)
return 1
from .app import PauseApp
return PauseApp().run(argv)
def _is_running():
from gi.repository import Gio, GLib
try:
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
reply = bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus",
"org.freedesktop.DBus", "NameHasOwner",
GLib.Variant("(s)", (APP_ID,)), GLib.VariantType("(b)"),
Gio.DBusCallFlags.NONE, 1000, None)
return reply.unpack()[0]
except GLib.Error:
return False
if __name__ == "__main__":
sys.exit(main())

244
pause/app.py Normal file
View file

@ -0,0 +1,244 @@
import datetime
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Adw, Gdk, Gio, GLib, Gtk # noqa: E402
from . import APP_ID, config, notes, sound
from .overlay import CSS, BreakOverlay, fmt
from .scheduler import BREAK, RESET, RESUMED, WARN, Scheduler, State, clock
class PauseApp(Adw.Application):
def __init__(self):
super().__init__(application_id=APP_ID,
flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
self.cfg = config.load()
self.scheduler = None
self.overlay = None
self.idle_seconds = 0.0
self._idle_monitor = None
self._idle_pending = False
for name, param, handler in [
("break-now", None, lambda a, p: self.take_break()),
("snooze", None, lambda a, p: self.snooze()),
("skip", None, lambda a, p: self.skip()),
("off", GLib.VariantType("u"), lambda a, p: self.turn_off(p.get_uint32())),
("on", None, lambda a, p: self.turn_on()),
]:
action = Gio.SimpleAction(name=name, parameter_type=param)
action.connect("activate", handler)
self.add_action(action)
def do_startup(self):
Adw.Application.do_startup(self)
Adw.StyleManager.get_default().set_color_scheme(Adw.ColorScheme.FORCE_DARK)
provider = Gtk.CssProvider()
provider.load_from_string(CSS)
Gtk.StyleContext.add_provider_for_display(
Gdk.Display.get_default(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
# Run in the background with no windows open.
self.hold()
self.scheduler = Scheduler(self.cfg, clock())
self._connect_idle_monitor()
GLib.timeout_add_seconds(1, self._tick)
def do_activate(self):
# Clicking a notification activates the app; nothing to show.
pass
def do_command_line(self, cmdline):
args = cmdline.get_arguments()[1:]
cmd, rest = (args[0], args[1:]) if args else (None, [])
try:
out = self.run_command(cmd, rest, remote=cmdline.get_is_remote())
except ValueError as e:
cmdline.printerr_literal(f"pause: {e}\n")
return 2
if out:
cmdline.print_literal(out + "\n")
return 0
def run_command(self, cmd, args, remote):
now = clock()
minutes = None
if args:
try:
minutes = float(args[0])
except ValueError:
raise ValueError(f"expected a number of minutes, got {args[0]!r}")
if cmd is None:
return self.status() if remote else None
if cmd == "show":
self._notify_status()
return None
if cmd == "status":
return self.status()
if cmd == "now":
self.take_break()
return "Break started."
if cmd == "snooze":
self.snooze(minutes)
return self.status()
if cmd == "skip":
self.skip()
return self.status()
if cmd == "off":
self.turn_off(minutes)
return self.status()
if cmd == "on":
self.turn_on()
return self.status()
if cmd == "quit":
if self.overlay:
self.overlay.close()
self.quit()
return "Pause stopped."
raise ValueError(f"unknown command {cmd!r}, see `pause help`")
def status(self):
s = self.scheduler
now = clock()
if s.state is State.BREAK:
return "On a break."
if s.state is State.OFF:
if s.off_until is None:
return "Breaks are off. Run `pause on` to turn them back on."
until = datetime.datetime.now() + datetime.timedelta(seconds=s.off_until - now)
return f"Breaks are off until {until:%H:%M}."
text = f"Next break in {fmt(s.remaining(now))}."
if s.away:
text += " You seem to be away; the timer restarts when you're back."
if s.snoozes:
text += f" (snoozed {s.snoozes}×)"
return text
# Timer
def _tick(self):
self._poll_idle()
event = self.scheduler.tick(clock(), self.idle_seconds)
if event == WARN:
self._notify_warning()
elif event == BREAK:
self._show_break()
elif event in (RESET, RESUMED):
self.withdraw_notification("warning")
return True
def _connect_idle_monitor(self):
"""Mutter tells us how long since the last keyboard/mouse input."""
try:
self._idle_monitor = Gio.DBusProxy.new_for_bus_sync(
Gio.BusType.SESSION,
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES | Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS
| Gio.DBusProxyFlags.DO_NOT_AUTO_START,
None, "org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core",
"org.gnome.Mutter.IdleMonitor", None)
except GLib.Error:
self._idle_monitor = None
def _poll_idle(self):
if self._idle_monitor is None or self._idle_pending:
return
self._idle_pending = True
self._idle_monitor.call("GetIdletime", None, Gio.DBusCallFlags.NONE, 1000, None,
self._on_idle_time)
def _on_idle_time(self, proxy, result):
self._idle_pending = False
try:
self.idle_seconds = proxy.call_finish(result).unpack()[0] / 1000
except GLib.Error:
self.idle_seconds = 0.0
# Actions
def take_break(self):
self.scheduler.break_now(clock())
self._show_break()
def snooze(self, minutes=None):
if self.overlay:
self.overlay.end("snoozed", snooze_minutes=minutes)
return
self.withdraw_notification("warning")
self.scheduler.snooze(clock(), minutes)
notes.log_event("snoozed")
def skip(self):
if self.overlay:
self.overlay.end("taken" if self.overlay.finished else "skipped")
return
self.withdraw_notification("warning")
self.scheduler.finish(clock())
notes.log_event("skipped")
def turn_off(self, minutes=None):
if self.overlay:
note = self.overlay.note
self.overlay.close()
self.overlay = None
notes.save_draft(note)
self.withdraw_notification("warning")
self.scheduler.turn_off(clock(), minutes)
def turn_on(self):
if self.scheduler.state is State.OFF:
self.scheduler.resume(clock())
def _show_break(self):
self.withdraw_notification("warning")
if self.overlay is None:
self.overlay = BreakOverlay(self, self.cfg.break_minutes * 60, notes.load_draft())
def break_ended(self, outcome, note, snooze_minutes=None):
"""Called by the overlay when one of its buttons is used."""
self.overlay = None
now = clock()
notes.log_event(outcome)
if outcome == "snoozed":
notes.save_draft(note)
self.scheduler.snooze(now, snooze_minutes)
return
notes.record(note)
self.scheduler.finish(now)
if note.strip():
self._notify_note(note.strip())
def save_draft(self, text):
notes.save_draft(text)
def play_sound(self, event_id):
sound.play(event_id)
# Notifications
def _notify_warning(self):
n = Gio.Notification.new(f"Break in {fmt(self.cfg.warn_seconds)}")
n.set_body("Start wrapping up. You'll get a scratchpad to note where you left off.")
n.set_priority(Gio.NotificationPriority.HIGH)
n.add_button(f"Snooze {self.cfg.snooze_minutes:g} min", "app.snooze")
n.add_button("Take it now", "app.break-now")
self.send_notification("warning", n)
def _notify_note(self, note):
n = Gio.Notification.new("Where you left off")
n.set_body(note)
# Low priority: no banner, it just waits in the notification list.
n.set_priority(Gio.NotificationPriority.LOW)
self.send_notification("note", n)
def _notify_status(self):
n = Gio.Notification.new("Pause is running")
n.set_body(self.status())
if self.scheduler.state is State.OFF:
n.add_button("Turn breaks on", "app.on")
else:
n.add_button("Take a break now", "app.break-now")
n.add_button_with_target("Off for an hour", "app.off", GLib.Variant("u", 60))
self.send_notification("status", n)

84
pause/config.py Normal file
View file

@ -0,0 +1,84 @@
import dataclasses
import os
import sys
import tomllib
from pathlib import Path
DEFAULT_TOML = """\
# Pause configuration. Restart Pause after editing: pause quit; pause &
# Minutes of work between breaks.
work_minutes = 25
# Length of a break in minutes (eye exercises first, then walking around).
break_minutes = 5
# How long the "Snooze" button postpones a break.
snooze_minutes = 2
# Notification this many seconds before a break starts (0 = no warning).
warn_seconds = 60
# If you are idle (or the laptop sleeps) for this many minutes, that counts
# as a break and the work timer starts over. 0 = disabled.
idle_reset_minutes = 5
# Pull the break screen back to the front if you switch away from it.
keep_on_top = true
# Chime when an exercise changes and when the break is over.
sounds = true
"""
@dataclasses.dataclass
class Config:
work_minutes: float = 25
break_minutes: float = 5
snooze_minutes: float = 2
warn_seconds: int = 60
idle_reset_minutes: float = 5
keep_on_top: bool = True
sounds: bool = True
def config_path():
base = os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"
return Path(base) / "pause" / "config.toml"
def load(path=None):
path = path or config_path()
cfg = Config()
try:
with open(path, "rb") as f:
data = tomllib.load(f)
except FileNotFoundError:
return cfg
except (OSError, tomllib.TOMLDecodeError) as e:
print(f"pause: ignoring {path}: {e}", file=sys.stderr)
return cfg
types = {f.name: f.type for f in dataclasses.fields(Config)}
for key, value in data.items():
if key not in types:
print(f"pause: unknown setting {key!r} in {path}", file=sys.stderr)
continue
want = types[key]
if want is bool:
ok = isinstance(value, bool)
else:
ok = isinstance(value, (int, float)) and not isinstance(value, bool) and value >= 0
if not ok:
print(f"pause: bad value for {key!r} in {path}: {value!r}", file=sys.stderr)
continue
setattr(cfg, key, want(value))
return cfg
def write_default(path=None):
path = path or config_path()
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(DEFAULT_TOML)
return path

68
pause/exercises.py Normal file
View file

@ -0,0 +1,68 @@
from dataclasses import dataclass
@dataclass(frozen=True)
class Step:
emoji: str
title: str
text: str
seconds: float
EYE_STEPS = [
Step("🔭", "Look into the distance",
"Find something at least 6 metres (20 ft) away, out of a window if you can, "
"and let your eyes rest on it. Don't stare, just look.", 20),
Step("😌", "Blink it out",
"Blink quickly about 15 times, then close your eyes gently and relax them "
"for a few seconds.", 15),
Step("👍", "Near and far",
"Hold your thumb about 25 cm from your face. Focus on it for a few seconds, "
"then on something far away. Keep switching.", 30),
Step("🔄", "Eye circles",
"Keep your head still and slowly roll your eyes in a big circle: "
"5 times clockwise, then 5 times the other way.", 20),
Step("♾️", "Figure eight",
"Imagine a large sideways 8 on the wall a few metres away and trace it "
"slowly with your eyes, first one way, then the other.", 20),
Step("🤲", "Palming",
"Rub your hands together until they're warm, then cup them over your closed "
"eyes without pressing. Breathe slowly.", 30),
]
WALK = Step("🚶", "Get up and move",
"Stand up and walk around. Roll your shoulders, stretch your neck and back, "
"get a glass of water. Come back when you hear the chime.", 0)
# Leave at least this much of the break for walking around.
MIN_WALK = 60
def plan(total_seconds):
"""Pick the steps for a break of the given length.
Eye exercises come first while you're still at the screen to read them,
then the rest of the break is for walking around.
"""
steps = []
used = 0
for step in EYE_STEPS:
budget = total_seconds - MIN_WALK if steps else total_seconds
if used + step.seconds > budget:
break
steps.append(step)
used += step.seconds
rest = total_seconds - used
if rest > 0:
steps.append(Step(WALK.emoji, WALK.title, WALK.text, rest))
return steps
def position(steps, elapsed):
"""Return (index, seconds left in that step) for the given elapsed time."""
start = 0
for i, step in enumerate(steps):
if elapsed < start + step.seconds:
return i, start + step.seconds - elapsed
start += step.seconds
return len(steps) - 1, 0.0

104
pause/notes.py Normal file
View file

@ -0,0 +1,104 @@
"""The scratchpad: notes you leave yourself when a break interrupts you."""
import collections
import datetime
import json
import os
from pathlib import Path
def data_dir():
base = os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share"
return Path(base) / "pause"
def notes_path():
return data_dir() / "notes.md"
def _draft_path():
return data_dir() / "draft.txt"
def _log_path():
return data_dir() / "log.jsonl"
def _now():
return datetime.datetime.now().astimezone()
def load_draft():
try:
return _draft_path().read_text()
except OSError:
return ""
def save_draft(text):
path = _draft_path()
if text.strip():
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
tmp.write_text(text)
tmp.replace(path)
else:
path.unlink(missing_ok=True)
def record(text, when=None):
"""Append a note to notes.md and clear the draft."""
text = text.strip()
save_draft("")
if not text:
return
when = when or _now()
path = notes_path()
path.parent.mkdir(parents=True, exist_ok=True)
# Headings separate the notes, so escape any in the note itself.
body = "\n".join("\\" + line if line.startswith("## ") else line
for line in text.split("\n"))
with open(path, "a") as f:
f.write(f"## {when:%Y-%m-%d %H:%M}\n\n{body}\n\n")
def recent(n=5):
"""Return the last n notes as (heading, text) pairs, oldest first."""
try:
content = notes_path().read_text()
except OSError:
return []
entries = []
for chunk in ("\n" + content).split("\n## ")[1:]:
heading, _, body = chunk.partition("\n")
body = "\n".join(line[1:] if line.startswith("\\## ") else line
for line in body.strip().split("\n"))
entries.append((heading.strip(), body))
return entries[-n:] if n else entries
def log_event(kind, when=None):
when = when or _now()
path = _log_path()
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "a") as f:
f.write(json.dumps({"t": when.isoformat(timespec="seconds"), "event": kind}) + "\n")
def stats(days=7, today=None):
"""Count break outcomes per day for the last `days` days, newest first."""
today = today or _now().date()
counts = collections.defaultdict(collections.Counter)
try:
with open(_log_path()) as f:
for line in f:
try:
entry = json.loads(line)
day = datetime.datetime.fromisoformat(entry["t"]).date()
counts[day][entry["event"]] += 1
except (ValueError, KeyError, TypeError):
continue
except OSError:
pass
days_back = (today - datetime.timedelta(days=i) for i in range(days))
return [(day, counts[day]) for day in days_back]

280
pause/overlay.py Normal file
View file

@ -0,0 +1,280 @@
"""The fullscreen break screen."""
from gi.repository import Adw, Gdk, GLib, Gtk
from . import exercises
from .scheduler import clock
CSS = """
window.pause-overlay {
background-color: rgba(14, 16, 22, 0.94);
color: #f2f2f5;
}
.pause-countdown {
font-size: 64pt;
font-weight: 800;
font-feature-settings: "tnum";
}
.pause-emoji { font-size: 38pt; }
.pause-card {
background-color: alpha(white, 0.06);
border-radius: 18px;
padding: 20px;
}
.pause-notes, .pause-notes text {
background: transparent;
font-size: 13pt;
}
.pause-note-frame {
background-color: alpha(black, 0.25);
border-radius: 10px;
padding: 6px;
}
"""
# Seconds the break screen may sit in the background before it's pulled forward.
REFOCUS_AFTER = 3
def fmt(seconds):
m, s = divmod(max(0, int(seconds + 0.999)), 60)
return f"{m}:{s:02d}"
class BreakOverlay:
"""One fullscreen window per monitor; the first one holds the content."""
def __init__(self, app, seconds, draft=""):
self.app = app
self.total = seconds
self.steps = exercises.plan(seconds)
self.start = clock()
self.step_index = -1
self.finished = False
self.closed = False
self._inactive = 0
self._draft_timer = 0
self.windows = []
display = Gdk.Display.get_default()
monitors = display.get_monitors()
for i in range(max(1, monitors.get_n_items())):
monitor = monitors.get_item(i)
win = Adw.ApplicationWindow(application=app, title="Pause",
default_width=1200, default_height=900)
win.add_css_class("pause-overlay")
win.set_content(self._build_main(draft) if i == 0 else self._build_secondary())
# Only the buttons end a break; Alt+F4 and friends do nothing.
win.connect("close-request", lambda w: True)
self.windows.append((win, monitor))
shortcuts = Gtk.ShortcutController(scope=Gtk.ShortcutScope.MANAGED)
shortcuts.add_shortcut(Gtk.Shortcut(
trigger=Gtk.ShortcutTrigger.parse_string("<Control>Return"),
action=Gtk.CallbackAction.new(self._on_ctrl_enter)))
self.windows[0][0].add_controller(shortcuts)
self._update()
for win, monitor in self.windows:
self._show(win, monitor)
self.textview.grab_focus()
self._tick_id = GLib.timeout_add(250, self._tick)
# UI construction
def _build_main(self, draft):
self.title = Gtk.Label(label="Time for a pause", css_classes=["title-1"])
self.countdown = Gtk.Label(css_classes=["pause-countdown"])
self.total_bar = Gtk.ProgressBar()
self.step_emoji = Gtk.Label(css_classes=["pause-emoji"], valign=Gtk.Align.START)
self.step_counter = Gtk.Label(xalign=0, css_classes=["caption-heading", "dim-label"])
self.step_title = Gtk.Label(xalign=0, wrap=True, css_classes=["title-2"])
self.step_left = Gtk.Label(css_classes=["title-3", "numeric"], valign=Gtk.Align.CENTER)
self.step_text = Gtk.Label(xalign=0, wrap=True, css_classes=["body"])
self.step_bar = Gtk.ProgressBar()
heading = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4, hexpand=True)
heading.append(self.step_counter)
heading.append(self.step_title)
top = Gtk.Box(spacing=16)
top.append(self.step_emoji)
top.append(heading)
top.append(self.step_left)
step_card = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12,
css_classes=["pause-card"])
step_card.append(top)
step_card.append(self.step_text)
step_card.append(self.step_bar)
self.step_card = step_card
self.notes_heading = Gtk.Label(
xalign=0, wrap=True, css_classes=["heading"],
label="Before you go: what were you in the middle of? What's next?")
self.buffer = Gtk.TextBuffer(text=draft)
self.buffer.connect("changed", self._on_note_changed)
self.textview = Gtk.TextView(
buffer=self.buffer, wrap_mode=Gtk.WrapMode.WORD_CHAR, accepts_tab=False,
top_margin=6, bottom_margin=6, left_margin=6, right_margin=6,
css_classes=["pause-notes"])
scroller = Gtk.ScrolledWindow(
child=self.textview, min_content_height=110, max_content_height=240,
propagate_natural_height=True, hscrollbar_policy=Gtk.PolicyType.NEVER,
css_classes=["pause-note-frame"])
notes_card = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10,
css_classes=["pause-card"])
notes_card.append(self.notes_heading)
notes_card.append(scroller)
snooze = self.app.cfg.snooze_minutes
self.snooze_btn = Gtk.Button(
label=f"Snooze {snooze:g} min", css_classes=["pill"])
self.skip_btn = Gtk.Button(label="Skip this break", css_classes=["pill"])
self.done_btn = Gtk.Button(
label="Back to work", css_classes=["pill", "suggested-action"], visible=False)
self.snooze_btn.connect("clicked", lambda b: self.end("snoozed"))
self.skip_btn.connect("clicked", lambda b: self.end("skipped"))
self.done_btn.connect("clicked", lambda b: self.end("taken"))
buttons = Gtk.Box(spacing=12, halign=Gtk.Align.CENTER)
for b in (self.snooze_btn, self.skip_btn, self.done_btn):
buttons.append(b)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18,
valign=Gtk.Align.CENTER)
for widget in (self.title, self.countdown, self.total_bar,
step_card, notes_card, buttons):
box.append(widget)
clamp = Adw.Clamp(maximum_size=720, child=box,
margin_top=24, margin_bottom=24, margin_start=24, margin_end=24)
return Gtk.ScrolledWindow(child=clamp, hscrollbar_policy=Gtk.PolicyType.NEVER)
def _build_secondary(self):
label = Gtk.Label(label="Pause: look away from the screen 🌿",
css_classes=["title-2", "dim-label"])
label.set_valign(Gtk.Align.CENTER)
return label
def _show(self, win, monitor):
if monitor is not None:
win.fullscreen_on_monitor(monitor)
else:
win.fullscreen()
win.present()
# Updates
def _tick(self):
if self.closed:
return False
self._update()
self._keep_on_top()
return True
def _update(self):
elapsed = clock() - self.start
left = self.total - elapsed
if left <= 0:
if not self.finished:
self._finish()
return
self.countdown.set_label(fmt(left))
self.total_bar.set_fraction(min(1.0, elapsed / self.total))
index, step_left = exercises.position(self.steps, elapsed)
step = self.steps[index]
if index != self.step_index:
if self.step_index >= 0:
self._chime("bell")
self.step_index = index
self.step_emoji.set_label(step.emoji)
self.step_counter.set_label(f"STEP {index + 1} OF {len(self.steps)}")
self.step_title.set_label(step.title)
self.step_text.set_label(step.text)
self.step_left.set_label(fmt(step_left))
self.step_bar.set_fraction(1 - step_left / step.seconds if step.seconds else 1)
def _finish(self):
self.finished = True
self._chime("complete")
self.title.set_label("Welcome back 👋")
self.countdown.set_label("Done")
self.total_bar.set_fraction(1)
self.step_card.set_visible(False)
if self.note.strip():
self.notes_heading.set_label("You were in the middle of:")
else:
self.notes_heading.set_label("Anything to jot down before you dive back in?")
self.snooze_btn.set_visible(False)
self.skip_btn.set_visible(False)
self.done_btn.set_visible(True)
self.done_btn.grab_focus()
# Bring the screen forward even if it was pushed back, so you see your note.
self._inactive = REFOCUS_AFTER
def _keep_on_top(self):
"""Re-show the break screen if something else took focus.
On Wayland an app can't force itself above other windows, but a newly
mapped window does get focus, so hide and map it again.
"""
if not self.app.cfg.keep_on_top:
return
if any(win.is_active() for win, _ in self.windows):
self._inactive = 0
return
if self.app.idle_seconds > 30 and not self.finished:
return
# _tick runs 4x a second
self._inactive += 0.25
if self._inactive >= REFOCUS_AFTER:
self._inactive = 0
win, monitor = self.windows[0]
win.set_visible(False)
self._show(win, monitor)
def _chime(self, sound):
if self.app.cfg.sounds:
self.app.play_sound(sound)
# Notes
@property
def note(self):
return self.buffer.get_text(self.buffer.get_start_iter(), self.buffer.get_end_iter(), False)
def _on_note_changed(self, buffer):
if self._draft_timer:
GLib.source_remove(self._draft_timer)
self._draft_timer = GLib.timeout_add_seconds(1, self._save_draft)
def _save_draft(self):
self._draft_timer = 0
self.app.save_draft(self.note)
return False
# Ending
def _on_ctrl_enter(self, *args):
if self.finished:
self.end("taken")
return True
def end(self, outcome, snooze_minutes=None):
if self.closed:
return
note = self.note
self.close()
self.app.break_ended(outcome, note, snooze_minutes)
def close(self):
if self.closed:
return
self.closed = True
GLib.source_remove(self._tick_id)
if self._draft_timer:
GLib.source_remove(self._draft_timer)
self._draft_timer = 0
for win, _ in self.windows:
win.destroy()
self.windows = []

129
pause/scheduler.py Normal file
View file

@ -0,0 +1,129 @@
"""Break timing logic, kept free of GTK so it can be unit tested.
All times are seconds from a clock that keeps running during suspend
(CLOCK_BOOTTIME), so a closed lid shows up as a big gap between ticks.
"""
import enum
import time
def clock():
return time.clock_gettime(time.CLOCK_BOOTTIME)
class State(enum.Enum):
WORKING = "working"
BREAK = "break"
OFF = "off"
# Events returned by Scheduler.tick()
WARN = "warn"
BREAK = "break"
RESET = "reset"
RESUMED = "resumed"
# A break that comes due while you haven't touched the machine for this long
# waits for you to come back instead of popping up at an empty chair.
AWAY_GRACE = 60
class Scheduler:
def __init__(self, cfg, now):
self.cfg = cfg
self.state = State.WORKING
self.last_tick = now
self.away = False
self.off_until = None
self.snoozes = 0
self._start_work(now)
@property
def work_seconds(self):
return self.cfg.work_minutes * 60
@property
def reset_seconds(self):
return self.cfg.idle_reset_minutes * 60
def _start_work(self, now):
self.state = State.WORKING
self.due = now + self.work_seconds
self.warned = False
def tick(self, now, idle=0.0):
"""Advance the clock. Returns one of the event constants or None."""
gap = now - self.last_tick
self.last_tick = now
if self.state is State.OFF:
if self.off_until is not None and now >= self.off_until:
self.resume(now)
return RESUMED
return None
if self.state is State.BREAK:
return None
# Suspended, or away long enough that it already counted as a break.
if self.reset_seconds > 0:
if gap >= self.reset_seconds:
self.away = False
self.snoozes = 0
self._start_work(now)
return RESET
if idle >= self.reset_seconds:
self.away = True
return None
if self.away:
if idle < AWAY_GRACE:
self.away = False
self.snoozes = 0
self._start_work(now)
return RESET
return None
warn = self.cfg.warn_seconds
if not self.warned and warn > 0 and self.due - warn <= now < self.due:
self.warned = True
return WARN
if now >= self.due:
if idle >= AWAY_GRACE:
return None
self.state = State.BREAK
return BREAK
return None
def break_now(self, now):
if self.state is not State.BREAK:
self.state = State.BREAK
self.due = now
def snooze(self, now, minutes=None):
minutes = self.cfg.snooze_minutes if minutes is None else minutes
# Snoozing from the warning pushes the upcoming break back;
# snoozing a running break (or while off) counts from now.
base = max(self.due, now) if self.state is State.WORKING else now
self.state = State.WORKING
self.off_until = None
self.due = base + minutes * 60
# Only warn again if the snooze is long enough for a warning to make sense.
self.warned = minutes * 60 <= self.cfg.warn_seconds * 2
self.snoozes += 1
def finish(self, now):
"""Break taken or skipped: start a fresh work period."""
self.snoozes = 0
self._start_work(now)
def turn_off(self, now, minutes=None):
self.state = State.OFF
self.off_until = now + minutes * 60 if minutes else None
def resume(self, now):
self.off_until = None
self.snoozes = 0
self._start_work(now)
def remaining(self, now):
return max(0.0, self.due - now)

34
pause/sound.py Normal file
View file

@ -0,0 +1,34 @@
import shutil
import subprocess
from pathlib import Path
from gi.repository import Gdk, Gtk
_FILES = {
"bell": "/usr/share/sounds/freedesktop/stereo/bell.oga",
"complete": "/usr/share/sounds/freedesktop/stereo/complete.oga",
}
_playing = []
def play(event_id):
"""Play a freedesktop theme sound, falling back to the system beep."""
player = shutil.which("canberra-gtk-play")
if player:
try:
subprocess.Popen([player, "-i", event_id],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return
except OSError:
pass
path = _FILES.get(event_id)
if path and Path(path).exists():
media = Gtk.MediaFile.new_for_filename(path)
# Keep a reference until it finishes, or it gets collected mid-sound.
_playing.append(media)
media.connect("notify::ended", lambda m, _: m in _playing and _playing.remove(m))
media.play()
return
display = Gdk.Display.get_default()
if display:
display.beep()

0
tests/__init__.py Normal file
View file

81
tests/test_notes.py Normal file
View file

@ -0,0 +1,81 @@
import datetime
import os
import tempfile
import unittest
from unittest import mock
from pause import config, exercises, notes
class NotesTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
patcher = mock.patch.dict(os.environ, {"XDG_DATA_HOME": self.tmp.name,
"XDG_CONFIG_HOME": self.tmp.name})
patcher.start()
self.addCleanup(patcher.stop)
self.addCleanup(self.tmp.cleanup)
def test_draft_roundtrip(self):
self.assertEqual(notes.load_draft(), "")
notes.save_draft("fixing the parser")
self.assertEqual(notes.load_draft(), "fixing the parser")
notes.save_draft(" ")
self.assertEqual(notes.load_draft(), "")
def test_record_clears_draft_and_appends(self):
notes.save_draft("draft")
when = datetime.datetime(2026, 9, 28, 14, 5)
notes.record("first\n\n## not a heading", when)
notes.record("", when)
notes.record("second", when + datetime.timedelta(minutes=30))
self.assertEqual(notes.load_draft(), "")
self.assertEqual(notes.recent(), [
("2026-09-28 14:05", "first\n\n## not a heading"),
("2026-09-28 14:35", "second"),
])
self.assertEqual(notes.recent(1), [("2026-09-28 14:35", "second")])
def test_stats(self):
day = datetime.datetime(2026, 9, 28, 10, 0).astimezone()
notes.log_event("taken", day)
notes.log_event("taken", day)
notes.log_event("snoozed", day - datetime.timedelta(days=1))
result = dict(notes.stats(days=3, today=day.date()))
self.assertEqual(result[day.date()]["taken"], 2)
self.assertEqual(result[day.date() - datetime.timedelta(days=1)]["snoozed"], 1)
self.assertEqual(len(result), 3)
def test_config_defaults_and_validation(self):
path = config.write_default()
self.assertEqual(config.load(path), config.Config())
path.write_text('work_minutes = 50\nsounds = "yes"\nbogus = 1\n')
with mock.patch("sys.stderr"):
cfg = config.load(path)
self.assertEqual(cfg.work_minutes, 50)
self.assertTrue(cfg.sounds)
class ExercisesTest(unittest.TestCase):
def test_plan_fills_break(self):
for seconds in (30, 90, 120, 300, 600):
steps = exercises.plan(seconds)
self.assertAlmostEqual(sum(s.seconds for s in steps), seconds)
self.assertTrue(all(s.seconds > 0 for s in steps))
def test_five_minute_break_has_all_eye_steps_then_walk(self):
steps = exercises.plan(300)
self.assertEqual(steps[:-1], exercises.EYE_STEPS)
self.assertEqual(steps[-1].title, exercises.WALK.title)
self.assertGreaterEqual(steps[-1].seconds, exercises.MIN_WALK)
def test_position(self):
steps = exercises.plan(300)
self.assertEqual(exercises.position(steps, 0), (0, 20))
self.assertEqual(exercises.position(steps, 25), (1, 10))
self.assertEqual(exercises.position(steps, 299)[0], len(steps) - 1)
self.assertEqual(exercises.position(steps, 400), (len(steps) - 1, 0.0))
if __name__ == "__main__":
unittest.main()

100
tests/test_scheduler.py Normal file
View file

@ -0,0 +1,100 @@
import unittest
from pause.config import Config
from pause.scheduler import BREAK, RESET, RESUMED, WARN, Scheduler, State
class SchedulerTest(unittest.TestCase):
def setUp(self):
self.cfg = Config(work_minutes=25, snooze_minutes=2, warn_seconds=60,
idle_reset_minutes=5)
self.s = Scheduler(self.cfg, 0)
def run_until(self, end, idle=0.0, step=1):
"""Tick once a second up to `end`; return {time: event} for non-None events."""
events = {}
t = self.s.last_tick
while t < end:
t += step
ev = self.s.tick(t, idle)
if ev:
events[t] = ev
return events
def test_warns_then_breaks(self):
events = self.run_until(25 * 60)
self.assertEqual(events, {24 * 60: WARN, 25 * 60: BREAK})
self.assertIs(self.s.state, State.BREAK)
def test_no_events_during_break(self):
self.run_until(25 * 60)
self.assertEqual(self.run_until(60 * 60), {})
def test_snooze_from_break_counts_from_now(self):
self.run_until(25 * 60)
self.s.snooze(25 * 60)
self.assertEqual(self.s.due, 27 * 60)
# A 2 minute snooze doesn't get its own warning.
self.assertEqual(self.run_until(27 * 60), {27 * 60: BREAK})
self.assertEqual(self.s.snoozes, 1)
def test_snooze_from_warning_pushes_break_back(self):
self.run_until(24 * 60 + 10)
self.s.snooze(24 * 60 + 10)
self.assertEqual(self.s.due, 27 * 60)
def test_long_snooze_warns_again(self):
self.run_until(25 * 60)
self.s.snooze(25 * 60, minutes=10)
self.assertEqual(self.run_until(35 * 60), {34 * 60: WARN, 35 * 60: BREAK})
def test_finish_starts_new_period(self):
self.run_until(25 * 60)
self.s.snooze(25 * 60)
self.s.finish(30 * 60)
self.assertEqual(self.s.snoozes, 0)
self.assertEqual(self.run_until(55 * 60), {54 * 60: WARN, 55 * 60: BREAK})
def test_suspend_resets_timer(self):
self.run_until(20 * 60)
self.assertEqual(self.s.tick(40 * 60, 0), RESET)
self.assertEqual(self.s.due, 65 * 60)
def test_idle_resets_when_back(self):
self.run_until(10 * 60)
self.assertEqual(self.run_until(16 * 60, idle=6 * 60), {})
self.assertTrue(self.s.away)
self.assertEqual(self.s.tick(16 * 60 + 1, idle=0), RESET)
self.assertEqual(self.s.due, 16 * 60 + 1 + 25 * 60)
def test_break_waits_while_idle(self):
self.run_until(24 * 60 + 30)
# Idle for 2 minutes when the break comes due: not shown yet.
self.assertEqual(self.run_until(25 * 60 + 30, idle=120), {})
self.assertEqual(self.s.tick(25 * 60 + 31, idle=0), BREAK)
def test_idle_reset_disabled(self):
self.cfg.idle_reset_minutes = 0
self.run_until(10 * 60)
# Without idle reset, a long gap (suspend) just means the break is due.
self.assertEqual(self.s.tick(40 * 60, 0), BREAK)
def test_off_for_minutes(self):
self.s.turn_off(0, minutes=60)
self.assertEqual(self.run_until(59 * 60), {})
self.assertEqual(self.s.tick(60 * 60, 0), RESUMED)
self.assertEqual(self.s.due, 85 * 60)
def test_off_indefinitely(self):
self.s.turn_off(0)
self.assertEqual(self.run_until(5 * 3600, step=60), {})
self.s.resume(5 * 3600)
self.assertIs(self.s.state, State.WORKING)
def test_break_now(self):
self.s.break_now(100)
self.assertIs(self.s.state, State.BREAK)
if __name__ == "__main__":
unittest.main()