pause/pause/app.py
agent 1bcbbfd8be Add a top-bar icon with a status menu, and a 2-hour off option
Pause now shows an eye in the GNOME top bar (open while breaks are on,
closed while they're off). Its menu shows the time to the next break and
offers Take a Break Now, Turn Off for an Hour / for 2 Hours, Turn Breaks
Back On and Quit.

It speaks StatusNotifierItem + dbusmenu over the app's own D-Bus
connection, so it needs the AppIndicator Shell extension (packaged in
Fedora) but no extra Python dependencies; libayatana-appindicator is
GTK 3 only and can't share a process with GTK 4. Without the extension
the icon just doesn't appear. Pause re-registers whenever the watcher
appears, so enabling the extension later or restarting the Shell works.

"Turn Off for 2 Hours" is also added to the app-grid right-click menu
and the status notification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F7w6vnQked3XNiTdTZDP8r
2026-10-26 13:37:35 +00:00

296 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import datetime
import math
from pathlib import Path
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
from .tray import MenuItem, Tray, separator
# Top-bar icons, found here when running from the checkout.
ICON_DIR = Path(__file__).resolve().parent.parent / "data" / "icons"
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.tray = 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()
self.tray = Tray(self.get_dbus_connection(), APP_ID, "Pause",
str(ICON_DIR) if ICON_DIR.is_dir() else "")
self._update_tray()
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":
self.quit_app()
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")
self._update_tray()
return True
# Top bar
def tray_status(self):
"""Like status(), but to the minute, so the menu doesn't change every second."""
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"
until = datetime.datetime.now() + datetime.timedelta(seconds=s.off_until - now)
return f"Breaks are off until {until:%H:%M}"
if s.away:
return "Away, timer restarts when you're back"
return f"Next break in {math.ceil(s.remaining(now) / 60)} min"
def _update_tray(self):
state = self.scheduler.state
status = self.tray_status()
self.tray.update(
"net.reudy.Pause-off-symbolic" if state is State.OFF else "net.reudy.Pause-symbolic",
status,
[
MenuItem("status", status),
separator("sep-actions"),
MenuItem("break-now", "Take a Break Now", self.take_break,
visible=state is State.WORKING),
MenuItem("on", "Turn Breaks Back On", self.turn_on, visible=state is State.OFF),
MenuItem("off-60", "Turn Off for an Hour", lambda: self.turn_off(60)),
MenuItem("off-120", "Turn Off for 2 Hours", lambda: self.turn_off(120)),
separator("sep-quit"),
MenuItem("quit", "Quit Pause", self.quit_app),
])
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 quit_app(self):
if self.overlay:
self.overlay.close()
if self.tray:
self.tray.close()
self.quit()
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))
n.add_button_with_target("Off for 2 hours", "app.off", GLib.Variant("u", 120))
self.send_notification("status", n)