Merge pull request 'Add a top-bar icon with a status menu, and a 2-hour off option' (#2) from session/add-gnome-icon-with-status-and-o into initial-app
Reviewed-on: #2
This commit is contained in:
commit
e45d85efa5
8 changed files with 500 additions and 9 deletions
27
README.md
27
README.md
|
|
@ -21,12 +21,32 @@ pause &
|
||||||
`install.sh` doesn't need root. It adds:
|
`install.sh` doesn't need root. It adds:
|
||||||
|
|
||||||
- `~/.local/bin/pause`, a launcher that runs from the checkout, so `git pull` updates it
|
- `~/.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
|
- an autostart entry, so Pause starts when you log in
|
||||||
|
|
||||||
If it complains about missing modules: `sudo dnf install python3-gobject gtk4 libadwaita`.
|
If it complains about missing modules: `sudo dnf install python3-gobject gtk4 libadwaita`.
|
||||||
Remove it with `./install.sh --uninstall` (your notes are kept).
|
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
|
## The break
|
||||||
|
|
||||||
1. A notification a minute before (**Snooze** / **Take it now**).
|
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
|
## Development
|
||||||
|
|
||||||
```sh
|
```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
|
python3 -m pause # run from the checkout
|
||||||
```
|
```
|
||||||
|
|
||||||
The timing logic lives in `pause/scheduler.py` and has no GTK dependency, so
|
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`.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
|
||||||
|
<!-- Closed eye: breaks are turned off. -->
|
||||||
|
<path fill="#2e3436" d="M0.6 6.6C2 9.4 4.8 11.2 8 11.2s6-1.8 7.4-4.6L14 5.9C12.9 8.2 10.6 9.7 8 9.7S3.1 8.2 2 5.9Z"/>
|
||||||
|
<path fill="#2e3436" d="M7.3 10.5h1.4v3.3H7.3ZM3.9 9.9l1.3.5-1.1 2.7-1.3-.5ZM12.1 9.9l-1.3.5 1.1 2.7 1.3-.5ZM1.4 8.4l1.1.9-1.6 1.9-1.1-.9ZM14.6 8.4l-1.1.9 1.6 1.9 1.1-.9Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 433 B |
|
|
@ -0,0 +1,4 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
|
||||||
|
<!-- Open eye with pause bars in the pupil: breaks are on. -->
|
||||||
|
<path fill="#2e3436" fill-rule="evenodd" d="M8 3C4.4 3 1.6 5.3 0.4 8 1.6 10.7 4.4 13 8 13s6.4-2.3 7.6-5C14.4 5.3 11.6 3 8 3Zm0 1.5c-2.6 0-4.8 1.5-5.9 3.5 1.1 2 3.3 3.5 5.9 3.5s4.8-1.5 5.9-3.5c-1.1-2-3.3-3.5-5.9-3.5ZM8 5.2a2.8 2.8 0 1 0 0 5.6 2.8 2.8 0 0 0 0-5.6ZM6.7 6.6h1v2.8h-1Zm1.6 0h1v2.8h-1Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 458 B |
|
|
@ -9,7 +9,7 @@ Categories=Utility;
|
||||||
Keywords=break;timer;eyes;pomodoro;rest;
|
Keywords=break;timer;eyes;pomodoro;rest;
|
||||||
StartupNotify=false
|
StartupNotify=false
|
||||||
X-GNOME-UsesNotifications=true
|
X-GNOME-UsesNotifications=true
|
||||||
Actions=break-now;off-hour;on;
|
Actions=break-now;off-hour;off-2h;on;
|
||||||
|
|
||||||
[Desktop Action break-now]
|
[Desktop Action break-now]
|
||||||
Name=Take a Break Now
|
Name=Take a Break Now
|
||||||
|
|
@ -19,6 +19,10 @@ Exec=@BIN@/pause now
|
||||||
Name=Turn Off for an Hour
|
Name=Turn Off for an Hour
|
||||||
Exec=@BIN@/pause off 60
|
Exec=@BIN@/pause off 60
|
||||||
|
|
||||||
|
[Desktop Action off-2h]
|
||||||
|
Name=Turn Off for 2 Hours
|
||||||
|
Exec=@BIN@/pause off 120
|
||||||
|
|
||||||
[Desktop Action on]
|
[Desktop Action on]
|
||||||
Name=Turn Breaks Back On
|
Name=Turn Breaks Back On
|
||||||
Exec=@BIN@/pause on
|
Exec=@BIN@/pause on
|
||||||
|
|
|
||||||
13
install.sh
13
install.sh
|
|
@ -12,10 +12,12 @@ APP_ID=net.reudy.Pause
|
||||||
DESKTOP=$DATA/applications/$APP_ID.desktop
|
DESKTOP=$DATA/applications/$APP_ID.desktop
|
||||||
AUTOSTART=$CONFIG/autostart/$APP_ID.desktop
|
AUTOSTART=$CONFIG/autostart/$APP_ID.desktop
|
||||||
ICON=$DATA/icons/hicolor/scalable/apps/$APP_ID.svg
|
ICON=$DATA/icons/hicolor/scalable/apps/$APP_ID.svg
|
||||||
|
SYMBOLIC=$DATA/icons/hicolor/symbolic/apps
|
||||||
|
|
||||||
if [ "${1:-}" = "--uninstall" ]; then
|
if [ "${1:-}" = "--uninstall" ]; then
|
||||||
"$BIN/pause" quit 2>/dev/null || true
|
"$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/."
|
echo "Pause removed. Your notes are still in $DATA/pause/."
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
@ -26,7 +28,7 @@ if ! python3 -c 'import gi; gi.require_version("Gtk", "4.0"); gi.require_version
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
mkdir -p "$BIN" "$(dirname "$DESKTOP")" "$(dirname "$AUTOSTART")" "$(dirname "$ICON")"
|
mkdir -p "$BIN" "$(dirname "$DESKTOP")" "$(dirname "$AUTOSTART")" "$(dirname "$ICON")" "$SYMBOLIC"
|
||||||
|
|
||||||
cat > "$BIN/pause" <<EOF
|
cat > "$BIN/pause" <<EOF
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
|
|
@ -37,11 +39,18 @@ chmod +x "$BIN/pause"
|
||||||
sed "s|@BIN@|$BIN|g" "$REPO/data/$APP_ID.desktop" > "$DESKTOP"
|
sed "s|@BIN@|$BIN|g" "$REPO/data/$APP_ID.desktop" > "$DESKTOP"
|
||||||
sed "s|@BIN@|$BIN|g" "$REPO/data/$APP_ID.autostart.desktop" > "$AUTOSTART"
|
sed "s|@BIN@|$BIN|g" "$REPO/data/$APP_ID.autostart.desktop" > "$AUTOSTART"
|
||||||
cp "$REPO/data/$APP_ID.svg" "$ICON"
|
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
|
update-desktop-database "$DATA/applications" 2>/dev/null || true
|
||||||
gtk-update-icon-cache -q "$DATA/icons/hicolor" 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 "Installed. Pause starts automatically when you log in."
|
||||||
echo "Start it now with: pause &"
|
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
|
case ":$PATH:" in
|
||||||
*":$BIN:"*) ;;
|
*":$BIN:"*) ;;
|
||||||
*) echo "Note: $BIN is not in your PATH; use $BIN/pause" ;;
|
*) echo "Note: $BIN is not in your PATH; use $BIN/pause" ;;
|
||||||
|
|
|
||||||
58
pause/app.py
58
pause/app.py
|
|
@ -1,4 +1,6 @@
|
||||||
import datetime
|
import datetime
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import gi
|
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 . import APP_ID, config, notes, sound
|
||||||
from .overlay import CSS, BreakOverlay, fmt
|
from .overlay import CSS, BreakOverlay, fmt
|
||||||
from .scheduler import BREAK, RESET, RESUMED, WARN, Scheduler, State, clock
|
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):
|
class PauseApp(Adw.Application):
|
||||||
|
|
@ -18,6 +24,7 @@ class PauseApp(Adw.Application):
|
||||||
self.cfg = config.load()
|
self.cfg = config.load()
|
||||||
self.scheduler = None
|
self.scheduler = None
|
||||||
self.overlay = None
|
self.overlay = None
|
||||||
|
self.tray = None
|
||||||
self.idle_seconds = 0.0
|
self.idle_seconds = 0.0
|
||||||
self._idle_monitor = None
|
self._idle_monitor = None
|
||||||
self._idle_pending = False
|
self._idle_pending = False
|
||||||
|
|
@ -45,6 +52,9 @@ class PauseApp(Adw.Application):
|
||||||
self.hold()
|
self.hold()
|
||||||
self.scheduler = Scheduler(self.cfg, clock())
|
self.scheduler = Scheduler(self.cfg, clock())
|
||||||
self._connect_idle_monitor()
|
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)
|
GLib.timeout_add_seconds(1, self._tick)
|
||||||
|
|
||||||
def do_activate(self):
|
def do_activate(self):
|
||||||
|
|
@ -94,9 +104,7 @@ class PauseApp(Adw.Application):
|
||||||
self.turn_on()
|
self.turn_on()
|
||||||
return self.status()
|
return self.status()
|
||||||
if cmd == "quit":
|
if cmd == "quit":
|
||||||
if self.overlay:
|
self.quit_app()
|
||||||
self.overlay.close()
|
|
||||||
self.quit()
|
|
||||||
return "Pause stopped."
|
return "Pause stopped."
|
||||||
raise ValueError(f"unknown command {cmd!r}, see `pause help`")
|
raise ValueError(f"unknown command {cmd!r}, see `pause help`")
|
||||||
|
|
||||||
|
|
@ -128,8 +136,44 @@ class PauseApp(Adw.Application):
|
||||||
self._show_break()
|
self._show_break()
|
||||||
elif event in (RESET, RESUMED):
|
elif event in (RESET, RESUMED):
|
||||||
self.withdraw_notification("warning")
|
self.withdraw_notification("warning")
|
||||||
|
self._update_tray()
|
||||||
return True
|
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):
|
def _connect_idle_monitor(self):
|
||||||
"""Mutter tells us how long since the last keyboard/mouse input."""
|
"""Mutter tells us how long since the last keyboard/mouse input."""
|
||||||
try:
|
try:
|
||||||
|
|
@ -191,6 +235,13 @@ class PauseApp(Adw.Application):
|
||||||
if self.scheduler.state is State.OFF:
|
if self.scheduler.state is State.OFF:
|
||||||
self.scheduler.resume(clock())
|
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):
|
def _show_break(self):
|
||||||
self.withdraw_notification("warning")
|
self.withdraw_notification("warning")
|
||||||
if self.overlay is None:
|
if self.overlay is None:
|
||||||
|
|
@ -241,4 +292,5 @@ class PauseApp(Adw.Application):
|
||||||
else:
|
else:
|
||||||
n.add_button("Take a break now", "app.break-now")
|
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 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)
|
self.send_notification("status", n)
|
||||||
|
|
|
||||||
268
pause/tray.py
Normal file
268
pause/tray.py
Normal file
|
|
@ -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("""
|
||||||
|
<node>
|
||||||
|
<interface name="org.kde.StatusNotifierItem">
|
||||||
|
<property name="Category" type="s" access="read"/>
|
||||||
|
<property name="Id" type="s" access="read"/>
|
||||||
|
<property name="Title" type="s" access="read"/>
|
||||||
|
<property name="Status" type="s" access="read"/>
|
||||||
|
<property name="WindowId" type="i" access="read"/>
|
||||||
|
<property name="IconName" type="s" access="read"/>
|
||||||
|
<property name="IconThemePath" type="s" access="read"/>
|
||||||
|
<property name="IconPixmap" type="a(iiay)" access="read"/>
|
||||||
|
<property name="OverlayIconName" type="s" access="read"/>
|
||||||
|
<property name="OverlayIconPixmap" type="a(iiay)" access="read"/>
|
||||||
|
<property name="AttentionIconName" type="s" access="read"/>
|
||||||
|
<property name="AttentionIconPixmap" type="a(iiay)" access="read"/>
|
||||||
|
<property name="AttentionMovieName" type="s" access="read"/>
|
||||||
|
<property name="ToolTip" type="(sa(iiay)ss)" access="read"/>
|
||||||
|
<property name="ItemIsMenu" type="b" access="read"/>
|
||||||
|
<property name="Menu" type="o" access="read"/>
|
||||||
|
<method name="ContextMenu"><arg name="x" type="i"/><arg name="y" type="i"/></method>
|
||||||
|
<method name="Activate"><arg name="x" type="i"/><arg name="y" type="i"/></method>
|
||||||
|
<method name="SecondaryActivate"><arg name="x" type="i"/><arg name="y" type="i"/></method>
|
||||||
|
<method name="Scroll"><arg name="delta" type="i"/><arg name="orientation" type="s"/></method>
|
||||||
|
<signal name="NewIcon"/>
|
||||||
|
<signal name="NewToolTip"/>
|
||||||
|
</interface>
|
||||||
|
<interface name="com.canonical.dbusmenu">
|
||||||
|
<property name="Version" type="u" access="read"/>
|
||||||
|
<property name="TextDirection" type="s" access="read"/>
|
||||||
|
<property name="Status" type="s" access="read"/>
|
||||||
|
<property name="IconThemePath" type="as" access="read"/>
|
||||||
|
<method name="GetLayout">
|
||||||
|
<arg name="parentId" type="i" direction="in"/>
|
||||||
|
<arg name="recursionDepth" type="i" direction="in"/>
|
||||||
|
<arg name="propertyNames" type="as" direction="in"/>
|
||||||
|
<arg name="revision" type="u" direction="out"/>
|
||||||
|
<arg name="layout" type="(ia{sv}av)" direction="out"/>
|
||||||
|
</method>
|
||||||
|
<method name="GetGroupProperties">
|
||||||
|
<arg name="ids" type="ai" direction="in"/>
|
||||||
|
<arg name="propertyNames" type="as" direction="in"/>
|
||||||
|
<arg name="properties" type="a(ia{sv})" direction="out"/>
|
||||||
|
</method>
|
||||||
|
<method name="GetProperty">
|
||||||
|
<arg name="id" type="i" direction="in"/>
|
||||||
|
<arg name="name" type="s" direction="in"/>
|
||||||
|
<arg name="value" type="v" direction="out"/>
|
||||||
|
</method>
|
||||||
|
<method name="Event">
|
||||||
|
<arg name="id" type="i" direction="in"/>
|
||||||
|
<arg name="eventId" type="s" direction="in"/>
|
||||||
|
<arg name="data" type="v" direction="in"/>
|
||||||
|
<arg name="timestamp" type="u" direction="in"/>
|
||||||
|
</method>
|
||||||
|
<method name="EventGroup">
|
||||||
|
<arg name="events" type="a(isvu)" direction="in"/>
|
||||||
|
<arg name="idErrors" type="ai" direction="out"/>
|
||||||
|
</method>
|
||||||
|
<method name="AboutToShow">
|
||||||
|
<arg name="id" type="i" direction="in"/>
|
||||||
|
<arg name="needUpdate" type="b" direction="out"/>
|
||||||
|
</method>
|
||||||
|
<method name="AboutToShowGroup">
|
||||||
|
<arg name="ids" type="ai" direction="in"/>
|
||||||
|
<arg name="updatesNeeded" type="ai" direction="out"/>
|
||||||
|
<arg name="idErrors" type="ai" direction="out"/>
|
||||||
|
</method>
|
||||||
|
<signal name="LayoutUpdated">
|
||||||
|
<arg name="revision" type="u"/>
|
||||||
|
<arg name="parent" type="i"/>
|
||||||
|
</signal>
|
||||||
|
</interface>
|
||||||
|
</node>
|
||||||
|
""")
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
128
tests/test_tray.py
Normal file
128
tests/test_tray.py
Normal file
|
|
@ -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"""
|
||||||
|
<node><interface name="{WATCHER}">
|
||||||
|
<method name="RegisterStatusNotifierItem"><arg name="service" type="s"/></method>
|
||||||
|
</interface></node>""")
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
Loading…
Add table
Add a link
Reference in a new issue