diff --git a/README.md b/README.md index b34a3c3..5446f70 100644 --- a/README.md +++ b/README.md @@ -21,12 +21,32 @@ 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 app-grid entry (open it to see the time left; right-click for *Take a Break Now* / *Turn Off for an Hour* / *for 2 Hours*) +- top-bar icons (see below) - 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). +### Top-bar icon + +Pause puts an eye in the top bar: open while breaks are on, closed while +they're off. Click it for the time to the next break and *Take a Break Now*, +*Turn Off for an Hour*, *Turn Off for 2 Hours*, *Turn Breaks Back On* and +*Quit Pause*. + +GNOME has no tray of its own, so this needs the AppIndicator extension, which +Fedora packages: + +```sh +sudo dnf install gnome-shell-extension-appindicator +``` + +Log out and back in (Wayland can't reload the Shell in place), then turn on +*AppIndicator and KStatusNotifierItem Support* in the Extensions app. Pause +picks it up on its own; no restart needed. Without the extension there's no +icon, and everything else works the same. + ## The break 1. A notification a minute before (**Snooze** / **Take it now**). @@ -73,9 +93,10 @@ 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 unittest # scheduler, notes, exercise-plan and tray 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`. +it can be tested with a fake clock. The break screen is in `pause/overlay.py`, the top-bar icon +(StatusNotifierItem + dbusmenu over D-Bus) in `pause/tray.py`. diff --git a/data/icons/hicolor/symbolic/apps/net.reudy.Pause-off-symbolic.svg b/data/icons/hicolor/symbolic/apps/net.reudy.Pause-off-symbolic.svg new file mode 100644 index 0000000..2bc4bc7 --- /dev/null +++ b/data/icons/hicolor/symbolic/apps/net.reudy.Pause-off-symbolic.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/data/icons/hicolor/symbolic/apps/net.reudy.Pause-symbolic.svg b/data/icons/hicolor/symbolic/apps/net.reudy.Pause-symbolic.svg new file mode 100644 index 0000000..bfbd565 --- /dev/null +++ b/data/icons/hicolor/symbolic/apps/net.reudy.Pause-symbolic.svg @@ -0,0 +1,4 @@ + + + + diff --git a/data/net.reudy.Pause.desktop b/data/net.reudy.Pause.desktop index 991c646..3c9dd7d 100644 --- a/data/net.reudy.Pause.desktop +++ b/data/net.reudy.Pause.desktop @@ -9,7 +9,7 @@ Categories=Utility; Keywords=break;timer;eyes;pomodoro;rest; StartupNotify=false X-GNOME-UsesNotifications=true -Actions=break-now;off-hour;on; +Actions=break-now;off-hour;off-2h;on; [Desktop Action break-now] Name=Take a Break Now @@ -19,6 +19,10 @@ Exec=@BIN@/pause now Name=Turn Off for an Hour Exec=@BIN@/pause off 60 +[Desktop Action off-2h] +Name=Turn Off for 2 Hours +Exec=@BIN@/pause off 120 + [Desktop Action on] Name=Turn Breaks Back On Exec=@BIN@/pause on diff --git a/install.sh b/install.sh index 4bf27b1..3338d22 100755 --- a/install.sh +++ b/install.sh @@ -12,10 +12,12 @@ 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 +SYMBOLIC=$DATA/icons/hicolor/symbolic/apps if [ "${1:-}" = "--uninstall" ]; then "$BIN/pause" quit 2>/dev/null || true - rm -f "$BIN/pause" "$DESKTOP" "$AUTOSTART" "$ICON" + rm -f "$BIN/pause" "$DESKTOP" "$AUTOSTART" "$ICON" \ + "$SYMBOLIC/$APP_ID-symbolic.svg" "$SYMBOLIC/$APP_ID-off-symbolic.svg" echo "Pause removed. Your notes are still in $DATA/pause/." exit 0 fi @@ -26,7 +28,7 @@ if ! python3 -c 'import gi; gi.require_version("Gtk", "4.0"); gi.require_version exit 1 fi -mkdir -p "$BIN" "$(dirname "$DESKTOP")" "$(dirname "$AUTOSTART")" "$(dirname "$ICON")" +mkdir -p "$BIN" "$(dirname "$DESKTOP")" "$(dirname "$AUTOSTART")" "$(dirname "$ICON")" "$SYMBOLIC" cat > "$BIN/pause" < "$DESKTOP" sed "s|@BIN@|$BIN|g" "$REPO/data/$APP_ID.autostart.desktop" > "$AUTOSTART" cp "$REPO/data/$APP_ID.svg" "$ICON" +# Top-bar icons. Pause also points the tray at the checkout, but installing +# them into the theme means any tray host can find them. +cp "$REPO/data/icons/hicolor/symbolic/apps/"*.svg "$SYMBOLIC/" 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 &" +if ! gnome-extensions info appindicatorsupport@rgcjonas.gmail.com >/dev/null 2>&1; then + echo "For the top-bar icon, install the AppIndicator extension (see README):" + echo " sudo dnf install gnome-shell-extension-appindicator" +fi case ":$PATH:" in *":$BIN:"*) ;; *) echo "Note: $BIN is not in your PATH; use $BIN/pause" ;; diff --git a/pause/app.py b/pause/app.py index c069d80..54b969a 100644 --- a/pause/app.py +++ b/pause/app.py @@ -1,4 +1,6 @@ import datetime +import math +from pathlib import Path import gi @@ -9,6 +11,10 @@ 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): @@ -18,6 +24,7 @@ class PauseApp(Adw.Application): 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 @@ -45,6 +52,9 @@ class PauseApp(Adw.Application): 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): @@ -94,9 +104,7 @@ class PauseApp(Adw.Application): self.turn_on() return self.status() if cmd == "quit": - if self.overlay: - self.overlay.close() - self.quit() + self.quit_app() return "Pause stopped." raise ValueError(f"unknown command {cmd!r}, see `pause help`") @@ -128,8 +136,44 @@ class PauseApp(Adw.Application): 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: @@ -191,6 +235,13 @@ class PauseApp(Adw.Application): 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: @@ -241,4 +292,5 @@ class PauseApp(Adw.Application): 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) diff --git a/pause/tray.py b/pause/tray.py new file mode 100644 index 0000000..2214d7f --- /dev/null +++ b/pause/tray.py @@ -0,0 +1,268 @@ +"""Top-bar icon with a status menu, over the StatusNotifierItem D-Bus protocol. + +GNOME Shell has no tray of its own; the AppIndicator extension +(`gnome-shell-extension-appindicator` on Fedora) shows these items. Without +it nobody is listening and the icon simply doesn't appear; the rest of Pause +works the same. + +Two objects are exported on the app's own session-bus connection: + +- /StatusNotifierItem org.kde.StatusNotifierItem: icon, tooltip, where the menu is +- /MenuBar com.canonical.dbusmenu: the menu itself, a flat list + +The libraries that usually do this (libayatana-appindicator) are GTK 3 only +and can't be loaded next to GTK 4, hence the hand-written D-Bus. +""" + +from gi.repository import Gio, GLib + +ITEM_PATH = "/StatusNotifierItem" +MENU_PATH = "/MenuBar" +WATCHER = "org.kde.StatusNotifierWatcher" + +INTERFACES = Gio.DBusNodeInfo.new_for_xml(""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""") + + +class MenuItem: + """One menu entry. `action=None` makes it a non-clickable label.""" + + def __init__(self, key, label, action=None, visible=True): + self.key, self.label, self.action, self.visible = key, label, action, visible + + def props(self): + if self.label is None: + return {"type": GLib.Variant("s", "separator")} + return { + "label": GLib.Variant("s", self.label.replace("_", "__")), # _ marks mnemonics + "enabled": GLib.Variant("b", self.action is not None), + "visible": GLib.Variant("b", self.visible), + } + + +def separator(key): + return MenuItem(key, None) + + +class Tray: + def __init__(self, connection, app_id, title, icon_theme_path=""): + self.conn = connection + self.app_id = app_id + self.title = title + self.icon_theme_path = icon_theme_path + self.icon_name = "" + self.tooltip = "" + self.items = [] + self.revision = 0 + self._ids = {} # item key -> stable dbusmenu id (0 is the root) + + sni, menu = INTERFACES.interfaces + self._registrations = [ + connection.register_object(ITEM_PATH, sni, self._item_call, self._item_property), + connection.register_object(MENU_PATH, menu, self._menu_call, self._menu_property), + ] + # The watcher comes and goes with the extension (and with every Shell + # restart), so register again whenever it appears. + self._watch = Gio.bus_watch_name_on_connection( + connection, WATCHER, Gio.BusNameWatcherFlags.NONE, self._on_watcher, None) + + def close(self): + Gio.bus_unwatch_name(self._watch) + for reg in self._registrations: + self.conn.unregister_object(reg) + + def update(self, icon_name, tooltip, items): + """Set what the tray shows. Only sends signals for what actually changed.""" + if icon_name != self.icon_name: + self.icon_name = icon_name + self._emit(ITEM_PATH, "org.kde.StatusNotifierItem", "NewIcon") + if tooltip != self.tooltip: + self.tooltip = tooltip + self._emit(ITEM_PATH, "org.kde.StatusNotifierItem", "NewToolTip") + for item in items: + self._ids.setdefault(item.key, len(self._ids) + 1) + if [(i.key, i.props()) for i in items] != [(i.key, i.props()) for i in self.items]: + self.items = items + self.revision += 1 + self._emit(MENU_PATH, "com.canonical.dbusmenu", "LayoutUpdated", + GLib.Variant("(ui)", (self.revision, 0))) + + def _emit(self, path, iface, signal, params=None): + try: + self.conn.emit_signal(None, path, iface, signal, params) + except GLib.Error: + pass # bus gone, e.g. while logging out + + def _on_watcher(self, conn, name, owner): + # Passing our object path (not a bus name) tells the watcher to use + # this connection's unique name, so we don't need to own a name. + conn.call(WATCHER, "/StatusNotifierWatcher", WATCHER, "RegisterStatusNotifierItem", + GLib.Variant("(s)", (ITEM_PATH,)), None, Gio.DBusCallFlags.NONE, + -1, None, None) + + # org.kde.StatusNotifierItem + + def _item_property(self, conn, sender, path, iface, name): + no_pixmap = GLib.Variant("a(iiay)", []) + return { + "Category": GLib.Variant("s", "ApplicationStatus"), + "Id": GLib.Variant("s", self.app_id), + "Title": GLib.Variant("s", self.title), + "Status": GLib.Variant("s", "Active"), + "WindowId": GLib.Variant("i", 0), + "IconName": GLib.Variant("s", self.icon_name), + "IconThemePath": GLib.Variant("s", self.icon_theme_path), + "IconPixmap": no_pixmap, + "OverlayIconName": GLib.Variant("s", ""), + "OverlayIconPixmap": no_pixmap, + "AttentionIconName": GLib.Variant("s", ""), + "AttentionIconPixmap": no_pixmap, + "AttentionMovieName": GLib.Variant("s", ""), + "ToolTip": GLib.Variant("(sa(iiay)ss)", ("", [], self.title, self.tooltip)), + "ItemIsMenu": GLib.Variant("b", True), + "Menu": GLib.Variant("o", MENU_PATH), + }.get(name) + + def _item_call(self, conn, sender, path, iface, method, params, invocation): + # ItemIsMenu: clicks open the menu, there's no separate activate action. + invocation.return_value(None) + + # com.canonical.dbusmenu + + def _menu_property(self, conn, sender, path, iface, name): + return { + "Version": GLib.Variant("u", 3), + "TextDirection": GLib.Variant("s", "ltr"), + "Status": GLib.Variant("s", "normal"), + "IconThemePath": GLib.Variant("as", []), + }.get(name) + + def _node(self, item): + return GLib.Variant("(ia{sv}av)", (self._ids[item.key], item.props(), [])) + + def _by_id(self, item_id): + return next((i for i in self.items if self._ids[i.key] == item_id), None) + + def _menu_call(self, conn, sender, path, iface, method, params, invocation): + args = params.unpack() + if method == "GetLayout": + parent = args[0] + if parent == 0: + root = (0, {"children-display": GLib.Variant("s", "submenu")}, + [self._node(i) for i in self.items]) + elif (item := self._by_id(parent)): + root = (parent, item.props(), []) + else: + invocation.return_dbus_error("com.canonical.dbusmenu.Error.UnknownId", + f"no menu item {parent}") + return + invocation.return_value(GLib.Variant("(u(ia{sv}av))", (self.revision, root))) + elif method == "GetGroupProperties": + found = [(i, self._by_id(i)) for i in args[0]] + invocation.return_value(GLib.Variant( + "(a(ia{sv}))", ([(i, item.props()) for i, item in found if item],))) + elif method == "GetProperty": + item = self._by_id(args[0]) + value = item.props().get(args[1]) if item else None + if value is None: + invocation.return_dbus_error("com.canonical.dbusmenu.Error.UnknownProperty", + f"no property {args[1]!r} on item {args[0]}") + return + invocation.return_value(GLib.Variant("(v)", (value,))) + elif method == "Event": + invocation.return_value(None) + self._clicked(args[0], args[1]) + elif method == "EventGroup": + invocation.return_value(GLib.Variant( + "(ai)", ([i for i, _, _, _ in args[0] if self._by_id(i) is None],))) + for item_id, event, _, _ in args[0]: + self._clicked(item_id, event) + elif method == "AboutToShow": + invocation.return_value(GLib.Variant("(b)", (False,))) + elif method == "AboutToShowGroup": + invocation.return_value(GLib.Variant("(aiai)", ([], []))) + else: + invocation.return_dbus_error("org.freedesktop.DBus.Error.UnknownMethod", method) + + def _clicked(self, item_id, event): + item = self._by_id(item_id) + if event == "clicked" and item and item.action: + # After the reply has gone out: some actions (quit) end the process. + GLib.idle_add(_run_once, item.action) + + +def _run_once(action): + action() + return GLib.SOURCE_REMOVE diff --git a/tests/test_tray.py b/tests/test_tray.py new file mode 100644 index 0000000..a929096 --- /dev/null +++ b/tests/test_tray.py @@ -0,0 +1,128 @@ +import unittest + +from gi.repository import Gio, GLib + +from pause.tray import MENU_PATH, ITEM_PATH, WATCHER, MenuItem, Tray, separator + +WATCHER_XML = Gio.DBusNodeInfo.new_for_xml(f""" + + +""") + + +class TrayTest(unittest.TestCase): + """Talks to the tray over a private session bus, like the Shell extension does.""" + + def setUp(self): + self.bus = Gio.TestDBus.new(Gio.TestDBusFlags.NONE) + self.bus.up() + addr = self.bus.get_bus_address() + flags = (Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT + | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION) + self.app_conn = Gio.DBusConnection.new_for_address_sync(addr, flags, None, None) + self.host = Gio.DBusConnection.new_for_address_sync(addr, flags, None, None) + self.clicked = [] + self.tray = Tray(self.app_conn, "test.App", "Test", "/icons") + + def tearDown(self): + self.tray.close() + self.app_conn.close_sync(None) + self.host.close_sync(None) + self.bus.down() + + def spin(self, until): + ctx = GLib.MainContext.default() + for _ in range(200): + if until(): + return + ctx.iteration(False) + GLib.usleep(5000) + self.fail("timed out waiting for D-Bus") + + def call(self, path, iface, method, args=None): + # Async: the tray answers on this same main loop, so a sync call would deadlock. + result = [] + self.host.call(self.app_conn.get_unique_name(), path, iface, method, args, None, + Gio.DBusCallFlags.NONE, 1000, None, + lambda conn, res: result.append(conn.call_finish(res))) + self.spin(lambda: result) + return result[0].unpack() + + def prop(self, path, iface, name): + return self.call(path, "org.freedesktop.DBus.Properties", "Get", + GLib.Variant("(ss)", (iface, name)))[0] + + def show(self, icon="icon-on", tooltip="Next break in 5 min"): + self.tray.update(icon, tooltip, [ + MenuItem("status", tooltip), + separator("sep"), + MenuItem("now", "Take a Break Now", lambda: self.clicked.append("now")), + MenuItem("on", "Turn Back On", lambda: self.clicked.append("on"), visible=False), + ]) + + def test_registers_when_watcher_appears(self): + registered = [] + + def on_call(conn, sender, path, iface, method, params, invocation): + registered.append((sender, params.unpack()[0])) + invocation.return_value(None) + + self.host.register_object("/StatusNotifierWatcher", WATCHER_XML.interfaces[0], + on_call, None, None) + Gio.bus_own_name_on_connection(self.host, WATCHER, Gio.BusNameOwnerFlags.NONE, + None, None) + self.spin(lambda: registered) + self.assertEqual(registered, [(self.app_conn.get_unique_name(), ITEM_PATH)]) + + def test_item_properties(self): + self.show() + sni = "org.kde.StatusNotifierItem" + self.assertEqual(self.prop(ITEM_PATH, sni, "IconName"), "icon-on") + self.assertEqual(self.prop(ITEM_PATH, sni, "IconThemePath"), "/icons") + self.assertEqual(self.prop(ITEM_PATH, sni, "Menu"), MENU_PATH) + self.assertEqual(self.prop(ITEM_PATH, sni, "ToolTip"), + ("", [], "Test", "Next break in 5 min")) + props = self.call(ITEM_PATH, "org.freedesktop.DBus.Properties", "GetAll", + GLib.Variant("(s)", (sni,)))[0] + self.assertTrue(props["ItemIsMenu"]) + + def test_layout(self): + self.show() + revision, (root_id, root_props, children) = self.call( + MENU_PATH, "com.canonical.dbusmenu", "GetLayout", + GLib.Variant("(iias)", (0, -1, []))) + self.assertEqual(root_id, 0) + self.assertEqual(root_props["children-display"], "submenu") + status, sep, now, on = [props for _, props, _ in children] + self.assertEqual(status, {"label": "Next break in 5 min", "enabled": False, + "visible": True}) + self.assertEqual(sep, {"type": "separator"}) + self.assertEqual(now["label"], "Take a Break Now") + self.assertTrue(now["enabled"]) + self.assertFalse(on["visible"]) + + def test_click_runs_action(self): + self.show() + children = self.call(MENU_PATH, "com.canonical.dbusmenu", "GetLayout", + GLib.Variant("(iias)", (0, -1, [])))[1][2] + now_id = children[2][0] + self.call(MENU_PATH, "com.canonical.dbusmenu", "Event", + GLib.Variant("(isvu)", (now_id, "clicked", GLib.Variant("i", 0), 0))) + self.spin(lambda: self.clicked) + self.assertEqual(self.clicked, ["now"]) + + def test_signals_only_on_change(self): + signals = [] + self.host.signal_subscribe(None, None, None, None, None, Gio.DBusSignalFlags.NONE, + lambda *a: signals.append(a[4])) + self.show() + self.spin(lambda: {"NewIcon", "NewToolTip", "LayoutUpdated"} <= set(signals)) + signals.clear() + self.show() # same again + self.show(tooltip="Next break in 4 min") + self.spin(lambda: "LayoutUpdated" in signals) + self.assertEqual(sorted(signals), ["LayoutUpdated", "NewToolTip"]) + + +if __name__ == "__main__": + unittest.main()