Compare commits

..
14 Commits
6 changed files with 84 additions and 298 deletions

No files matched your search

+24 -64
View File
@@ -4,26 +4,22 @@ A fully automated break timer for wlroots-based desktop environments (SwayWM, et
## Features
- **Zero user interaction required** - Automatically tracks work/break cycles.
- **Dual break timers** - Independent short breaks (20m work → 20s break) and long breaks (45m work → 5m break).
- **Automatic idle detection** - Detects when you're away from the computer, even while an idle inhibitor (such as Waybar's "stay awake") is active.
- **Pause/Unpause** - Manually pause the timer when needed (paused time doesn't count toward work duration).
- **Reading mode** - Hands-off time counts as work while reading, and you start breaks from the menu.
- **Self-managing log** - Automatically trims old events to keep log size minimal.
- **Waybar integration** - Shows countdown timers in your status bar with context menu.
- **No dependencies** - Only requires Python 3 (pre-installed on most Linux systems).
- **No daemon process** - `break-idle` and swayidle are the only long-running processes. Other scripts are executed to modify or read the log file.
- **Zero user interaction required** - Automatically tracks work/break cycles
- **Dual break timers** - Independent short breaks (20m work → 20s break) and long breaks (45m work → 5m break)
- **Automatic idle detection** - Uses swayidle to detect when you're away from the computer
- **Pause/Unpause** - Manually pause the timer when needed (paused time doesn't count toward work duration)
- **Self-managing log** - Automatically trims old events to keep log size minimal
- **Waybar integration** - Shows countdown timers in your status bar with context menu
- **No dependencies** - Only requires Python 3 (pre-installed on most Linux systems)
## How It Works
1. **break-idle** monitors keyboard/mouse activity via the ext-idle-notify-v1 Wayland protocol
1. **swayidle** monitors keyboard/mouse activity via Wayland protocols
2. When idle timeout is reached, `break-event` logs an `idle_start` event
3. When you return, `break-event` logs an `idle_end` event
4. `break-status` parses the log to calculate active time and break status
5. Waybar polls `break-status` every second to display current timers
swayidle can't be used for the idle timeout because it obeys idle inhibitors, so activity would stop being tracked whenever an inhibitor is active. `break-idle` uses `get_input_idle_notification` (ext-idle-notify-v1 version 2, sway 1.11+), which only looks at real input. swayidle is still used to log sleep and resume.
### Timer Logic
- **Short breaks**: After 20 minutes of active work, you need a 20 second break
@@ -36,8 +32,8 @@ swayidle can't be used for the idle timeout because it obeys idle inhibitors, so
1. **Copy scripts to your PATH:**
```bash
chmod +x break-event break-idle break-status
cp break-event break-idle break-status ~/.local/bin/
chmod +x break-event break-status
cp break-event break-status ~/.local/bin/
```
2. **Create configuration directory:**
@@ -53,10 +49,11 @@ swayidle can't be used for the idle timeout because it obeys idle inhibitors, so
4. **Add to Sway config** (`~/.config/sway/config`):
```
exec break-idle 5
exec swayidle -w \
before-sleep 'break-event sleep' \
after-resume 'break-event wake'
timeout 5 'break-event idle_start' \
resume 'break-event idle_end' \
before-sleep 'break-event idle_start' \
after-resume 'break-event idle_end'
```
5. **Add to Waybar config** (`~/.config/waybar/config`):
@@ -68,21 +65,12 @@ swayidle can't be used for the idle timeout because it obeys idle inhibitors, so
"exec": "break-status",
"return-type": "json",
"interval": 1,
"format": "{icon} {}",
"format-icons": {
"normal": "🕐",
"reading": "📖",
"snoozed": "💤"
},
"format": "🕐 {}",
"tooltip": true,
"menu": "on-click",
"menu-file": "/path/to/menu.xml",
"menu-actions": {
"start-break": "break-event start-break",
"snooze": "break-event snooze",
"toggle-reading": "break-event toggle-reading",
"skip-long": "break-event skip_long",
"toggle-pause": "break-event toggle-pause"
"skip-long": "break-event skip_long"
}
}
}
@@ -99,15 +87,8 @@ swayidle can't be used for the idle timeout because it obeys idle inhibitors, so
}
#custom-break-timer.overdue {
font-weight: bold;
}
#custom-break-timer.overdue-short {
color: #fab387;
}
#custom-break-timer.overdue-long {
color: #f38ba8;
font-weight: bold;
}
#custom-break-timer.break {
@@ -118,10 +99,6 @@ swayidle can't be used for the idle timeout because it obeys idle inhibitors, so
color: #cba6f7;
font-style: italic;
}
#custom-break-timer.snoozed {
color: #9399b2;
}
```
7. **Reload Sway and Waybar:**
@@ -141,10 +118,9 @@ Edit `~/.config/break-timer/config.json`:
"duration": "20s" // Required short break length
},
"long_break": {
"interval": "45m", // Work duration before long break
"interval": "45", // Work duration before long break
"duration": "5m" // Required long break length
},
"snooze": "5m" // How long Snooze hides an overdue break (optional)
}
```
@@ -155,37 +131,27 @@ The Waybar module shows:
- **Working**: `15:30 / 45:20` - Time until short break (15min 30sec) and long break (45min 20sec)
- **Short break**: `SB 1:45` - Time remaining in short break
- **Long break**: `LB 8:30` - Time remaining in long break
- **Overdue**: `BREAK! 0:00 / 5:00` - You've exceeded a break time
- **Snoozed**: `3:20 (-2:30)` - Snooze time remaining, and how overdue the most overdue break is
- **Overdue**: `BREAK! -2:30 / 5:00` - You've exceeded a break time
- **Paused**: `⏸ PAUSED` - Timer is paused, no activity is being tracked
### Color Coding
- **Green (normal)**: Plenty of time until next break
- **Yellow (warning)**: Break due in less than 5 minutes
- **Orange (overdue-short)**: Short break time has passed, you should take a break!
- **Red (overdue-long)**: Long break time has passed, you should take a break!
- **Red (overdue)**: Break time has passed, you should take a break!
- **Blue (break)**: Currently in a break period
- **Purple (paused)**: Timer is paused
- **Grey (snoozed)**: An overdue break is snoozed
The overdue states also carry the `overdue` class, so one rule (such as a blink animation) can apply to both.
## Using the Context Menu
Right-click the break timer widget in Waybar to access the context menu:
- **Start Break**: Start a break now: a long break if one is due, otherwise a short break. Keyboard or mouse input ends it.
- **Snooze**: Hide overdue breaks for 5 minutes (configurable). Does nothing if no break is due. Snoozing again restarts the 5 minutes, a break that comes due during the snooze also waits, and taking a break ends the snooze. The timers keep counting, so when the snooze ends the widget shows the true overdue amount. The icon changes to 💤 while snoozed.
- **Toggle Reading Mode**: For reading or watching without touching the computer. While on:
- Hands-off time counts as work instead of a break
- Breaks only start from **Start Break**, and end on input
- The widget icon changes to 📖 (via `format-icons`)
- **Skip Long Break**: Reset all timers (useful if you just returned from a break not tracked by the timer)
- ** Toggle Pause**: Pause or unpause the timer. While paused:
- No activity is tracked
- Idle detection is disabled (idle events are not logged)
- The widget shows "⏸ PAUSED" in purple
- Only the "Unpause Timer" menu option is shown
## Log Management
@@ -203,7 +169,7 @@ Right-click the break timer widget in Waybar to access the context menu:
- Check log exists: `ls $XDG_RUNTIME_DIR/break-timer/`
### Timers don't update
- Verify break-idle is running: `pgrep -af break-idle` (if it exited, run it in a terminal to see the error)
- Verify swayidle is running: `ps aux | grep swayidle`
- Check if events are being logged: `cat $XDG_RUNTIME_DIR/break-timer/activity.log`
- Test event logging: `break-event idle_start` then `break-event idle_end`
@@ -216,7 +182,7 @@ Right-click the break timer widget in Waybar to access the context menu:
```
┌─────────────┐
│ break-idle │ Monitors compositor for keyboard/mouse activity
│ swayidle │ Monitors compositor for keyboard/mouse activity
└──────┬──────┘
│ timeout → idle_start
│ resume → idle_end
@@ -237,12 +203,6 @@ Right-click the break timer widget in Waybar to access the context menu:
└──────────────────────┘
```
## Similar Projects
- [Workrave](https://workrave.org/) - The original, and a great app, but does not have very robust Wayland support at the time this tool was created.
- [BreakTimer](https://breaktimer.app/) - Very nice interface, but only supports a single timer.
- [ianny](https://github.com/zefr0x/ianny) - Supports Wayland, but otherwise I have not explored deeply.
## License
MIT
Public domain - use however you like!
+8 -46
View File
@@ -2,13 +2,8 @@
"""
break-event - Log idle state transitions and auto-trim old events
Called by break-idle and swayidle to record when the user goes idle or resumes
activity, and by the Waybar menu. Automatically trims log entries before
qualifying break periods to keep log small.
In reading mode (a "reading" flag file next to the log), automatic idle is
ignored so hands-off reading counts as work. Breaks are started from the menu
with start-break and end on input.
Called by swayidle to record when the user goes idle or resumes activity.
Automatically trims log entries before qualifying break periods to keep log small.
"""
import os
@@ -171,31 +166,15 @@ def is_paused(events: Events) -> bool:
return bool(events and events[-1][1] == "paused")
def in_break(events: Events) -> bool:
"""Whether the last idle-related event started a break. With none (e.g.
after skip_long) there is no work period yet, so idle_end must be logged."""
for _, event_type in reversed(events):
if event_type == "idle_start":
return True
if event_type == "idle_end":
return False
return True
COMMANDS = ("idle_start", "idle_end", "sleep", "wake", "start-break", "snooze",
"skip_long", "toggle-pause", "toggle-reading")
def main():
if len(sys.argv) != 2 or sys.argv[1] not in COMMANDS:
print(f"Usage: break-event <{'|'.join(COMMANDS)}>", file=sys.stderr)
if len(sys.argv) != 2 or sys.argv[1] not in ("idle_start", "idle_end", "skip_long", "toggle-pause"):
print("Usage: break-event <idle_start|idle_end|skip_long|toggle-pause>", file=sys.stderr)
sys.exit(1)
event_type = sys.argv[1]
config = load_config()
log_path = get_log_path()
lock_path = log_path.parent / "break-timer.lock"
reading_path = log_path.parent / "reading"
# Convert config to seconds
long_break_duration = parse_duration(config["long_break"]["duration"])
@@ -217,28 +196,11 @@ def main():
event_key = "paused" if not is_paused(events) else "unpaused"
events.append((current_time, event_key))
write_log(log_path, events)
elif event_type == "toggle-reading":
if reading_path.exists():
reading_path.unlink()
else:
reading_path.touch()
elif not is_paused(events): # Don't log idle events when paused
reading = reading_path.exists()
if event_type == "start-break":
logged = "idle_start"
elif event_type == "snooze":
logged = "snoozed"
elif event_type in ("sleep", "wake"):
logged = "idle_start" if event_type == "sleep" else "idle_end"
elif reading and event_type == "idle_start":
logged = None
elif reading and event_type == "idle_end" and not in_break(events):
logged = None
else:
logged = event_type
if logged:
events.append((int(time.time()), logged))
# Don't log idle events when paused
if not is_paused(events):
current_time = int(time.time())
events.append((current_time, event_type))
events = trim_log(events, long_break_duration)
write_log(log_path, events)
finally:
-98
View File
@@ -1,98 +0,0 @@
#!/usr/bin/env python3
"""
break-idle - Report idle/resume to break-event, ignoring idle inhibitors
swayidle obeys idle inhibitors (e.g. Waybar's idle_inhibitor), which stops
activity tracking entirely while "stay awake" is on. This speaks the Wayland
wire protocol directly and uses ext-idle-notify-v1's version 2
get_input_idle_notification, which only considers real user input.
Usage: break-idle [timeout_seconds] (default 5)
"""
import os
import socket
import struct
import subprocess
import sys
from pathlib import Path
DISPLAY_ID, REGISTRY_ID, CALLBACK_ID, SEAT_ID, NOTIFIER_ID, NOTIFICATION_ID = range(1, 7)
BREAK_EVENT = Path(__file__).resolve().parent / "break-event"
def encode_string(s: str) -> bytes:
data = s.encode() + b"\0"
return struct.pack("=I", len(data)) + data + b"\0" * (-len(data) % 4)
def decode_string(payload: bytes, offset: int) -> tuple[str, int]:
(length,) = struct.unpack_from("=I", payload, offset)
start = offset + 4
return payload[start:start + length - 1].decode(), start + length + (-length % 4)
def send(sock: socket.socket, obj: int, opcode: int, args: bytes) -> None:
sock.sendall(struct.pack("=II", obj, (8 + len(args)) << 16 | opcode) + args)
def messages(sock: socket.socket):
buf = b""
while True:
chunk = sock.recv(4096)
if not chunk:
sys.exit("break-idle: compositor closed the connection")
buf += chunk
while len(buf) >= 8:
obj, size_op = struct.unpack_from("=II", buf)
size = size_op >> 16
if len(buf) < size:
break
yield obj, size_op & 0xFFFF, buf[8:size]
buf = buf[size:]
def main() -> None:
timeout = int(sys.argv[1]) if len(sys.argv) > 1 else 5
display = os.environ.get("WAYLAND_DISPLAY", "wayland-0")
path = display if display.startswith("/") else os.path.join(os.environ["XDG_RUNTIME_DIR"], display)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(path)
send(sock, DISPLAY_ID, 1, struct.pack("=I", REGISTRY_ID)) # wl_display.get_registry
send(sock, DISPLAY_ID, 0, struct.pack("=I", CALLBACK_ID)) # wl_display.sync
globals_: dict[str, tuple[int, int]] = {}
for obj, opcode, payload in messages(sock):
if obj == DISPLAY_ID and opcode == 0: # wl_display.error
sys.exit(f"break-idle: protocol error: {decode_string(payload, 8)[0]}")
if obj == REGISTRY_ID and opcode == 0: # wl_registry.global
(name,) = struct.unpack_from("=I", payload)
interface, offset = decode_string(payload, 4)
(version,) = struct.unpack_from("=I", payload, offset)
globals_.setdefault(interface, (name, version))
elif obj == CALLBACK_ID: # wl_callback.done: all globals received
break
notifier = globals_.get("ext_idle_notifier_v1")
if "wl_seat" not in globals_ or not notifier or notifier[1] < 2:
sys.exit("break-idle: compositor lacks ext_idle_notifier_v1 version 2 "
"(needed to ignore idle inhibitors)")
for interface, obj, version in (("wl_seat", SEAT_ID, 1), ("ext_idle_notifier_v1", NOTIFIER_ID, 2)):
args = struct.pack("=I", globals_[interface][0]) + encode_string(interface) + struct.pack("=II", version, obj)
send(sock, REGISTRY_ID, 0, args) # wl_registry.bind
# ext_idle_notifier_v1.get_input_idle_notification(id, timeout_ms, seat)
send(sock, NOTIFIER_ID, 2, struct.pack("=III", NOTIFICATION_ID, timeout * 1000, SEAT_ID))
for obj, opcode, payload in messages(sock):
if obj == DISPLAY_ID and opcode == 0:
sys.exit(f"break-idle: protocol error: {decode_string(payload, 8)[0]}")
if obj == NOTIFICATION_ID: # 0 = idled, 1 = resumed
subprocess.run([BREAK_EVENT, "idle_start" if opcode == 0 else "idle_end"])
if __name__ == "__main__":
main()
+51 -73
View File
@@ -25,14 +25,12 @@ class BreakConfig(TypedDict):
class Config(TypedDict):
short_break: BreakConfig
long_break: BreakConfig
snooze: NotRequired[str]
class Status(TypedDict):
state: str
short_remaining: int
long_remaining: int
break_remaining: NotRequired[int]
snooze_remaining: NotRequired[int]
def parse_duration(duration: str) -> int:
@@ -143,7 +141,6 @@ def calculate_status(events: Events, config: Config) -> Status:
short_duration = parse_duration(config["short_break"]["duration"])
long_interval = parse_duration(config["long_break"]["interval"])
long_duration = parse_duration(config["long_break"]["duration"])
snooze_duration = parse_duration(config.get("snooze", "5m"))
# If no events, assume just took breaks (timers at 0)
if not events:
@@ -153,12 +150,14 @@ def calculate_status(events: Events, config: Config) -> Status:
"long_remaining": long_interval,
}
# Track active time since each type of break
active_time_since_short_break = 0
active_time_since_long_break = 0
current_state = "working"
idle_start_time = None
pause_events = [e for e in events if e[1] in ("paused", "unpaused")]
idle_events = [e for e in events if e[1] in ("idle_start", "idle_end", "snoozed")]
snooze_until = None
idle_events = [e for e in events if e[1] in ("idle_start", "idle_end")]
# Helper to calculate paused time within a range
def get_paused_time_in_range(start_time: int, end_time: int) -> int:
@@ -185,56 +184,59 @@ def calculate_status(events: Events, config: Config) -> Status:
paused_time += end_time - max(pause_start, start_time)
return paused_time
def add_work(start: int, end: int) -> None:
nonlocal active_time_since_short_break, active_time_since_long_break
duration = end - start - get_paused_time_in_range(start, end)
# Process events to calculate active time and breaks
for i, (timestamp, event_type) in enumerate(idle_events):
if event_type == "idle_start":
current_state = "idle"
idle_start_time = timestamp
if i > 0 and events[i-1][1] == "idle_end":
# Active period just ended
active_end = timestamp
active_start = events[i-1][0]
duration = active_end - active_start
# Subtract any paused time within this active period
paused_time = get_paused_time_in_range(active_start, active_end)
duration -= paused_time
# Add to both counters, they reset independently
active_time_since_short_break += duration
active_time_since_long_break += duration
def credit_break(start: int, end: int) -> None:
nonlocal active_time_since_short_break, active_time_since_long_break, snooze_until
if end - start >= long_duration:
active_time_since_long_break = 0
if end - start >= short_duration:
active_time_since_short_break = 0
snooze_until = None # Taking a break uses up the snooze
# Replay the log. Exactly one of active_start / idle_start_time is set once
# the first event is seen.
active_start = None
idle_start_time = None
for timestamp, event_type in idle_events:
if event_type == "snoozed":
# Only counts if a break is due; snoozing again restarts it
pending = 0
if active_start is not None:
pending = timestamp - active_start - get_paused_time_in_range(active_start, timestamp)
if (active_time_since_short_break + pending >= short_interval
or active_time_since_long_break + pending >= long_interval):
snooze_until = timestamp + snooze_duration
elif event_type == "idle_end":
if idle_start_time is not None:
credit_break(idle_start_time, timestamp)
idle_start_time = None
if active_start is None:
active_start = timestamp
current_state = "working"
elif idle_start_time is None: # idle_start; ignored if already on a break
if active_start is not None:
add_work(active_start, timestamp)
active_start = None
idle_start_time = timestamp
if i > 0 and events[i-1][1] == "idle_start":
# Idle period just ended
idle_end = timestamp
idle_start = events[i-1][0]
idle_duration = idle_end - idle_start
if active_start is not None:
add_work(active_start, current_time)
# If the idle duration qualifies as a break, reset timers
if idle_duration >= long_duration:
active_time_since_long_break = 0
if idle_duration >= short_duration:
active_time_since_short_break = 0
if current_state == "working":
# If currently working, add time since last idle_end
if events and events[-1][1] == "idle_end":
last_active_start = events[-1][0]
current_active_duration = current_time - last_active_start
# Subtract any paused time in current active period
paused_time = get_paused_time_in_range(last_active_start, current_time)
current_active_duration -= paused_time
active_time_since_short_break += current_active_duration
active_time_since_long_break += current_active_duration
short_remaining = short_interval - active_time_since_short_break
long_remaining = long_interval - active_time_since_long_break
# Determine current state and calculate remaining times
if idle_start_time is not None:
if current_state == "idle" and idle_start_time:
# Currently idle - determine if in break
idle_elapsed = current_time - idle_start_time
@@ -265,14 +267,11 @@ def calculate_status(events: Events, config: Config) -> Status:
}
# Currently working
status: Status = {
return {
"state": "working",
"short_remaining": short_remaining,
"long_remaining": long_remaining,
}
if snooze_until is not None and current_time < snooze_until:
status["snooze_remaining"] = snooze_until - current_time
return status
def format_output(status: Status):
@@ -293,16 +292,8 @@ def format_output(status: Status):
long_time = format_time(status["long_remaining"])
# Determine urgency class
overdue = min(status["short_remaining"], status["long_remaining"])
if overdue <= 0 and "snooze_remaining" in status:
snooze_time = format_time(status["snooze_remaining"])
css_class = "snoozed"
text = f"{snooze_time} (-{format_time(-overdue)})"
elif status["long_remaining"] <= 0:
css_class = ["overdue", "overdue-long"]
text = f"BREAK! {short_time} / {long_time}"
elif status["short_remaining"] <= 0:
css_class = ["overdue", "overdue-short"]
if status["short_remaining"] <= 0 or status["long_remaining"] <= 0:
css_class = "overdue"
text = f"BREAK! {short_time} / {long_time}"
elif status["long_remaining"] < 300: # Less than 5 minutes
css_class = "warning"
@@ -312,21 +303,17 @@ def format_output(status: Status):
text = f"{short_time} / {long_time}"
tooltip = f"Short break in {short_time}\nLong break in {long_time}"
if css_class == "snoozed":
tooltip = f"Snoozed for {snooze_time}\n" + tooltip
elif state == "short_break":
break_time = format_time(status["break_remaining"])
short_time = format_time(status["short_remaining"])
css_class = "break"
text = f"SB {break_time} ({short_time})"
text = f"SB {break_time}"
tooltip = f"Short break ends in {break_time}"
elif state == "long_break":
break_time = format_time(status["break_remaining"])
long_time = format_time(status["long_remaining"])
css_class = "break"
text = f"LB {break_time} ({long_time})"
text = f"LB {break_time}"
tooltip = f"Long break ends in {break_time}"
elif state == "break_complete":
@@ -356,15 +343,6 @@ def main():
status = calculate_status(events, config)
output = format_output(status)
# Waybar's format-icons picks the icon by "alt"
reading = (log_path.parent / "reading").exists()
if reading:
output["tooltip"] += "\nReading mode: idle time counts as work"
if output["class"] == "snoozed":
output["alt"] = "snoozed"
else:
output["alt"] = "reading" if reading else "normal"
print(json.dumps(output))
+1 -2
View File
@@ -6,6 +6,5 @@
"long_break": {
"interval": "45m",
"duration": "5m"
},
"snooze": "5m"
}
}
-15
View File
@@ -1,21 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<object class="GtkMenu" id="menu">
<child>
<object class="GtkMenuItem" id="start-break">
<property name="label">Start Break</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="snooze">
<property name="label">Snooze</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="toggle-reading">
<property name="label">Toggle Reading Mode</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="skip-long">
<property name="label">Skip Long Break</property>