Compare commits

85 Commits

Author SHA1 Message Date
6da7e97f19 feat: mail finder 2026-05-06 23:12:57 +02:00
cfdcf0c039 feat: email debt timer 2026-05-06 21:22:27 +02:00
4adace6c4c feat: subscribe to all players 2026-05-05 23:58:15 +02:00
cc3bac5ce7 feat: player animations 2026-05-05 23:47:47 +02:00
81e1a1fc1f feat: mpris player widget 2026-05-05 23:15:09 +02:00
d14a0c9678 fix: start apps not in this service cgroup 2026-05-05 20:50:18 +02:00
47e104465e feat: control center 2026-05-05 00:19:10 +02:00
4a271ac4d8 feat: notification markup support 2026-05-04 23:05:23 +02:00
5e8f9e44bb fix: drop full emacs runtime dep, only emacsclient is used
sims only invokes emacsclient (in modules/notmuch.py) and never the
full emacs binary. Bundling emacs onto the wrapper PATH was forcing
consumers to pull in an extra ~310M emacs closure (often a different
version from the user's actual editor). Rely on the consumer's
emacsclient via PATH, configurable via services.sims.settings.notmuch.emacsclient_command.
2026-05-04 22:56:12 +02:00
047a85925a feat: sims notifications 2026-05-04 21:31:09 +02:00
4c8b9020b0 fix: start apps in subprocess 2026-05-04 20:06:52 +02:00
e7a1a2c0ee feat: spawn layer shells on correct output 2026-05-04 19:50:06 +02:00
cb3b7bf392 fix: correct smart corner events 2026-05-04 19:40:39 +02:00
f83b7ce874 fix: launchers should have exclusive focus 2026-05-04 19:29:56 +02:00
ec7e2cd6fd fix: render more of launchers 2026-05-04 19:15:26 +02:00
6f4e397f6c feat: clipboard menu 2026-05-04 17:01:08 +02:00
aad8121fa4 fix: only show screenrec when recording 2026-05-04 12:09:39 +02:00
709695fd22 fix: dont ship weird default styles 2026-05-04 12:03:48 +02:00
1d98a541de fix: click on workspace 2026-05-04 11:35:14 +02:00
af978f5baf feat: round bar on smart corners
also take in the i3 ipc code to support custom messages
2026-05-04 11:07:34 +02:00
6343c91fca fix: instantly spawn bar 2026-05-04 00:00:11 +02:00
0cd58f4a1f feat: sims cli as python package 2026-05-03 22:19:52 +02:00
afcf8d51fe feat: power and screenshot launchers 2026-05-03 21:53:10 +02:00
7bdf23001f feat: add app launcher 2026-05-03 21:42:30 +02:00
60757ee336 feat: sims launcher 2026-05-03 20:40:21 +02:00
c10709df26 feat: rename to sims 2026-05-03 20:15:43 +02:00
fb206667c4 feat: dim other monitors workspaces 2026-05-03 19:05:46 +02:00
aee5be7f39 fix: stylix needs to generate visible colours 2026-05-03 18:53:37 +02:00
d1b6d3a560 feat: always show 9 bubbles 2026-05-03 14:58:52 +02:00
0d4c4caf10 feat: show visible and active workspaces 2026-05-03 14:47:20 +02:00
f1c45a7f8c feat: use fenster ipc (sway/i3 compatible) 2026-03-10 22:58:40 +01:00
7962947f80 feat: refresh mail widget 2025-10-18 20:38:03 +02:00
c256931b1d feat: log level in nix 2025-10-17 17:44:49 +02:00
5137379ac9 shadow preparation
the shadow needs to be done on the compositor
2025-09-30 20:54:57 +02:00
159eafbc73 quick menu 2025-09-30 20:52:03 +02:00
7b0a4a56db better vinyl styling 2025-09-30 12:56:05 +02:00
9666a2f7ae fix: nix paths 2025-09-30 00:48:41 +02:00
0be71cfddf prod logging 2025-09-30 00:35:27 +02:00
2d3f97cae1 fix: khal and notmuch in path 2025-09-30 00:29:02 +02:00
15077fe6fa feat: mail 2025-09-29 23:24:33 +02:00
34e837562f better calendar styling 2025-09-29 18:45:36 +02:00
a22f16a84f fix: run 2025-09-29 18:32:05 +02:00
17d11591ac dev mode 2025-09-29 18:29:57 +02:00
05f20d65b9 notch docs 2025-09-29 18:29:24 +02:00
0b3ee96ccf better calendar styling 2025-09-29 17:00:53 +02:00
dd6feb4170 stylix font size 2025-09-29 16:42:44 +02:00
5cea889af3 feat: calendar in bar 2025-09-29 16:36:43 +02:00
f781603907 example dev stylix yaml 2025-09-29 12:54:58 +02:00
5afada0fb3 better workspace styling 2025-09-29 12:52:03 +02:00
055f4ebb96 better snowflake symbol 2025-09-29 12:44:48 +02:00
da2a7d94d8 new workspace styling 2025-09-29 12:27:24 +02:00
c814eb01de smaller stylix workspace buttons 2025-09-29 11:40:51 +02:00
03598694fc fix: stylix workspace buttons 2025-09-29 11:39:16 +02:00
c4e522f17a fix battery usage 2025-09-29 11:36:33 +02:00
fe87de7580 fix stylix stylesheet 2025-09-29 11:19:13 +02:00
5c2ee58f4d fix: stylix enable option 2025-09-29 11:13:34 +02:00
4fda2670ac feat: stylix support 2025-09-29 11:10:25 +02:00
d9a176d4ec window title option 2025-09-29 11:02:48 +02:00
1a24c4eb99 add makefile 2025-09-29 10:56:37 +02:00
0ce3d286e2 bar height 2025-09-29 10:51:21 +02:00
7a6eca395d fix: correct battery icons 2025-09-29 10:34:24 +02:00
40ab13ab26 fix: really run battery updates 2025-09-29 10:12:12 +02:00
56c35ec7ec fix: battery run 2025-09-29 09:19:09 +02:00
e3396be9af battery icons 2025-09-29 09:13:40 +02:00
fc264dda44 feat: battery 2025-09-29 09:01:23 +02:00
df2bef7685 fix: vinyl 2025-05-19 10:44:26 +02:00
5d08a48b6c init: window finder 2025-05-15 23:29:20 +02:00
82b0cf7aaa feat: nixos dbus availability 2025-05-15 18:38:00 +02:00
e4744bab81 right module order 2025-05-13 23:22:03 +02:00
872dbfc792 fix vinyl enable 2025-05-13 23:18:06 +02:00
64781af68f add default 2025-05-13 23:13:45 +02:00
0ebfbdb3a9 add yaml example 2025-05-13 23:10:23 +02:00
bf3920ad35 config 2025-05-13 23:09:05 +02:00
72c76c9fda move river service to fabric fork
so i could request merge to upstream later
2025-05-12 12:31:30 +02:00
743e1ed0c5 update fabric 2025-05-12 12:01:43 +02:00
f28dd0b6a2 move nix 2025-05-12 11:18:04 +02:00
0b8190ae8b not working rework 2025-05-10 12:24:52 +02:00
9495dfba62 feat: river-control-unstable-v1 2025-05-06 13:57:30 +02:00
0cf1c5aeb7 isort 2025-05-06 13:15:44 +02:00
f8b352d624 multiple monitor support 2025-05-06 13:09:40 +02:00
53713ee0f5 more modules 2025-05-05 20:13:39 +02:00
736e1a47c9 urgent tags 2025-05-05 09:31:17 +02:00
0966c1ce70 white workspace 2025-05-04 20:40:14 +02:00
2541edd0f4 add icon 2025-05-04 20:38:00 +02:00
ce030a8734 default package 2025-05-04 18:41:50 +02:00
83 changed files with 7810 additions and 1950 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
__pycache__
.direnv

15
Makefile Normal file
View File

@@ -0,0 +1,15 @@
run:
python -m sims.main --config ./example-stylix-dev.yaml
# Talk to the running sims daemon over DBus.
# Usage: make cli list
# make cli finder
# make cli screenrec stop
# make cli ARGS="list --json" # for flags (make eats leading dashes)
ifeq (cli,$(firstword $(MAKECMDGOALS)))
CLI_ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
$(eval $(CLI_ARGS):;@:)
endif
cli:
@python -m sims.cli $(if $(ARGS),$(ARGS),$(CLI_ARGS))

14
README.md Normal file
View File

@@ -0,0 +1,14 @@
# Todo
# Ideas
## Org-mode integration
- https://github.com/jlumpe/pyorg
- https://github.com/jlumpe/ox-json
## Emails not seen
with notmuch
## notch power bar
- show the power around the notch
- show watts charging/discharging in bar
- https://lo.cafe/notchnook
## Screenshot menu
## Media Playing

View File

@@ -1,170 +0,0 @@
/* Fabric bar.css
* https://github.com/Fabric-Development/fabric/blob/rewrite/examples/bar/bar.css
* Modified with Camellia Theme: https://github.com/camellia-theme/camellia
*/
/* we can use webcss variables, fabric compiles that to gtk css.
global variables can be stored in :vars */
:vars {
/* Base colors from Camellia theme */
--background: #17181C; /* BG */
--mid-bg: #1E1F24; /* Mid BG */
--light-bg: #26272B; /* Light BG */
--dark-grey: #333438; /* Dark Grey */
--light-grey: #8F9093; /* Light Grey */
--dark-fg: #B0B1B4; /* Dark FG */
--mid-fg: #CBCCCE; /* Mid FG */
--foreground: #E4E5E7; /* FG */
/* Accent colors from Camellia theme */
--pink: #FA3867; /* Pink */
--orange: #F3872F; /* Orange */
--gold: #FEBD16; /* Gold */
--lime: #3FD43B; /* Lime */
--turquoise: #47E7CE; /* Turquoise */
--blue: #53ADE1; /* Blue */
--violet: #AD60FF; /* Violet */
--red: #FC3F2C; /* Red */
/* Functional variables */
--window-bg: alpha(var(--background), 0.9);
--module-bg: alpha(var(--mid-bg), 0.8);
--border-color: var(--light-bg);
--ws-active: var(--pink);
--ws-inactive: var(--blue);
--ws-empty: var(--dark-grey);
--ws-hover: var(--turquoise);
--ws-urgent: var(--red);
}
/* unset so we can style everything from the ground up. */
* {
all: unset;
color: var(--foreground);
font-size: 16px;
font-family: "Jost*", sans-serif;
}
button {
background-size: 400% 400%;
}
#bar-inner {
padding: 4px;
border-bottom: solid 2px;
border-color: var(--border-color);
background-color: var(--window-bg);
min-height: 28px;
}
#workspaces {
padding: 6px;
min-width: 0px;
background-color: var(--module-bg);
}
#workspaces>button {
padding: 0px 8px;
transition: padding 0.05s steps(8);
background-color: var(--ws-inactive);
border-radius: 100px;
}
#workspaces>button>label {
font-size: 0px;
}
#workspaces>button:hover {
background-color: var(--ws-hover);
}
#workspaces>button.urgent {
background-color: var(--ws-urgent);
}
#workspaces>button.empty {
background-color: var(--ws-empty);
}
#workspaces>button.active {
padding: 0px 32px;
background-color: var(--ws-active);
}
#center-container {
color: var(--foreground);
}
.active-window {
color: var(--foreground);
font-weight: bold;
}
#date-time,
menu>menuitem>label,
#date-time>label,
/* system tray */
#system-tray {
padding: 2px 4px;
background-color: var(--module-bg);
}
/* menu and menu items (written for the system tray) */
menu {
border: solid 2px;
border-radius: 10px;
border-color: var(--border-color);
background-color: var(--window-bg);
}
menu>menuitem {
border-radius: 0px;
background-color: var(--module-bg);
padding: 6px;
margin-left: 2px;
margin-right: 2px;
}
menu>menuitem:first-child {
margin-top: 1px;
border-radius: 8px 8px 0px 0px;
}
menu>menuitem:last-child {
margin-bottom: 1px;
border-radius: 0px 0px 8px 8px;
}
menu>menuitem:hover {
background-color: var(--pink);
}
#cpu-progress-bar,
#ram-progress-bar,
#volume-progress-bar {
color: transparent;
background-color: transparent
}
#cpu-progress-bar {
border: solid 0px alpha(var(--violet), 0.8);
}
#ram-progress-bar,
#volume-progress-bar {
border: solid 0px var(--blue);
}
#widgets-container {
background-color: var(--module-bg);
padding: 2px;
}
tooltip {
border: solid 2px;
border-color: var(--border-color);
background-color: var(--window-bg);
}
tooltip>* {
padding: 2px 4px
}

View File

@@ -1,178 +0,0 @@
# fabric bar.py example
# https://github.com/Fabric-Development/fabric/blob/rewrite/examples/bar/bar.py
import psutil
from fabric import Application
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.overlay import Overlay
from fabric.widgets.eventbox import EventBox
from fabric.widgets.datetime import DateTime
from fabric.widgets.centerbox import CenterBox
from fabric.system_tray.widgets import SystemTray
from fabric.widgets.circularprogressbar import CircularProgressBar
from fabric.widgets.wayland import WaylandWindow as Window
from .river.widgets import RiverWorkspaces, RiverWorkspaceButton, RiverActiveWindow
from fabric.utils import (
FormattedString,
bulk_replace,
invoke_repeater,
get_relative_path,
)
AUDIO_WIDGET = True
if AUDIO_WIDGET is True:
try:
from fabric.audio.service import Audio
except Exception as e:
print(e)
AUDIO_WIDGET = False
class VolumeWidget(Box):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.audio = Audio()
self.progress_bar = CircularProgressBar(
name="volume-progress-bar", pie=True, size=24
)
self.event_box = EventBox(
events="scroll",
child=Overlay(
child=self.progress_bar,
overlays=Label(
label="",
style="margin: 0px 6px 0px 0px; font-size: 12px", # to center the icon glyph
),
),
)
self.audio.connect("notify::speaker", self.on_speaker_changed)
self.event_box.connect("scroll-event", self.on_scroll)
self.add(self.event_box)
def on_scroll(self, _, event):
match event.direction:
case 0:
self.audio.speaker.volume += 8
case 1:
self.audio.speaker.volume -= 8
return
def on_speaker_changed(self, *_):
if not self.audio.speaker:
return
self.progress_bar.value = self.audio.speaker.volume / 100
self.audio.speaker.bind(
"volume", "value", self.progress_bar, lambda _, v: v / 100
)
return
class StatusBar(Window):
def __init__(self, display: int, monitor: int = 1, with_system_tray: bool = False):
super().__init__(
name="bar",
layer="top",
anchor="left top right",
margin="0px 0px -2px 0px",
exclusivity="auto",
visible=False,
all_visible=False,
monitor=monitor,
)
self.workspaces = RiverWorkspaces(
display,
name="workspaces",
spacing=4,
buttons_factory=lambda ws_id: RiverWorkspaceButton(id=ws_id, label=None),
)
self.date_time = DateTime(name="date-time", formatters="%d %b - %H:%M")
self.system_tray = None
if with_system_tray:
self.system_tray = SystemTray(name="system-tray", spacing=4)
self.active_window = RiverActiveWindow(
name="active-window",
max_length=50,
style="color: #ffffff; font-size: 14px; font-weight: bold;",
)
self.ram_progress_bar = CircularProgressBar(
name="ram-progress-bar", pie=True, size=24
)
self.cpu_progress_bar = CircularProgressBar(
name="cpu-progress-bar", pie=True, size=24
)
self.progress_bars_overlay = Overlay(
child=self.ram_progress_bar,
overlays=[
self.cpu_progress_bar,
Label("", style="margin: 0px 6px 0px 0px; font-size: 12px"),
],
)
self.status_container = Box(
name="widgets-container",
spacing=4,
orientation="h",
children=self.progress_bars_overlay,
)
self.status_container.add(VolumeWidget()) if AUDIO_WIDGET is True else None
end_container_children = [
self.status_container,
self.date_time,
]
if self.system_tray is not None:
end_container_children = [
self.status_container,
self.system_tray,
self.date_time,
]
self.children = CenterBox(
name="bar-inner",
start_children=Box(
name="start-container",
spacing=4,
orientation="h",
children=self.workspaces,
),
center_children=Box(
name="center-container",
spacing=4,
orientation="h",
children=[self.active_window],
),
end_children=Box(
name="end-container",
spacing=4,
orientation="h",
children=end_container_children,
),
)
invoke_repeater(1000, self.update_progress_bars)
self.show_all()
def update_progress_bars(self):
self.ram_progress_bar.value = psutil.virtual_memory().percent / 100
self.cpu_progress_bar.value = psutil.cpu_percent() / 100
return True
def main():
bar = StatusBar(45)
bar_two = StatusBar(44, monitor=2, with_system_tray=True)
app = Application("bar", bar, bar_two)
app.set_stylesheet_from_file(get_relative_path("bar.css"))
app.run()
if __name__ == "__main__":
main()

View File

@@ -1,3 +0,0 @@
from .service import River
__all__ = ["River"]

View File

@@ -1,18 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright 2020 The River Developers
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from .zriver_command_callback_v1 import ZriverCommandCallbackV1 # noqa: F401
from .zriver_control_v1 import ZriverControlV1 # noqa: F401

View File

@@ -1,90 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright 2020 The River Developers
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class ZriverCommandCallbackV1(Interface):
"""Callback object
This object is created by the run_command request. Exactly one of the
success or failure events will be sent. This object will be destroyed by
the compositor after one of the events is sent.
"""
name = "zriver_command_callback_v1"
version = 1
class ZriverCommandCallbackV1Proxy(Proxy[ZriverCommandCallbackV1]):
interface = ZriverCommandCallbackV1
class ZriverCommandCallbackV1Resource(Resource):
interface = ZriverCommandCallbackV1
@ZriverCommandCallbackV1.event(
Argument(ArgumentType.String),
)
def success(self, output: str) -> None:
"""Command successful
Sent when the command has been successfully received and executed by
the compositor. Some commands may produce output, in which case the
output argument will be a non-empty string.
:param output:
the output of the command
:type output:
`ArgumentType.String`
"""
self._post_event(0, output)
@ZriverCommandCallbackV1.event(
Argument(ArgumentType.String),
)
def failure(self, failure_message: str) -> None:
"""Command failed
Sent when the command could not be carried out. This could be due to
sending a non-existent command, no command, not enough arguments, too
many arguments, invalid arguments, etc.
:param failure_message:
a message explaining why failure occurred
:type failure_message:
`ArgumentType.String`
"""
self._post_event(1, failure_message)
class ZriverCommandCallbackV1Global(Global):
interface = ZriverCommandCallbackV1
ZriverCommandCallbackV1._gen_c()
ZriverCommandCallbackV1.proxy_class = ZriverCommandCallbackV1Proxy
ZriverCommandCallbackV1.resource_class = ZriverCommandCallbackV1Resource
ZriverCommandCallbackV1.global_class = ZriverCommandCallbackV1Global

View File

@@ -1,111 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright 2020 The River Developers
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from ..wayland import WlSeat
from .zriver_command_callback_v1 import ZriverCommandCallbackV1
class ZriverControlV1(Interface):
"""Run compositor commands
This interface allows clients to run compositor commands and receive a
success/failure response with output or a failure message respectively.
Each command is built up in a series of add_argument requests and executed
with a run_command request. The first argument is the command to be run.
A complete list of commands should be made available in the man page of the
compositor.
"""
name = "zriver_control_v1"
version = 1
class ZriverControlV1Proxy(Proxy[ZriverControlV1]):
interface = ZriverControlV1
@ZriverControlV1.request()
def destroy(self) -> None:
"""Destroy the river_control object
This request indicates that the client will not use the river_control
object any more. Objects that have been created through this instance
are not affected.
"""
self._marshal(0)
self._destroy()
@ZriverControlV1.request(
Argument(ArgumentType.String),
)
def add_argument(self, argument: str) -> None:
"""Add an argument to the current command
Arguments are stored by the server in the order they were sent until
the run_command request is made.
:param argument:
the argument to add
:type argument:
`ArgumentType.String`
"""
self._marshal(1, argument)
@ZriverControlV1.request(
Argument(ArgumentType.Object, interface=WlSeat),
Argument(ArgumentType.NewId, interface=ZriverCommandCallbackV1),
)
def run_command(self, seat: WlSeat) -> Proxy[ZriverCommandCallbackV1]:
"""Run the current command
Execute the command built up using the add_argument request for the
given seat.
:param seat:
:type seat:
:class:`~pywayland.protocol.wayland.WlSeat`
:returns:
:class:`~pywayland.protocol.river_control_unstable_v1.ZriverCommandCallbackV1`
-- callback object
"""
callback = self._marshal_constructor(2, ZriverCommandCallbackV1, seat)
return callback
class ZriverControlV1Resource(Resource):
interface = ZriverControlV1
class ZriverControlV1Global(Global):
interface = ZriverControlV1
ZriverControlV1._gen_c()
ZriverControlV1.proxy_class = ZriverControlV1Proxy
ZriverControlV1.resource_class = ZriverControlV1Resource
ZriverControlV1.global_class = ZriverControlV1Global

View File

@@ -1,19 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright 2020 The River Developers
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from .zriver_output_status_v1 import ZriverOutputStatusV1 # noqa: F401
from .zriver_seat_status_v1 import ZriverSeatStatusV1 # noqa: F401
from .zriver_status_manager_v1 import ZriverStatusManagerV1 # noqa: F401

View File

@@ -1,140 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright 2020 The River Developers
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class ZriverOutputStatusV1(Interface):
"""Track output tags and focus
This interface allows clients to receive information about the current
windowing state of an output.
"""
name = "zriver_output_status_v1"
version = 4
class ZriverOutputStatusV1Proxy(Proxy[ZriverOutputStatusV1]):
interface = ZriverOutputStatusV1
@ZriverOutputStatusV1.request()
def destroy(self) -> None:
"""Destroy the river_output_status object
This request indicates that the client will not use the
river_output_status object any more.
"""
self._marshal(0)
self._destroy()
class ZriverOutputStatusV1Resource(Resource):
interface = ZriverOutputStatusV1
@ZriverOutputStatusV1.event(
Argument(ArgumentType.Uint),
)
def focused_tags(self, tags: int) -> None:
"""Focused tags of the output
Sent once binding the interface and again whenever the tag focus of the
output changes.
:param tags:
32-bit bitfield
:type tags:
`ArgumentType.Uint`
"""
self._post_event(0, tags)
@ZriverOutputStatusV1.event(
Argument(ArgumentType.Array),
)
def view_tags(self, tags: list) -> None:
"""Tag state of an output's views
Sent once on binding the interface and again whenever the tag state of
the output changes.
:param tags:
array of 32-bit bitfields
:type tags:
`ArgumentType.Array`
"""
self._post_event(1, tags)
@ZriverOutputStatusV1.event(
Argument(ArgumentType.Uint),
version=2,
)
def urgent_tags(self, tags: int) -> None:
"""Tags of the output with an urgent view
Sent once on binding the interface and again whenever the set of tags
with at least one urgent view changes.
:param tags:
32-bit bitfield
:type tags:
`ArgumentType.Uint`
"""
self._post_event(2, tags)
@ZriverOutputStatusV1.event(
Argument(ArgumentType.String),
version=4,
)
def layout_name(self, name: str) -> None:
"""Name of the layout
Sent once on binding the interface should a layout name exist and again
whenever the name changes.
:param name:
layout name
:type name:
`ArgumentType.String`
"""
self._post_event(3, name)
@ZriverOutputStatusV1.event(version=4)
def layout_name_clear(self) -> None:
"""Name of the layout
Sent when the current layout name has been removed without a new one
being set, for example when the active layout generator disconnects.
"""
self._post_event(4)
class ZriverOutputStatusV1Global(Global):
interface = ZriverOutputStatusV1
ZriverOutputStatusV1._gen_c()
ZriverOutputStatusV1.proxy_class = ZriverOutputStatusV1Proxy
ZriverOutputStatusV1.resource_class = ZriverOutputStatusV1Resource
ZriverOutputStatusV1.global_class = ZriverOutputStatusV1Global

View File

@@ -1,131 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright 2020 The River Developers
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from pywayland.protocol.wayland import WlOutput
class ZriverSeatStatusV1(Interface):
"""Track seat focus
This interface allows clients to receive information about the current
focus of a seat. Note that (un)focused_output events will only be sent if
the client has bound the relevant
:class:`~pywayland.protocol.wayland.WlOutput` globals.
"""
name = "zriver_seat_status_v1"
version = 3
class ZriverSeatStatusV1Proxy(Proxy[ZriverSeatStatusV1]):
interface = ZriverSeatStatusV1
@ZriverSeatStatusV1.request()
def destroy(self) -> None:
"""Destroy the river_seat_status object
This request indicates that the client will not use the
river_seat_status object any more.
"""
self._marshal(0)
self._destroy()
class ZriverSeatStatusV1Resource(Resource):
interface = ZriverSeatStatusV1
@ZriverSeatStatusV1.event(
Argument(ArgumentType.Object, interface=WlOutput),
)
def focused_output(self, output: WlOutput) -> None:
"""The seat focused an output
Sent on binding the interface and again whenever an output gains focus.
:param output:
:type output:
:class:`~pywayland.protocol.wayland.WlOutput`
"""
self._post_event(0, output)
@ZriverSeatStatusV1.event(
Argument(ArgumentType.Object, interface=WlOutput),
)
def unfocused_output(self, output: WlOutput) -> None:
"""The seat unfocused an output
Sent whenever an output loses focus.
:param output:
:type output:
:class:`~pywayland.protocol.wayland.WlOutput`
"""
self._post_event(1, output)
@ZriverSeatStatusV1.event(
Argument(ArgumentType.String),
)
def focused_view(self, title: str) -> None:
"""Information on the focused view
Sent once on binding the interface and again whenever the focused view
or a property thereof changes. The title may be an empty string if no
view is focused or the focused view did not set a title.
:param title:
title of the focused view
:type title:
`ArgumentType.String`
"""
self._post_event(2, title)
@ZriverSeatStatusV1.event(
Argument(ArgumentType.String),
version=3,
)
def mode(self, name: str) -> None:
"""The active mode changed
Sent once on binding the interface and again whenever a new mode is
entered (e.g. with riverctl enter-mode foobar).
:param name:
name of the mode
:type name:
`ArgumentType.String`
"""
self._post_event(3, name)
class ZriverSeatStatusV1Global(Global):
interface = ZriverSeatStatusV1
ZriverSeatStatusV1._gen_c()
ZriverSeatStatusV1.proxy_class = ZriverSeatStatusV1Proxy
ZriverSeatStatusV1.resource_class = ZriverSeatStatusV1Resource
ZriverSeatStatusV1.global_class = ZriverSeatStatusV1Global

View File

@@ -1,109 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright 2020 The River Developers
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from pywayland.protocol.wayland import WlOutput
from pywayland.protocol.wayland import WlSeat
from .zriver_output_status_v1 import ZriverOutputStatusV1
from .zriver_seat_status_v1 import ZriverSeatStatusV1
class ZriverStatusManagerV1(Interface):
"""Manage river status objects
A global factory for objects that receive status information specific to
river. It could be used to implement, for example, a status bar.
"""
name = "zriver_status_manager_v1"
version = 4
class ZriverStatusManagerV1Proxy(Proxy[ZriverStatusManagerV1]):
interface = ZriverStatusManagerV1
@ZriverStatusManagerV1.request()
def destroy(self) -> None:
"""Destroy the river_status_manager object
This request indicates that the client will not use the
river_status_manager object any more. Objects that have been created
through this instance are not affected.
"""
self._marshal(0)
self._destroy()
@ZriverStatusManagerV1.request(
Argument(ArgumentType.NewId, interface=ZriverOutputStatusV1),
Argument(ArgumentType.Object, interface=WlOutput),
)
def get_river_output_status(self, output: WlOutput) -> Proxy[ZriverOutputStatusV1]:
"""Create an output status object
This creates a new river_output_status object for the given
:class:`~pywayland.protocol.wayland.WlOutput`.
:param output:
:type output:
:class:`~pywayland.protocol.wayland.WlOutput`
:returns:
:class:`~pywayland.protocol.river_status_unstable_v1.ZriverOutputStatusV1`
"""
id = self._marshal_constructor(1, ZriverOutputStatusV1, output)
return id
@ZriverStatusManagerV1.request(
Argument(ArgumentType.NewId, interface=ZriverSeatStatusV1),
Argument(ArgumentType.Object, interface=WlSeat),
)
def get_river_seat_status(self, seat: WlSeat) -> Proxy[ZriverSeatStatusV1]:
"""Create a seat status object
This creates a new river_seat_status object for the given
:class:`~pywayland.protocol.wayland.WlSeat`.
:param seat:
:type seat:
:class:`~pywayland.protocol.wayland.WlSeat`
:returns:
:class:`~pywayland.protocol.river_status_unstable_v1.ZriverSeatStatusV1`
"""
id = self._marshal_constructor(2, ZriverSeatStatusV1, seat)
return id
class ZriverStatusManagerV1Resource(Resource):
interface = ZriverStatusManagerV1
class ZriverStatusManagerV1Global(Global):
interface = ZriverStatusManagerV1
ZriverStatusManagerV1._gen_c()
ZriverStatusManagerV1.proxy_class = ZriverStatusManagerV1Proxy
ZriverStatusManagerV1.resource_class = ZriverStatusManagerV1Resource
ZriverStatusManagerV1.global_class = ZriverStatusManagerV1Global

View File

@@ -1,85 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="river_control_unstable_v1">
<copyright>
Copyright 2020 The River Developers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
</copyright>
<interface name="zriver_control_v1" version="1">
<description summary="run compositor commands">
This interface allows clients to run compositor commands and receive a
success/failure response with output or a failure message respectively.
Each command is built up in a series of add_argument requests and
executed with a run_command request. The first argument is the command
to be run.
A complete list of commands should be made available in the man page of
the compositor.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the river_control object">
This request indicates that the client will not use the
river_control object any more. Objects that have been created
through this instance are not affected.
</description>
</request>
<request name="add_argument">
<description summary="add an argument to the current command">
Arguments are stored by the server in the order they were sent until
the run_command request is made.
</description>
<arg name="argument" type="string" summary="the argument to add"/>
</request>
<request name="run_command">
<description summary="run the current command">
Execute the command built up using the add_argument request for the
given seat.
</description>
<arg name="seat" type="object" interface="wl_seat"/>
<arg name="callback" type="new_id" interface="zriver_command_callback_v1"
summary="callback object"/>
</request>
</interface>
<interface name="zriver_command_callback_v1" version="1">
<description summary="callback object">
This object is created by the run_command request. Exactly one of the
success or failure events will be sent. This object will be destroyed
by the compositor after one of the events is sent.
</description>
<event name="success" type="destructor">
<description summary="command successful">
Sent when the command has been successfully received and executed by
the compositor. Some commands may produce output, in which case the
output argument will be a non-empty string.
</description>
<arg name="output" type="string" summary="the output of the command"/>
</event>
<event name="failure" type="destructor">
<description summary="command failed">
Sent when the command could not be carried out. This could be due to
sending a non-existent command, no command, not enough arguments, too
many arguments, invalid arguments, etc.
</description>
<arg name="failure_message" type="string"
summary="a message explaining why failure occurred"/>
</event>
</interface>
</protocol>

View File

@@ -1,148 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="river_status_unstable_v1">
<copyright>
Copyright 2020 The River Developers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
</copyright>
<interface name="zriver_status_manager_v1" version="4">
<description summary="manage river status objects">
A global factory for objects that receive status information specific
to river. It could be used to implement, for example, a status bar.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the river_status_manager object">
This request indicates that the client will not use the
river_status_manager object any more. Objects that have been created
through this instance are not affected.
</description>
</request>
<request name="get_river_output_status">
<description summary="create an output status object">
This creates a new river_output_status object for the given wl_output.
</description>
<arg name="id" type="new_id" interface="zriver_output_status_v1"/>
<arg name="output" type="object" interface="wl_output"/>
</request>
<request name="get_river_seat_status">
<description summary="create a seat status object">
This creates a new river_seat_status object for the given wl_seat.
</description>
<arg name="id" type="new_id" interface="zriver_seat_status_v1"/>
<arg name="seat" type="object" interface="wl_seat"/>
</request>
</interface>
<interface name="zriver_output_status_v1" version="4">
<description summary="track output tags and focus">
This interface allows clients to receive information about the current
windowing state of an output.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the river_output_status object">
This request indicates that the client will not use the
river_output_status object any more.
</description>
</request>
<event name="focused_tags">
<description summary="focused tags of the output">
Sent once binding the interface and again whenever the tag focus of
the output changes.
</description>
<arg name="tags" type="uint" summary="32-bit bitfield"/>
</event>
<event name="view_tags">
<description summary="tag state of an output's views">
Sent once on binding the interface and again whenever the tag state
of the output changes.
</description>
<arg name="tags" type="array" summary="array of 32-bit bitfields"/>
</event>
<event name="urgent_tags" since="2">
<description summary="tags of the output with an urgent view">
Sent once on binding the interface and again whenever the set of
tags with at least one urgent view changes.
</description>
<arg name="tags" type="uint" summary="32-bit bitfield"/>
</event>
<event name="layout_name" since="4">
<description summary="name of the layout">
Sent once on binding the interface should a layout name exist and again
whenever the name changes.
</description>
<arg name="name" type="string" summary="layout name"/>
</event>
<event name="layout_name_clear" since="4">
<description summary="name of the layout">
Sent when the current layout name has been removed without a new one
being set, for example when the active layout generator disconnects.
</description>
</event>
</interface>
<interface name="zriver_seat_status_v1" version="3">
<description summary="track seat focus">
This interface allows clients to receive information about the current
focus of a seat. Note that (un)focused_output events will only be sent
if the client has bound the relevant wl_output globals.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the river_seat_status object">
This request indicates that the client will not use the
river_seat_status object any more.
</description>
</request>
<event name="focused_output">
<description summary="the seat focused an output">
Sent on binding the interface and again whenever an output gains focus.
</description>
<arg name="output" type="object" interface="wl_output"/>
</event>
<event name="unfocused_output">
<description summary="the seat unfocused an output">
Sent whenever an output loses focus.
</description>
<arg name="output" type="object" interface="wl_output"/>
</event>
<event name="focused_view">
<description summary="information on the focused view">
Sent once on binding the interface and again whenever the focused
view or a property thereof changes. The title may be an empty string
if no view is focused or the focused view did not set a title.
</description>
<arg name="title" type="string" summary="title of the focused view"/>
</event>
<event name="mode" since="3">
<description summary="the active mode changed">
Sent once on binding the interface and again whenever a new mode
is entered (e.g. with riverctl enter-mode foobar).
</description>
<arg name="name" type="string" summary="name of the mode"/>
</event>
</interface>
</protocol>

View File

@@ -1,288 +0,0 @@
import os
import threading
import time
from loguru import logger
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any, Set
from fabric.core.service import Service, Signal, Property
from fabric.utils.helpers import idle_add
# Import pywayland components - ensure these imports are correct
from pywayland.client import Display
from pywayland.protocol.wayland import WlOutput, WlRegistry, WlSeat
from .generated.river_status_unstable_v1 import ZriverStatusManagerV1
@dataclass
class OutputInfo:
"""Information about a River output"""
name: int
output: WlOutput
status: Any = None # ZriverOutputStatusV1
tags_view: List[int] = field(default_factory=list)
tags_focused: List[int] = field(default_factory=list)
@dataclass(frozen=True)
class RiverEvent:
"""Event data from River compositor"""
name: str
data: List[Any]
output_id: Optional[int] = None
class River(Service):
"""Connection to River Wayland compositor via river-status protocol"""
@Property(bool, "readable", "is-ready", default_value=False)
def ready(self) -> bool:
return self._ready
@Property(str, "readable", "active-window", default_value="")
def active_window(self) -> str:
"""Get the title of the currently active window"""
return self._active_window_title
@Signal
def ready(self):
return self.notify("ready")
@Signal("event", flags="detailed")
def event(self, event: object): ...
def __init__(self, **kwargs):
"""Initialize the River service"""
super().__init__(**kwargs)
self._ready = False
self._active_window_title = ""
self.outputs: Dict[int, OutputInfo] = {}
self.river_status_mgr = None
self.seat = None
self.seat_status = None
# Start the connection in a separate thread
self.river_thread = threading.Thread(
target=self._river_connection_task, daemon=True, name="river-status-service"
)
self.river_thread.start()
def _river_connection_task(self):
"""Main thread that connects to River and listens for events"""
try:
# Create a new display connection - THIS IS WHERE THE ERROR OCCURS
logger.info("[RiverService] Starting connection to River")
# Let's add some more diagnostic info to help troubleshoot
logger.debug(
f"[RiverService] XDG_RUNTIME_DIR={os.environ.get('XDG_RUNTIME_DIR', 'Not set')}"
)
logger.debug(
f"[RiverService] WAYLAND_DISPLAY={os.environ.get('WAYLAND_DISPLAY', 'Not set')}"
)
# Create the display connection
# with Display() as display:
# registry = display.get_registry()
# logger.debug("[RiverService] Registry obtained")
# Discover globals
display = Display("wayland-1")
display.connect()
logger.debug("[RiverService] Display connection created")
# Get the registry
registry = display.get_registry()
logger.debug("[RiverService] Registry obtained")
# Create state object to hold our data
state = {
"display": display,
"registry": registry,
"outputs": {},
"river_status_mgr": None,
"seat": None,
"seat_status": None,
}
# Set up registry handlers - using more direct approach like your example
def handle_global(registry, name, iface, version):
logger.debug(
f"[RiverService] Global: {iface} (v{version}, name={name})"
)
if iface == "zriver_status_manager_v1":
state["river_status_mgr"] = registry.bind(
name, ZriverStatusManagerV1, version
)
logger.info("[RiverService] Found river status manager")
elif iface == "wl_output":
output = registry.bind(name, WlOutput, version)
state["outputs"][name] = OutputInfo(name=name, output=output)
logger.info(f"[RiverService] Found output {name}")
elif iface == "wl_seat":
state["seat"] = registry.bind(name, WlSeat, version)
logger.info("[RiverService] Found seat")
def handle_global_remove(registry, name):
if name in state["outputs"]:
logger.info(f"[RiverService] Output {name} removed")
del state["outputs"][name]
idle_add(
lambda: self.emit(
"event::output_removed",
RiverEvent("output_removed", [name]),
)
)
# Set up the dispatchers
registry.dispatcher["global"] = handle_global
registry.dispatcher["global_remove"] = handle_global_remove
# Discover globals
logger.debug("[RiverService] Performing initial roundtrip")
display.roundtrip()
# Check if we found the river status manager
if not state["river_status_mgr"]:
logger.error("[RiverService] River status manager not found")
return
# Handle the window title updates through seat status
def focused_view_handler(_, title):
logger.debug(f"[RiverService] Focused view title: {title}")
self._active_window_title = title
idle_add(lambda: self._emit_active_window(title))
# Get the seat status to track active window
if state["seat"]:
seat_status = state["river_status_mgr"].get_river_seat_status(
state["seat"]
)
seat_status.dispatcher["focused_view"] = focused_view_handler
state["seat_status"] = seat_status
logger.info("[RiverService] Set up seat status for window tracking")
# Create view tags and focused tags handlers
def make_view_tags_handler(output_id):
def handler(_, tags):
decoded = self._decode_bitfields(tags)
state["outputs"][output_id].tags_view = decoded
logger.debug(
f"[RiverService] Output {output_id} view tags: {decoded}"
)
idle_add(lambda: self._emit_view_tags(output_id, decoded))
return handler
def make_focused_tags_handler(output_id):
def handler(_, tags):
decoded = self._decode_bitfields(tags)
state["outputs"][output_id].tags_focused = decoded
logger.debug(
f"[RiverService] Output {output_id} focused tags: {decoded}"
)
idle_add(lambda: self._emit_focused_tags(output_id, decoded))
return handler
# Bind output status listeners
for name, info in list(state["outputs"].items()):
status = state["river_status_mgr"].get_river_output_status(info.output)
status.dispatcher["view_tags"] = make_view_tags_handler(name)
status.dispatcher["focused_tags"] = make_focused_tags_handler(name)
info.status = status
logger.info(f"[RiverService] Set up status for output {name}")
# Initial data fetch
logger.debug("[RiverService] Performing second roundtrip")
display.roundtrip()
# Update our outputs dictionary
self.outputs.update(state["outputs"])
self.river_status_mgr = state["river_status_mgr"]
self.seat = state["seat"]
self.seat_status = state.get("seat_status")
# Mark service as ready
idle_add(self._set_ready)
# Main event loop
logger.info("[RiverService] Entering main event loop")
while True:
display.dispatch(block=True)
time.sleep(0.01) # Small sleep to prevent CPU spinning
except Exception as e:
logger.error(f"[RiverService] Error in River connection: {e}")
import traceback
logger.error(traceback.format_exc())
def _set_ready(self):
"""Set the service as ready (called on main thread via idle_add)"""
self._ready = True
logger.info("[RiverService] Service ready")
self.ready.emit()
return False # Don't repeat
def _emit_view_tags(self, output_id, tags):
"""Emit view_tags events (called on main thread)"""
event = RiverEvent("view_tags", tags, output_id)
self.emit("event::view_tags", event)
self.emit(f"event::view_tags::{output_id}", tags)
return False # Don't repeat
def _emit_focused_tags(self, output_id, tags):
"""Emit focused_tags events (called on main thread)"""
event = RiverEvent("focused_tags", tags, output_id)
self.emit("event::focused_tags", event)
self.emit(f"event::focused_tags::{output_id}", tags)
return False # Don't repeat
def _emit_active_window(self, title):
"""Emit active window title events (called on main thread)"""
event = RiverEvent("active_window", [title])
self.emit("event::active_window", event)
self.notify("active-window")
return False # Don't repeat
@staticmethod
def _decode_bitfields(bitfields) -> List[int]:
"""Decode River's tag bitfields into a list of tag indices"""
tags: Set[int] = set()
# Ensure we have an iterable
if not hasattr(bitfields, "__iter__"):
bitfields = [bitfields]
for bits in bitfields:
for i in range(32):
if bits & (1 << i):
tags.add(i)
return sorted(tags)
def run_command(self, command, *args):
"""Run a riverctl command"""
import subprocess
cmd = ["riverctl", command] + [str(arg) for arg in args]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
logger.info(f"[RiverService] Ran command: {' '.join(cmd)}")
return result.stdout.strip()
except subprocess.CalledProcessError as e:
logger.error(
f"[RiverService] Command failed: {' '.join(cmd)}, error: {e.stderr}"
)
return None
def toggle_focused_tag(self, tag):
"""Toggle a tag in the focused tags"""
tag_mask = 1 << int(tag)
self.run_command("set-focused-tags", str(tag_mask))

View File

@@ -1,231 +0,0 @@
from loguru import logger
from fabric.core.service import Property
from fabric.widgets.button import Button
from fabric.widgets.box import Box
from fabric.widgets.eventbox import EventBox
from fabric.widgets.label import Label
from fabric.utils.helpers import bulk_connect
from .service import River
from gi.repository import Gdk
_connection: River | None = None
def get_river_connection() -> River:
global _connection
if not _connection:
_connection = River()
return _connection
class RiverWorkspaceButton(Button):
@Property(int, "readable")
def id(self) -> int:
return self._id
@Property(bool, "read-write", default_value=False)
def active(self) -> bool:
return self._active
@active.setter
def active(self, value: bool):
self._active = value
(self.remove_style_class if not value else self.add_style_class)("active")
@Property(bool, "read-write", default_value=False)
def empty(self) -> bool:
return self._empty
@empty.setter
def empty(self, value: bool):
self._empty = value
(self.remove_style_class if not value else self.add_style_class)("empty")
def __init__(self, id: int, label: str = None, **kwargs):
super().__init__(label or str(id), **kwargs)
self._id = id
self._active = False
self._empty = True
class RiverWorkspaces(EventBox):
def __init__(self, output_id=None, max_tags=9, **kwargs):
super().__init__(events="scroll")
self.service = get_river_connection()
self._box = Box(**kwargs)
self.children = self._box
# Store output_id as received
self.output_id = output_id
self.max_tags = max_tags
# Create buttons for tags 0 to max_tags-1 (to match River's 0-based tag indexing)
self._buttons = {i: RiverWorkspaceButton(i) for i in range(max_tags)}
for btn in self._buttons.values():
btn.connect("clicked", self.on_workspace_click)
self._box.add(btn)
# Connect to service events
self.service.connect("event::focused_tags", self.on_focus_change_general)
self.service.connect("event::view_tags", self.on_view_change_general)
self.service.connect("event::output_removed", self.on_output_removed)
# Initial setup when service is ready
if self.service.ready:
self.on_ready(None)
else:
self.service.connect("event::ready", self.on_ready)
self.connect("scroll-event", self.on_scroll)
def on_ready(self, _):
"""Initialize widget state when service is ready"""
logger.debug(
f"[RiverWorkspaces] Service ready, outputs: {list(self.service.outputs.keys())}"
)
# If no output_id was specified, take the first one
if self.output_id is None and self.service.outputs:
self.output_id = next(iter(self.service.outputs.keys()))
logger.info(f"[RiverWorkspaces] Selected output {self.output_id}")
# Initialize state from selected output
if self.output_id is not None and self.output_id in self.service.outputs:
output_info = self.service.outputs[self.output_id]
# Initialize buttons with current state
# Access fields directly on the OutputInfo dataclass
focused_tags = output_info.tags_focused
view_tags = output_info.tags_view
logger.debug(
f"[RiverWorkspaces] Initial state - focused: {focused_tags}, view: {view_tags}"
)
for i, btn in self._buttons.items():
btn.active = i in focused_tags
btn.empty = i not in view_tags
def on_focus_change(self, _, tags):
"""Handle focused tags change for our specific output"""
logger.debug(
f"[RiverWorkspaces] Focus change on output {self.output_id}: {tags}"
)
for i, btn in self._buttons.items():
btn.active = i in tags
def on_view_change(self, _, tags):
"""Handle view tags change for our specific output"""
logger.debug(
f"[RiverWorkspaces] View change on output {self.output_id}: {tags}"
)
for i, btn in self._buttons.items():
btn.empty = i not in tags
def on_focus_change_general(self, _, event):
"""Handle general focused tags event"""
# Only handle event if it's for our output
if event.output_id == self.output_id:
logger.debug(
f"[RiverWorkspaces] General focus change for output {self.output_id}"
)
self.on_focus_change(_, event.data)
def on_view_change_general(self, _, event):
"""Handle general view tags event"""
# Only handle event if it's for our output
if event.output_id == self.output_id:
logger.debug(
f"[RiverWorkspaces] General view change for output {self.output_id}"
)
self.on_view_change(_, event.data)
def on_output_removed(self, _, event):
"""Handle output removal"""
removed_id = event.data[0]
if removed_id == self.output_id:
logger.info(f"[RiverWorkspaces] Our output {self.output_id} was removed")
# Try to find another output
if self.service.outputs:
self.output_id = next(iter(self.service.outputs.keys()))
logger.info(f"[RiverWorkspaces] Switching to output {self.output_id}")
# Update state for new output
if self.output_id in self.service.outputs:
output_info = self.service.outputs[self.output_id]
# Access fields directly on the OutputInfo dataclass
focused_tags = output_info.tags_focused
view_tags = output_info.tags_view
for i, btn in self._buttons.items():
btn.active = i in focused_tags
btn.empty = i not in view_tags
def on_workspace_click(self, btn):
"""Handle workspace button click"""
logger.info(f"[RiverWorkspaces] Clicked on workspace {btn.id}")
self.service.toggle_focused_tag(btn.id)
def on_scroll(self, _, event):
"""Handle scroll events"""
direction = event.direction
if direction == Gdk.ScrollDirection.DOWN:
logger.info("[RiverWorkspaces] Scroll down - focusing next view")
self.service.run_command("focus-view", "next")
elif direction == Gdk.ScrollDirection.UP:
logger.info("[RiverWorkspaces] Scroll up - focusing previous view")
self.service.run_command("focus-view", "previous")
class RiverActiveWindow(Label):
"""Widget to display the currently active window's title"""
def __init__(self, max_length=None, ellipsize="end", **kwargs):
super().__init__(**kwargs)
self.service = get_river_connection()
self.max_length = max_length
self.ellipsize = ellipsize
# Set initial state
if self.service.ready:
self.on_ready(None)
else:
self.service.connect("event::ready", self.on_ready)
# Connect to active window changes
self.service.connect("event::active_window", self.on_active_window_changed)
def on_ready(self, _):
"""Initialize widget when service is ready"""
logger.debug("[RiverActiveWindow] Service ready")
self.update_title(self.service.active_window)
def on_active_window_changed(self, _, event):
"""Update widget when active window changes"""
title = event.data[0] if event.data else ""
logger.debug(f"[RiverActiveWindow] Window changed to: {title}")
self.update_title(title)
def update_title(self, title):
"""Update the label with the window title"""
if not title:
self.label = ""
self.set_label(self.label)
return
if self.max_length and len(title) > self.max_length:
if self.ellipsize == "end":
title = title[: self.max_length] + "..."
elif self.ellipsize == "middle":
half = (self.max_length - 3) // 2
title = title[:half] + "..." + title[-half:]
elif self.ellipsize == "start":
title = "..." + title[-self.max_length :]
self.label = title
self.set_label(self.label)

View File

@@ -1,122 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Callable
from pywayland.client import Display
from pywayland.protocol.wayland import WlOutput, WlRegistry, WlSeat
from generated.river_status_unstable_v1 import (
ZriverStatusManagerV1,
ZriverOutputStatusV1,
)
@dataclass
class OutputInfo:
name: int
output: WlOutput
status: ZriverOutputStatusV1
tags_view: list[int] = field(default_factory=list)
tags_focused: list[int] = field(default_factory=list)
@dataclass
class State:
display: Display
registry: WlRegistry
outputs: dict[int, OutputInfo] = field(default_factory=dict)
river_status_mgr: ZriverStatusManagerV1 | None = None
seat: WlSeat | None = None
seat_status: ZriverSeatStatusV1 | None = None
def decode_bitfields(bitfields: list[int] | int) -> list[int]:
tags = set()
if isinstance(bitfields, int):
bitfields = [bitfields]
for bits in bitfields:
for i in range(32):
if bits & (1 << i):
tags.add(i)
return sorted(tags)
def handle_global(
state: State, registry: WlRegistry, name: int, iface: str, version: int
) -> None:
if iface == "zriver_status_manager_v1":
state.river_status_mgr = registry.bind(name, ZriverStatusManagerV1, version)
elif iface == "wl_output":
output = registry.bind(name, WlOutput, version)
state.outputs[name] = OutputInfo(name=name, output=output, status=None)
elif iface == "wl_seat":
seat = registry.bind(name, WlSeat, version)
state.seat = seat
def handle_global_remove(state: State, registry: WlRegistry, name: int) -> None:
if name in state.outputs:
print(f"Output {name} removed.")
del state.outputs[name]
def make_view_tags_handler(state: State, name: int) -> Callable:
def handler(self, tags: list[int]) -> None:
decoded = decode_bitfields(tags)
state.outputs[name].tags_view = decoded
print(f"[Output {name}] View tags: {decoded}")
return handler
def make_focused_tags_handler(state: State, name: int) -> Callable:
def handler(self, tags: int) -> None:
decoded = decode_bitfields(tags)
state.outputs[name].tags_focused = decoded
print(f"[Output {name}] Focused tags: {decoded}")
return handler
def main() -> None:
with Display() as display:
registry = display.get_registry()
state = State(display=display, registry=registry)
registry.dispatcher["global"] = lambda reg, name, iface, ver: handle_global(
state, reg, name, iface, ver
)
registry.dispatcher["global_remove"] = lambda reg, name: handle_global_remove(
state, reg, name
)
# Discover globals
display.roundtrip()
if not state.river_status_mgr:
print("❌ River status manager not found.")
return
# Bind output status listeners
for name, info in state.outputs.items():
status = state.river_status_mgr.get_river_output_status(info.output)
status.dispatcher["view_tags"] = make_view_tags_handler(state, name)
status.dispatcher["focused_tags"] = make_focused_tags_handler(state, name)
info.status = status
if state.seat:
state.seat_status = state.river_status_mgr.get_river_seat_status(state.seat)
print("✅ Bound seat status")
# Initial data
display.roundtrip()
print("🟢 Listening for tag changes. Press Ctrl+C to exit.")
while True:
display.roundtrip()
if __name__ == "__main__":
main()

View File

@@ -1,56 +0,0 @@
{
lib,
python3Packages,
gtk3,
gtk-layer-shell,
cairo,
gobject-introspection,
libdbusmenu-gtk3,
gdk-pixbuf,
gnome,
cinnamon,
wrapGAppsHook3,
...
}:
python3Packages.buildPythonApplication {
pname = "fabric-nix-example";
version = "0.0.1";
pyproject = true;
src = ./.;
nativeBuildInputs = [
wrapGAppsHook3
gtk3
gobject-introspection
cairo
];
# buildInputs = [
# libdbusmenu-gtk3
# gtk-layer-shell
# gnome.gnome-bluetooth
# cinnamon.cinnamon-desktop
# gdk-pixbuf
# ];
dependencies = with python3Packages; [
python-fabric
pywayland
];
doCheck = false;
dontWrapGApps = true;
preFixup = ''
makeWrapperArgs+=("''${gappsWrapperArgs[@]}")
'';
meta = {
changelog = "";
description = ''
Fabrix Bar Example
'';
homepage = "https://github.com/wholikeel/fabric";
license = lib.licenses.agpl3Only;
};
}

55
example-stylix-dev.yaml Normal file
View File

@@ -0,0 +1,55 @@
height: 42
dev: true
window_title:
enable: true
vinyl:
enable: true
battery:
enable: true
calendar:
enable: true
khal_path: "khal" # or full path like "/home/user/.nix-profile/bin/khal"
notmuch:
enable: true
notmuch_path: "notmuch" # or full path like "/home/user/.nix-profile/bin/notmuch"
emacsclient_command: "emacsclient" # or full path like "/home/user/.nix-profile/bin/emacsclient"
screenrec:
enable: true
output_dir: "~/Videos/wl-screenrec"
notifications:
enable: true
anchor: "top center"
margin: "8px"
width: 360
timeout_ms: 10000
history_size: 50
image_max_px: 128
center_width: 380
stylix:
enable: true
colors:
base00: "1e1e2e" # background
base01: "313244" # lighter background
base02: "45475a" # selection background
base03: "585b70" # comments
base04: "bac2de" # dark foreground
base05: "cdd6f4" # foreground
base06: "f5e0dc" # light foreground
base07: "b4befe" # light background
base08: "f38ba8" # red
base09: "fab387" # orange
base0A: "f9e2af" # yellow
base0B: "a6e3a1" # green
base0C: "94e2d5" # cyan
base0D: "89b4fa" # blue
base0E: "cba6f7" # purple
base0F: "f2cdcd" # brown
fonts:
sansSerif: "Inter"
serif: "Times New Roman"
monospace: "JetBrains Mono"
sizes:
desktop: 16
applications: 14
terminal: 16
popups: 14

7
example.yaml Normal file
View File

@@ -0,0 +1,7 @@
bar_height: 42
window_title:
enable: false
vinyl:
enable: true
battery:
enable: true

57
flake.lock generated
View File

@@ -6,47 +6,67 @@
"utils": "utils"
},
"locked": {
"lastModified": 1725442219,
"narHash": "sha256-xgTjqwlAgfY0Kv6G6CogOV2pN6U0wllRYteVAAZs7BU=",
"owner": "wholikeel",
"repo": "fabric-nix",
"rev": "3bc86cfb8c988ff5488526a47e1914f03a34a87c",
"lastModified": 1770146720,
"narHash": "sha256-YVlwsUz4SLj8qYAb21ernT3lDB/piU1V6hTW/UjikWA=",
"owner": "Fabric-Development",
"repo": "fabric",
"rev": "fd2aabbd7e1859aa7c11c626a6c36a937aca736a",
"type": "github"
},
"original": {
"owner": "wholikeel",
"repo": "fabric-nix",
"owner": "Fabric-Development",
"repo": "fabric",
"type": "github"
}
},
"home-manager": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1746369725,
"narHash": "sha256-m3ai7LLFYsymMK0uVywCceWfUhP0k3CALyFOfcJACqE=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "1a1793f6d940d22c6e49753548c5b6cb7dc5545d",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "home-manager",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1717179513,
"narHash": "sha256-vboIEwIQojofItm2xGCdZCzW96U85l9nDW3ifMuAIdM=",
"lastModified": 1733261153,
"narHash": "sha256-eq51hyiaIwtWo19fPEeE0Zr2s83DYMKJoukNLgGGpek=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "63dacb46bf939521bdc93981b4cbb7ecb58427a0",
"rev": "b681065d0919f7eb5309a93cea2cfa84dec9aa88",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "24.05",
"ref": "nixos-24.11",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1717179513,
"narHash": "sha256-vboIEwIQojofItm2xGCdZCzW96U85l9nDW3ifMuAIdM=",
"lastModified": 1731603435,
"narHash": "sha256-CqCX4JG7UiHvkrBTpYC3wcEurvbtTADLbo3Ns2CEoL8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "63dacb46bf939521bdc93981b4cbb7ecb58427a0",
"rev": "8b27c1239e5c421a2bbc2c65d52e4a6fbf2ff296",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "24.05",
"ref": "24.11",
"repo": "nixpkgs",
"type": "github"
}
@@ -54,6 +74,7 @@
"root": {
"inputs": {
"fabric": "fabric",
"home-manager": "home-manager",
"nixpkgs": "nixpkgs_2",
"unstable": "unstable",
"utils": "utils_2"
@@ -110,11 +131,11 @@
"systems": "systems"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {

245
flake.nix
View File

@@ -1,11 +1,11 @@
{
description = "Fabric Bar Example";
description = "sims status bar (companion to fenster WM).";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/24.05";
nixpkgs.url = "github:NixOS/nixpkgs/24.11";
unstable.url = "github:NixOS/nixpkgs/nixos-unstable";
utils.url = "github:numtide/flake-utils";
fabric.url = "github:wholikeel/fabric-nix";
fabric.url = "github:Fabric-Development/fabric";
home-manager.url = "github:nix-community/home-manager";
home-manager.inputs.nixpkgs.follows = "nixpkgs";
};
@@ -31,42 +31,255 @@
in
{
formatter = pkgs.nixfmt-rfc-style;
devShells.default = pkgs.callPackage ./shell.nix { inherit pkgs; };
packages.default = pkgs.callPackage ./derivation.nix { inherit (pkgs) lib python3Packages; };
devShells.default = pkgs.callPackage ./nix/shell.nix { inherit pkgs; };
packages = rec {
default = pkgs.callPackage ./nix/derivation.nix { inherit (pkgs) lib python3Packages; };
sims = default;
};
apps.default = {
type = "app";
program = "${self.packages.${system}.default}/bin/bar";
program = "${self.packages.${system}.default}/bin/sims";
};
}
)
// {
homeManagerModules.makku-bar =
homeManagerModules = {
sims =
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.sims;
settingsFormat = pkgs.formats.yaml { };
in
{
options.services.makku-bar = {
enable = lib.mkEnableOption "makku-bar status bar";
options.services.sims = {
enable = lib.mkEnableOption "sims status bar";
package = lib.mkOption {
type = lib.types.package;
default = pkgs.callPackage ./derivation.nix { inherit (pkgs) lib python3Packages; };
description = "The makku-bar package to use.";
default = self.packages.${pkgs.system}.default;
description = "The sims package to use.";
};
settings = lib.mkOption {
type = lib.types.submodule {
options = {
vinyl = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
};
};
battery = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
};
};
height = lib.mkOption {
type = lib.types.int;
default = 40;
description = "Height of the status bar in pixels";
};
logLevel = lib.mkOption {
type = lib.types.enum [ "TRACE" "DEBUG" "INFO" "SUCCESS" "WARNING" "ERROR" "CRITICAL" ];
default = "WARNING";
description = "Log level for the status bar (loguru levels: TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL)";
};
window_title = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether to show the window title in the center of the bar";
};
};
stylix = lib.mkOption {
type = lib.types.attrsOf lib.types.anything;
default = { enable = false; };
description = "Stylix configuration passed from the stylix module";
};
calendar = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether to enable the calendar widget";
};
khal_path = lib.mkOption {
type = lib.types.str;
default = "khal";
description = "Path to the khal binary";
};
};
notmuch = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether to enable the notmuch email widget";
};
notmuch_path = lib.mkOption {
type = lib.types.str;
default = "notmuch";
description = "Path to the notmuch binary";
};
emacsclient_command = lib.mkOption {
type = lib.types.str;
default = "emacsclient";
description = "Path to the emacsclient binary";
};
debt_query = lib.mkOption {
type = lib.types.str;
default = "tag:unread and date:..1w";
description = "notmuch query whose count drives the mail-debt severity color on the bar widget";
};
debt_warn_at = lib.mkOption {
type = lib.types.int;
default = 1;
description = "Debt count at which the widget switches to the warn (orange) color";
};
debt_alarm_at = lib.mkOption {
type = lib.types.int;
default = 6;
description = "Debt count at which the widget switches to the alarm (red) color";
};
saved_searches = lib.mkOption {
type = lib.types.listOf (lib.types.submodule {
options = {
name = lib.mkOption {
type = lib.types.str;
description = "Display label shown in the search launcher";
};
query = lib.mkOption {
type = lib.types.str;
description = "notmuch query to run when this saved search is activated";
};
};
});
default = [ ];
description = "Saved searches shown in the notmuch search launcher when the entry is empty";
};
};
screenrec = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to enable the screenrec widget and menu";
};
output_dir = lib.mkOption {
type = lib.types.str;
default = "~/Videos/wl-screenrec";
description = "Directory to save recordings into";
};
};
power = {
lock_command = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ "waylock" ];
description = "argv for the Lock action in the power menu";
};
};
notifications = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to enable the notification toast service. Owns org.freedesktop.Notifications, so other notification daemons (mako, dunst, swaync) must be disabled.";
};
anchor = lib.mkOption {
type = lib.types.str;
default = "top center";
description = "Layer-shell anchor for the toast stack";
};
margin = lib.mkOption {
type = lib.types.str;
default = "8px";
description = "Layer-shell margin for the toast stack";
};
width = lib.mkOption {
type = lib.types.int;
default = 360;
description = "Width of each notification toast in pixels";
};
timeout_ms = lib.mkOption {
type = lib.types.int;
default = 10000;
description = "Auto-close timeout for notifications in milliseconds";
};
history_size = lib.mkOption {
type = lib.types.int;
default = 50;
description = "How many past notifications the in-memory center keeps";
};
image_max_px = lib.mkOption {
type = lib.types.int;
default = 128;
description = "Max edge in pixels for stored notification thumbnails";
};
center_width = lib.mkOption {
type = lib.types.int;
default = 380;
description = "Width of the notification center side rail in pixels";
};
};
};
};
default = {
vinyl.enable = false;
battery.enable = false;
height = 40;
logLevel = "WARNING";
window_title.enable = true;
stylix.enable = false;
calendar = {
enable = true;
khal_path = "khal";
};
notmuch = {
enable = true;
notmuch_path = "notmuch";
emacsclient_command = "emacsclient";
debt_query = "tag:unread and date:..1w";
debt_warn_at = 1;
debt_alarm_at = 6;
saved_searches = [ ];
};
screenrec = {
enable = false;
output_dir = "~/Videos/wl-screenrec";
};
power = {
lock_command = [ "waylock" ];
};
notifications = {
enable = false;
anchor = "top center";
margin = "8px";
width = 360;
timeout_ms = 10000;
history_size = 50;
image_max_px = 128;
center_width = 380;
};
};
};
};
config = lib.mkIf config.services.makku-bar.enable {
systemd.user.services.makku-bar = {
config = lib.mkIf config.services.sims.enable {
systemd.user.services.sims =
let
configFile = settingsFormat.generate "config.yaml" cfg.settings;
in
{
Unit = {
Description = "Makku Status Bar";
Description = "sims status bar";
After = [ "graphical-session.target" ];
};
Service = {
ExecStart = "${config.services.makku-bar.package}/bin/bar";
ExecStart = "${config.services.sims.package}/bin/sims --config ${configFile}";
Restart = "on-failure";
};
@@ -76,5 +289,7 @@
};
};
};
stylix-sims = import ./nix/stylix/hm.nix;
};
};
}

97
nix/derivation.nix Normal file
View File

@@ -0,0 +1,97 @@
{
lib,
python3Packages,
gtk3,
gtk-layer-shell,
cairo,
gobject-introspection,
libdbusmenu-gtk3,
gdk-pixbuf,
gnome-bluetooth,
cinnamon-desktop,
wrapGAppsHook3,
playerctl,
webp-pixbuf-loader,
notmuch,
khal,
dbus,
...
}:
python3Packages.buildPythonApplication {
pname = "sims";
version = "0.0.1";
pyproject = true;
src = ../.;
nativeBuildInputs = [
wrapGAppsHook3
gtk3
gobject-introspection
python3Packages.pygobject3
cairo
playerctl
];
buildInputs = [
libdbusmenu-gtk3
gtk-layer-shell
gnome-bluetooth
cinnamon-desktop
gdk-pixbuf
playerctl
webp-pixbuf-loader
notmuch
khal
];
dependencies = with python3Packages; [
python-fabric
pywayland
pyyaml
platformdirs
];
doCheck = false;
dontWrapGApps = true;
installPhase = ''
runHook preInstall
mkdir -p $out/${python3Packages.python.sitePackages}
cp -r sims $out/${python3Packages.python.sitePackages}/
# If you have any scripts to install
mkdir -p $out/bin
cp scripts/launcher.py $out/bin/sims
chmod +x $out/bin/sims
cp scripts/cli_launcher.py $out/bin/sims-cli
chmod +x $out/bin/sims-cli
runHook postInstall
'';
preFixup = ''
makeWrapperArgs+=("''${gappsWrapperArgs[@]}")
makeWrapperArgs+=(--prefix PATH : ${
lib.makeBinPath [
khal
notmuch
dbus
]
})
'';
passthru = {
inherit khal notmuch;
};
meta = {
changelog = "";
description = ''
sims status bar (companion to fenster WM).
'';
homepage = "https://github.com/wholikeel/fabric";
license = lib.licenses.agpl3Only;
};
}

View File

@@ -22,11 +22,14 @@ pkgs.mkShell {
gobject-introspection
libdbusmenu-gtk3
gdk-pixbuf
gnome.gnome-bluetooth
cinnamon.cinnamon-desktop
librsvg
gnome-bluetooth
cinnamon-desktop
wayland-scanner
wayland
wayland-protocols
playerctl
(python3.withPackages (
ps: with ps; [
setuptools
@@ -39,7 +42,13 @@ pkgs.mkShell {
pylsp-mypy
pyls-isort
python-lsp-ruff
pyyaml
platformdirs
]
))
];
shellHook = ''
export GDK_PIXBUF_MODULE_FILE=${pkgs.librsvg}/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache
'';
}

44
nix/stylix/hm.nix Normal file
View File

@@ -0,0 +1,44 @@
{ config, lib, ... }:
let
cfg = config.stylix.targets.sims;
in
{
options.stylix.targets.sims.enable =
config.lib.stylix.mkEnableTarget "sims" true;
config = lib.mkIf (config.stylix.enable && cfg.enable) {
services.sims.settings.stylix = {
enable = true;
colors = {
base00 = config.lib.stylix.colors.base00; # background
base01 = config.lib.stylix.colors.base01; # lighter background
base02 = config.lib.stylix.colors.base02; # selection background
base03 = config.lib.stylix.colors.base03; # comments
base04 = config.lib.stylix.colors.base04; # dark foreground
base05 = config.lib.stylix.colors.base05; # foreground
base06 = config.lib.stylix.colors.base06; # light foreground
base07 = config.lib.stylix.colors.base07; # light background
base08 = config.lib.stylix.colors.base08; # red
base09 = config.lib.stylix.colors.base09; # orange
base0A = config.lib.stylix.colors.base0A; # yellow
base0B = config.lib.stylix.colors.base0B; # green
base0C = config.lib.stylix.colors.base0C; # cyan
base0D = config.lib.stylix.colors.base0D; # blue
base0E = config.lib.stylix.colors.base0E; # purple
base0F = config.lib.stylix.colors.base0F; # brown
};
fonts = {
serif = config.stylix.fonts.serif.name;
sansSerif = config.stylix.fonts.sansSerif.name;
monospace = config.stylix.fonts.monospace.name;
sizes = {
desktop = config.stylix.fonts.sizes.desktop;
applications = config.stylix.fonts.sizes.applications;
terminal = config.stylix.fonts.sizes.terminal;
popups = config.stylix.fonts.sizes.popups;
};
};
};
};
}

6
nix/stylix/meta.nix Normal file
View File

@@ -0,0 +1,6 @@
{ lib }:
{
name = "Makku Bar";
homepage = "https://github.com/Makesesama/makku-bar";
maintainers = [ ];
}

View File

@@ -3,22 +3,22 @@ requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "fabric-nix-example"
name = "sims"
version = "0.0.1"
requires-python = ">= 3.11"
authors = [
]
maintainers = [
]
description = "Fabric using Nix example."
description = "sims status bar (companion to fenster WM)."
readme = "README.md"
license = {file = "LICENSE"}
[project.scripts]
bar = "bar.bar:main"
[tool.setuptools]
include-package-data = true
[tool.setuptools.packages.find]
where = ["."]
[tool.setuptools.packages]
find = { namespaces = true }
[tool.setuptools.package-data]
bar = ["bar.css"]
"*" = ["*.css", "styles"]

20
scripts/cli_launcher.py Normal file
View File

@@ -0,0 +1,20 @@
#!/usr/bin/env python3
import os
import sys
script_dir = os.path.dirname(os.path.abspath(__file__))
site_packages_dir = os.path.join(
script_dir,
os.pardir,
"lib",
f"python{sys.version_info.major}.{sys.version_info.minor}",
"site-packages",
)
if site_packages_dir not in sys.path:
sys.path.insert(0, site_packages_dir)
from sims.cli import main
sys.argv[0] = os.path.join(script_dir, os.path.basename(__file__))
sys.exit(main())

21
scripts/launcher.py Executable file
View File

@@ -0,0 +1,21 @@
#!/usr/bin/env python3
import sys
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
site_packages_dir = os.path.join(
script_dir,
os.pardir,
"lib",
f"python{sys.version_info.major}.{sys.version_info.minor}",
"site-packages",
)
if site_packages_dir not in sys.path:
sys.path.insert(0, site_packages_dir)
from sims.main import *
sys.argv[0] = os.path.join(script_dir, os.path.basename(__file__))
sys.exit(main())

171
sims/cli.py Normal file
View File

@@ -0,0 +1,171 @@
"""sims-cli — talk to the running sims status bar over DBus."""
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
from dataclasses import dataclass
from typing import Callable
DEST = "org.Fabric.fabric.sims"
OBJ = "/org/Fabric/fabric"
IFACE = "org.Fabric.fabric"
def _dbus_send(*args: str) -> str:
proc = subprocess.run(
["dbus-send", "--session", "--print-reply", f"--dest={DEST}", OBJ, *args],
capture_output=True,
text=True,
)
if proc.returncode != 0:
sys.stderr.write(proc.stderr)
sys.exit(proc.returncode)
return proc.stdout
def invoke_action(action: str) -> None:
_dbus_send(f"{IFACE}.InvokeAction", f"string:{action}", "array:string:")
_ACTION_RE = re.compile(r'dict entry\(\s*string "([^"]+)"')
def list_actions() -> list[str]:
out = _dbus_send(
"org.freedesktop.DBus.Properties.Get",
f"string:{IFACE}",
"string:Actions",
)
return _ACTION_RE.findall(out)
@dataclass
class Command:
name: str
help: str
run: Callable[[argparse.Namespace], None]
def _action(name: str) -> Callable[[argparse.Namespace], None]:
return lambda _ns: invoke_action(name)
COMMANDS: list[Command] = [
Command("finder", "open window finder", _action("open-finder")),
Command("apps", "open application launcher", _action("open-app-launcher")),
Command("clipboard", "open clipboard history picker", _action("open-clipboard-menu")),
Command("power", "open power menu", _action("open-power-menu")),
Command("screenshot", "open screenshot menu", _action("open-screenshot-menu")),
Command("notmuch-refresh", "refresh unread mail count", _action("refresh-notmuch")),
]
def _cmd_screenrec(ns: argparse.Namespace) -> None:
mapping = {
"menu": "open-screenrec-menu",
"start-monitor": "screenrec-start-monitor",
"start-region": "screenrec-start-region",
"stop": "screenrec-stop",
}
invoke_action(mapping[ns.screenrec_cmd])
def _cmd_mail(ns: argparse.Namespace) -> None:
mapping = {
"search": "open-notmuch-search",
"refresh": "refresh-notmuch",
}
invoke_action(mapping[ns.mail_cmd])
def _cmd_corners(ns: argparse.Namespace) -> None:
mapping = {
"rounded": "set-bar-corners-rounded",
"flat": "set-bar-corners-flat",
"toggle": "toggle-bar-corners",
}
invoke_action(mapping[ns.corners_cmd])
def _cmd_list(ns: argparse.Namespace) -> None:
actions = list_actions()
if ns.json:
json.dump(actions, sys.stdout, indent=2)
sys.stdout.write("\n")
else:
for a in actions:
print(a)
def _cmd_invoke(ns: argparse.Namespace) -> None:
invoke_action(ns.action)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="sims-cli",
description="Talk to the running sims status bar over DBus.",
)
sub = parser.add_subparsers(dest="cmd", required=True, metavar="COMMAND")
for cmd in COMMANDS:
p = sub.add_parser(cmd.name, help=cmd.help)
p.set_defaults(func=cmd.run)
rec = sub.add_parser("screenrec", help="screen recording controls")
rec_sub = rec.add_subparsers(dest="screenrec_cmd", required=True, metavar="ACTION")
for sub_name, sub_help in [
("menu", "open screenrec menu (auto-detects state)"),
("start-monitor", "start recording the focused monitor"),
("start-region", "start recording a slurp-selected region"),
("stop", "stop active recording"),
]:
rec_sub.add_parser(sub_name, help=sub_help)
rec.set_defaults(func=_cmd_screenrec)
mail = sub.add_parser("mail", help="notmuch mail controls")
mail_sub = mail.add_subparsers(dest="mail_cmd", required=True, metavar="ACTION")
for sub_name, sub_help in [
("search", "open the live notmuch search launcher"),
("refresh", "refresh the bar's unread/debt counts"),
]:
mail_sub.add_parser(sub_name, help=sub_help)
mail.set_defaults(func=_cmd_mail)
corners = sub.add_parser("corners", help="bar bottom-corner rounding")
corners_sub = corners.add_subparsers(
dest="corners_cmd", required=True, metavar="STATE"
)
for sub_name, sub_help in [
("rounded", "round the bar's bottom corners"),
("flat", "remove rounding (current default look)"),
("toggle", "flip the current rounding state"),
]:
corners_sub.add_parser(sub_name, help=sub_help)
corners.set_defaults(func=_cmd_corners)
lst = sub.add_parser("list", help="list registered actions")
lst.add_argument("--json", action="store_true", help="emit JSON array")
lst.set_defaults(func=_cmd_list)
inv = sub.add_parser(
"invoke",
help="invoke a raw action by name (escape hatch for actions without a dedicated subcommand)",
)
inv.add_argument("action", help="dbus action name, e.g. open-finder")
inv.set_defaults(func=_cmd_invoke)
return parser
def main() -> None:
parser = build_parser()
ns = parser.parse_args()
ns.func(ns)
if __name__ == "__main__":
main()

78
sims/config.py Normal file
View File

@@ -0,0 +1,78 @@
import yaml
import os
from platformdirs import user_config_dir
import argparse
APP_NAME = "sims"
XDG_CONFIG_HOME = user_config_dir(appname=APP_NAME)
XDG_CONFIG_FILE = os.path.join(XDG_CONFIG_HOME, "config.yaml")
def load_config(config_path=XDG_CONFIG_FILE):
"""Loads configuration from a YAML file."""
if config_path is None:
print("No configuration file path provided or found.")
return None
try:
with open(config_path, "r") as f:
config = yaml.safe_load(f)
return config
except FileNotFoundError:
print(f"Error: Configuration file not found at {config_path}")
return None
except yaml.YAMLError as e:
print(f"Error parsing YAML file '{config_path}': {e}")
return None
except Exception as e:
print(f"An unexpected error occurred loading config file '{config_path}': {e}")
return None
def load_args():
parser = argparse.ArgumentParser(description="sims")
parser.add_argument(
"-c",
"--config",
help="Path to a custom configuration file.",
type=str,
)
args = parser.parse_args()
return args.config
app_config = load_config() if not load_args() else load_config(load_args())
if app_config is None:
raise Exception("Config file missing")
VINYL = app_config.get("vinyl", {"enable": False})
BATTERY = app_config.get("battery", {"enable": False})
WINDOW_TITLE = app_config.get("window_title", {"enable": True})
STYLIX = app_config.get("stylix", {"enable": False})
CALENDAR = app_config.get("calendar", {"enable": True, "khal_path": "khal"})
NOTMUCH = app_config.get("notmuch", {"enable": True, "notmuch_path": "notmuch", "emacsclient_command": "emacsclient", "saved_searches": []})
NOTMUCH.setdefault("saved_searches", [])
SCREENREC = app_config.get("screenrec", {
"enable": False,
"output_dir": "~/Videos/wl-screenrec",
})
POWER = app_config.get("power", {
"lock_command": ["waylock"],
})
NOTIFICATIONS = app_config.get("notifications", {
"enable": False,
"anchor": "top center",
"margin": "8px",
"width": 360,
"timeout_ms": 10_000,
"history_size": 50,
"image_max_px": 128,
"center_width": 380,
})
BAR_HEIGHT = app_config.get("height", 40)
LOG_LEVEL = app_config.get("logLevel", "WARNING")
DEV = app_config.get("dev", False)

244
sims/main.py Normal file
View File

@@ -0,0 +1,244 @@
from loguru import logger
# Configure logging based on dev flag
from .config import DEV, LOG_LEVEL
if DEV:
# In dev mode, disable fabric logs but keep stylix and bar logs
logger.disable("fabric")
else:
# In production, disable fabric logs but keep bar logs with configurable level
import sys
logger.disable("fabric")
logger.configure(handlers=[{"sink": sys.stderr, "level": LOG_LEVEL, "format": "{time} | {level} | {name}:{function}:{line} - {message}"}])
from fabric import Application
from sims.services.i3 import I3, I3MessageType
from fabric.system_tray.widgets import SystemTray
from fabric.widgets.wayland import WaylandWindow as Window
from fabric.utils import (
get_relative_path,
)
from .modules.bar import StatusBar
from .modules.window_fuzzy import FuzzyWindowFinder
from .modules.launcher.apps import AppLauncher
from .modules.launcher.clipboard import ClipboardMenu
from .modules.launcher.notmuch_search import NotmuchSearchMenu
from .modules.launcher.power import PowerMenu
from .modules.launcher.screenrec import ScreenrecMenu
from .modules.launcher.screenshot import ScreenshotMenu
from .modules.calendar import CalendarService
from .modules.control_center import ControlCenter
from .modules.notifications import NotificationToasts
from .modules.stylix import get_stylix_css_path
from .modules.vinyl import VinylButton
from .config import CALENDAR, NOTIFICATIONS, POWER, SCREENREC, STYLIX, VINYL
from .services.fenster import get_i3_connection
from .services.notification_history import NotificationHistoryService
from .services.screenrec import ScreenrecService
from fabric.notifications import Notifications
tray = SystemTray(name="system-tray", spacing=4)
get_i3_connection()
dummy = Window(visible=False)
finder = FuzzyWindowFinder()
app_launcher = AppLauncher()
clipboard_menu = ClipboardMenu()
power_menu = PowerMenu(lock_command=POWER.get("lock_command", ["waylock"]))
screenshot_menu = ScreenshotMenu()
notmuch_search_menu = NotmuchSearchMenu()
screenrec_service: ScreenrecService | None = None
screenrec_menu = None
if SCREENREC.get("enable", False):
screenrec_service = ScreenrecService(
output_dir=SCREENREC.get("output_dir", "~/Videos/wl-screenrec")
)
screenrec_menu = ScreenrecMenu(screenrec_service)
notifications_service: Notifications | None = None
notification_history: NotificationHistoryService | None = None
notification_toasts: NotificationToasts | None = None
if NOTIFICATIONS.get("enable", False):
notifications_service = Notifications()
notification_history = NotificationHistoryService(
notifications_service,
history_size=NOTIFICATIONS.get("history_size", 50),
image_max_px=NOTIFICATIONS.get("image_max_px", 128),
)
notification_toasts = NotificationToasts(
notifications_service,
monitor=0,
anchor=NOTIFICATIONS.get("anchor", "top center"),
margin=NOTIFICATIONS.get("margin", "8px"),
width=NOTIFICATIONS.get("width", 360),
timeout_ms=NOTIFICATIONS.get("timeout_ms", 10_000),
)
vinyl_button: VinylButton | None = VinylButton() if VINYL.get("enable", False) else None
calendar_service: CalendarService | None = (
CalendarService(update_interval=120000) if CALENDAR.get("enable", True) else None
)
control_center: ControlCenter | None = None
if notification_history is not None:
control_center = ControlCenter(
history=notification_history,
calendar_service=calendar_service,
vinyl_button=vinyl_button,
monitor=0,
width=NOTIFICATIONS.get("center_width", 380),
)
bar_windows = []
notmuch_widget = None
_app_windows = [dummy, finder, app_launcher, clipboard_menu, power_menu, screenshot_menu, notmuch_search_menu]
if screenrec_menu is not None:
_app_windows.append(screenrec_menu)
if notification_toasts is not None:
_app_windows.append(notification_toasts)
if control_center is not None:
_app_windows.append(control_center)
app = Application("sims", *_app_windows)
@Application.action()
def open_finder():
finder.show()
@Application.action()
def open_app_launcher():
app_launcher.show()
@Application.action()
def open_clipboard_menu():
clipboard_menu.show()
@Application.action()
def open_power_menu():
power_menu.show()
@Application.action()
def open_screenshot_menu():
screenshot_menu.show()
@Application.action()
def refresh_notmuch():
if notmuch_widget is not None:
notmuch_widget.service.update_counts()
@Application.action()
def open_notmuch_search():
notmuch_search_menu.show()
@Application.action()
def open_screenrec_menu():
if screenrec_menu is not None:
screenrec_menu.show()
@Application.action()
def screenrec_start_monitor():
if screenrec_service is not None:
screenrec_service.start_monitor("videos")
@Application.action()
def screenrec_start_region():
if screenrec_service is not None:
screenrec_service.start_region("videos")
@Application.action()
def screenrec_stop():
if screenrec_service is not None:
screenrec_service.stop()
@Application.action()
def toggle_control_center():
if control_center is not None:
control_center.toggle()
def _set_all_bars_rounded(rounded: bool):
for bar in bar_windows:
bar.set_corners_rounded(rounded)
@Application.action()
def set_bar_corners_rounded():
_set_all_bars_rounded(True)
@Application.action()
def set_bar_corners_flat():
_set_all_bars_rounded(False)
@Application.action()
def toggle_bar_corners():
new_state = not any(bar.corners_rounded for bar in bar_windows)
_set_all_bars_rounded(new_state)
# Load CSS - use Stylix if enabled, otherwise use default
if STYLIX.get("enable", False):
stylix_css_path = get_stylix_css_path()
if stylix_css_path:
logger.info("[Bar] Using Stylix CSS")
app.set_stylesheet_from_file(get_relative_path("styles/main.css"))
app.set_stylesheet_from_file(stylix_css_path, append=True)
else:
logger.warning("[Bar] Stylix enabled but CSS generation failed, falling back to default")
app.set_stylesheet_from_file(get_relative_path("styles/main.css"))
else:
logger.info("[Bar] Using default CSS")
app.set_stylesheet_from_file(get_relative_path("styles/main.css"))
def spawn_bars():
global notmuch_widget
logger.info("[Bar] Spawning bars")
outputs_reply = I3.send_command("", I3MessageType.GET_OUTPUTS)
if not (outputs_reply.is_ok and isinstance(outputs_reply.reply, list)):
logger.warning("[Bar] Failed to get outputs — skipping bar spawn")
return
outputs = [o for o in outputs_reply.reply if o.get("active")]
if not outputs:
logger.warning("[Bar] No active outputs found — skipping bar spawn")
return
for i, output in enumerate(outputs):
output_name = output.get("name", f"Unknown-{i}")
bar = StatusBar(
display=output_name,
tray=tray if i == 0 else None,
monitor=i,
screenrec_service=screenrec_service if i == 0 else None,
control_center=control_center if i == 0 else None,
)
bar_windows.append(bar)
if i == 0 and bar.notmuch:
notmuch_widget = bar.notmuch
def main():
spawn_bars()
app.run()
if __name__ == "__main__":
main()

201
sims/modules/bar.py Normal file
View File

@@ -0,0 +1,201 @@
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.image import Image
from fabric.widgets.overlay import Overlay
from fabric.widgets.datetime import DateTime
from fabric.widgets.centerbox import CenterBox
from sims.modules.player import Player, PlayerSmall
from sims.modules.battery import Battery
from sims.modules.control_center import ControlCenter
from sims.modules.notmuch import NotmuchWidget
from sims.modules.screenrec import ScreenrecWidget
from fabric.widgets.wayland import WaylandWindow as Window
from fabric.system_tray.widgets import SystemTray
from sims.widgets.fenster import FensterWorkspaces, FensterActiveWindow
from sims.services.screenrec import ScreenrecService
from sims.services.smart_corners import get_smart_corners_service
from fabric.widgets.button import Button
from fabric.widgets.circularprogressbar import CircularProgressBar
from sims.services.system_stats import SystemStatsService
from sims.config import BATTERY, BAR_HEIGHT, WINDOW_TITLE, NOTMUCH
class StatusBar(Window):
def __init__(
self,
display: str,
tray: SystemTray | None = None,
monitor: int = 1,
screenrec_service: ScreenrecService | None = None,
control_center: ControlCenter | None = None,
):
super().__init__(
name="sims",
layer="top",
anchor="left top right",
margin="0px 0px -2px 0px",
exclusivity="auto",
visible=False,
all_visible=False,
monitor=monitor,
)
self.output = display
self._corners_rounded = False
self._right_flat = False
self.workspaces = FensterWorkspaces(
output=display,
name="workspaces",
spacing=4,
)
datetime_widget = DateTime(name="date-time", formatters="%d %b - %H:%M")
self.date_time = Button(
name="date-time-button",
child=datetime_widget,
on_clicked=self._on_date_time_clicked,
style="background: transparent; border: none; padding: 0; margin: 0; box-shadow: none;",
)
self.control_center = control_center
self.system_tray = tray
self.active_window = FensterActiveWindow(
name="active-window",
max_length=50,
style="color: #ffffff; font-size: 14px; font-weight: bold;",
)
self.ram_progress_bar = CircularProgressBar(
name="ram-progress-bar", pie=True, size=24
)
self.cpu_progress_bar = CircularProgressBar(
name="cpu-progress-bar", pie=True, size=24
)
self.progress_label = Label(
"", style="margin: 0px 6px 0px 0px; font-size: 12px"
)
self.progress_bars_overlay = Overlay(
child=self.ram_progress_bar,
overlays=[self.cpu_progress_bar, self.progress_label],
)
self.player = Player()
self.player_small = PlayerSmall()
self.battery = None
if BATTERY["enable"]:
self.battery = Battery()
self.notmuch = None
if NOTMUCH["enable"]:
self.notmuch = NotmuchWidget()
self.screenrec = None
if screenrec_service is not None:
self.screenrec = ScreenrecWidget(screenrec_service)
self.status_container = Box(
name="widgets-container",
spacing=4,
orientation="h",
children=self.progress_bars_overlay,
)
end_container_children = []
end_container_children.append(self.status_container)
if self.system_tray:
end_container_children.append(self.system_tray)
if self.battery:
end_container_children.append(self.battery)
if self.notmuch:
end_container_children.append(self.notmuch)
if self.screenrec:
end_container_children.append(self.screenrec)
end_container_children.append(self.date_time)
center_children = []
if WINDOW_TITLE["enable"]:
center_children.append(self.active_window)
self.inner = CenterBox(
name="sims-inner",
start_children=Box(
name="start-container",
spacing=6,
orientation="h",
children=[
Image(name="nixos-label", icon_name="nix-snowflake-white", icon_size=20),
self.workspaces,
self.player_small,
],
),
center_children=Box(
name="center-container",
spacing=4,
orientation="h",
children=center_children,
),
end_children=Box(
name="end-container",
spacing=4,
orientation="h",
children=end_container_children,
),
)
self.children = self.inner
self.system_stats_service = SystemStatsService(update_interval=3000)
self.system_stats_service.connect("stats-changed", self.update_progress_bars)
self.set_size_request(-1, BAR_HEIGHT)
smart_corners = get_smart_corners_service()
smart_corners.connect("state-changed", self._on_smart_corners_changed)
self.set_corners_rounded(not smart_corners.get(display))
if self.control_center is not None:
self.control_center.add_visibility_listener(self.set_right_flat)
self.show_all()
@property
def corners_rounded(self) -> bool:
return self._corners_rounded
def set_corners_rounded(self, rounded: bool) -> None:
if rounded == self._corners_rounded:
return
if rounded:
self.inner.add_style_class("rounded-bottom")
else:
self.inner.remove_style_class("rounded-bottom")
self._corners_rounded = rounded
def _on_smart_corners_changed(self, _service, output: str, active: bool):
if output != self.output:
return
self.set_corners_rounded(not active)
def set_right_flat(self, flat: bool) -> None:
if flat == self._right_flat:
return
if flat:
self.inner.set_style("border-radius: 0 0 0 28px;")
else:
self.inner.set_style("")
self._right_flat = flat
def update_progress_bars(self, service, cpu_percent, memory_percent):
self.cpu_progress_bar.value = cpu_percent
self.ram_progress_bar.value = memory_percent
def _on_date_time_clicked(self, _button=None):
if self.control_center is not None:
self.control_center.toggle()

53
sims/modules/battery.py Normal file
View File

@@ -0,0 +1,53 @@
from gi.repository import GLib
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.image import Image
from sims.services.battery import BatteryService
class Battery(Box):
def __init__(self, **kwargs):
super().__init__(name="battery-widget", orientation="h", spacing=4, **kwargs)
self.bat_icon = Image(
name="bat-icon", icon_name="battery-full-symbolic", icon_size=16
)
self.bat_label = Label(name="bat-label", label="100%")
# Create battery service with signal-based updates
self.battery_service = BatteryService(update_interval=10000) # Check every 10 seconds
self.battery_service.connect("battery-changed", self.update_battery)
self.children = [self.bat_icon, self.bat_label]
self.show_all()
# Initialize with current battery status
initial_percent = self.battery_service.percent
initial_charging = self.battery_service.charging
GLib.idle_add(self.update_battery, None, initial_percent, initial_charging)
def _icon_lookup(self, bat, charging):
# Round to nearest 10 for level-based icons
level = max(10, min(100, round(bat / 10) * 10))
if charging:
# Adwaita ships battery-level-100-charged-symbolic, not -charging.
suffix = "charged" if level == 100 else "charging"
return f"battery-level-{level}-{suffix}-symbolic"
else:
return f"battery-level-{level}-symbolic"
def update_battery(self, service, percent, charging):
"""Update battery display when battery status changes"""
icon_name = self._icon_lookup(percent, charging)
self.bat_icon.set_property("icon-name", icon_name)
self.bat_label.set_text(f"{int(percent)}%")
if percent < 20 and not charging:
self.bat_label.add_style_class("battery-low")
self.bat_icon.add_style_class("battery-low")
else:
self.bat_label.remove_style_class("battery-low")
self.bat_icon.remove_style_class("battery-low")

200
sims/modules/calendar.py Normal file
View File

@@ -0,0 +1,200 @@
import json
import os
import subprocess
import shutil
from datetime import date
# Add common binary paths to PATH for user binaries
os.environ['PATH'] = '/run/current-system/sw/bin:/home/' + os.environ.get('USER', 'user') + '/.nix-profile/bin:' + os.environ.get('PATH', '')
from loguru import logger
from sims.config import CALENDAR
# Try to import khal as a Python library
try:
from khal.cli.main import main_khal
from khal.settings import get_config
from khal.khalendar import CalendarCollection
KHAL_AVAILABLE = True
logger.info("[Calendar] Using khal as Python library")
except ImportError:
KHAL_AVAILABLE = False
logger.info("[Calendar] khal Python library not available, falling back to subprocess")
class CalendarService:
def __init__(self, update_interval=300000): # 5 minutes default
self.events = []
self.callbacks = []
self._update_interval = update_interval
self._timer_id = None
# Initial load
self.update_events()
# Start periodic updates
self.start_monitoring()
def connect(self, signal_name, callback):
"""Simple callback system to replace signals"""
if signal_name == "events-changed":
self.callbacks.append(callback)
def emit_events_changed(self, events):
"""Emit events changed to all callbacks"""
for callback in self.callbacks:
callback(self, events)
def start_monitoring(self):
"""Start periodic event updates"""
if self._timer_id is None:
from fabric.utils import invoke_repeater
self._timer_id = invoke_repeater(
self._update_interval, self._periodic_update
)
logger.info(
f"[Calendar] Started periodic updates every {self._update_interval/1000/60:.1f} minutes"
)
def stop_monitoring(self):
"""Stop periodic event updates"""
if self._timer_id is not None:
from gi.repository import GLib
GLib.source_remove(self._timer_id)
self._timer_id = None
logger.info("[Calendar] Stopped periodic updates")
def _periodic_update(self):
"""Periodic update callback"""
logger.info("[Calendar] Performing periodic events update")
self.update_events()
return True # Keep the timer running
def get_cached_events(self):
"""Get cached events without triggering update"""
return self.events
def update_events_python_api(self):
"""Fetch today's events using khal Python API"""
try:
# Get khal configuration
config = get_config()
# Create calendar collection
collection = CalendarCollection.from_calendars(
calendars=config['calendars'],
dbpath=config['sqlite']['path'],
locale=config['locale'],
color=config['default']['print_new'],
unicode_symbols=config['default']['unicode_symbols'],
default_calendar=config['default']['default_calendar'],
readonly=True
)
# Get today's events
today = date.today()
events = collection.get_events_on(today)
# Format events to match our expected structure
formatted_events = []
for event in events:
formatted_event = {
'title': str(event.summary),
'start': event.start.strftime('%m-%d %H:%M') if hasattr(event.start, 'strftime') else '',
'end': event.end.strftime('%m-%d %H:%M') if hasattr(event.end, 'strftime') else '',
'location': str(event.location) if event.location else ''
}
formatted_events.append(formatted_event)
# Sort by start time
formatted_events.sort(key=lambda e: e.get('start', ''))
self.events = formatted_events
logger.info(f"[Calendar] Found {len(self.events)} events using Python API")
self.emit_events_changed(self.events)
except Exception as e:
logger.error(f"[Calendar] Error using khal Python API: {e}")
# Fall back to subprocess method
self.update_events_subprocess()
def update_events_subprocess(self):
"""Fetch today's events using khal subprocess (fallback)"""
# Get khal path from config
khal_path = CALENDAR.get("khal_path", "khal")
# Check if khal is available
if not shutil.which(khal_path):
logger.warning(f"[Calendar] khal not found at '{khal_path}'. Please install khal or configure the correct path.")
self.events = []
self.emit_events_changed(self.events)
return
try:
cmd = [
khal_path,
"list",
"--json",
"title",
"--json",
"start",
"--json",
"end",
"--json",
"location",
"today",
]
logger.info(f"[Calendar] Running command: {' '.join(cmd)}")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=True,
)
logger.info(f"[Calendar] Command stdout: {result.stdout[:200]}...")
logger.info(f"[Calendar] Command stderr: {result.stderr[:200]}...")
if result.stdout.strip():
lines = result.stdout.strip().split("\n")
all_events = []
for line in lines:
if line.strip():
try:
events = json.loads(line)
all_events.extend(events)
except json.JSONDecodeError:
continue
self.events = all_events
logger.info(f"[Calendar] Found {len(self.events)} events using subprocess")
self.emit_events_changed(self.events)
else:
self.events = []
self.emit_events_changed(self.events)
except subprocess.CalledProcessError as e:
logger.error(f"[Calendar] Failed to fetch events: {e}")
self.events = []
self.emit_events_changed(self.events)
except Exception as e:
logger.error(f"[Calendar] Error processing events: {e}")
self.events = []
self.emit_events_changed(self.events)
def update_events(self):
"""Fetch today's events from khal"""
# Check if calendar is enabled
if not CALENDAR.get("enable", True):
logger.info("[Calendar] Calendar is disabled in config")
self.events = []
self.emit_events_changed(self.events)
return
# Try Python API first, fall back to subprocess
if KHAL_AVAILABLE:
logger.info("[Calendar] Using khal Python API")
self.update_events_python_api()
else:
logger.info("[Calendar] Using khal subprocess")
self.update_events_subprocess()

View File

@@ -0,0 +1,352 @@
from datetime import datetime
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from fabric.widgets.scrolledwindow import ScrolledWindow
from fabric.widgets.wayland import WaylandWindow as Window
from gi.repository import Gdk
from sims.modules.calendar import CalendarService
from sims.modules.vinyl import VinylButton
from sims.services.notification_history import NotificationHistoryService
from sims.widgets.notification_history_entry import NotificationHistoryEntryWidget
class ControlCenter(Window):
def __init__(
self,
history: NotificationHistoryService,
calendar_service: CalendarService | None = None,
vinyl_button: VinylButton | None = None,
monitor: int = 0,
width: int = 380,
):
super().__init__(
name="control-center",
anchor="top right bottom",
monitor=monitor,
margin="0",
exclusivity="none",
keyboard_mode="on-demand",
visible=False,
)
self._history = history
self._calendar_service = calendar_service
self._vinyl_button = vinyl_button
self._width = width
self._visibility_listeners: list = []
close_button = Button(
name="control-center-close",
image=Image(icon_name="window-close-symbolic", icon_size=16),
on_clicked=lambda *_: self.hide(),
)
header = Box(
name="control-center-header",
orientation="h",
spacing=8,
)
header.pack_start(
Label(name="control-center-title", label="Control Center", h_align="start"),
True,
True,
0,
)
header.pack_end(close_button, False, False, 0)
sections: list = []
if vinyl_button is not None:
sections.append(self._build_settings_section())
if calendar_service is not None:
sections.append(self._build_calendar_section())
sections.append(self._build_notifications_section())
sections_box = Box(
name="control-center-sections",
orientation="v",
spacing=12,
children=sections,
h_expand=True,
)
scroll = ScrolledWindow(
name="control-center-scroll",
h_scrollbar_policy="never",
v_scrollbar_policy="automatic",
child=sections_box,
h_expand=True,
v_expand=True,
)
body = Box(
name="control-center-body",
orientation="v",
spacing=8,
children=[header, scroll],
h_expand=True,
v_expand=True,
)
body.set_size_request(self._width, -1)
self.add(body)
self.connect("key-press-event", self._on_key_press)
self._history.connect("changed", lambda *_: self._refresh_notifications())
if self._calendar_service is not None:
self._calendar_service.connect(
"events-changed",
lambda _service, events: self._refresh_calendar(events),
)
self._refresh_notifications()
if self._calendar_service is not None:
self._refresh_calendar(self._calendar_service.get_cached_events())
def _build_section(self, name: str, title: str | None) -> Box:
section = Box(
name=name,
orientation="v",
spacing=6,
h_expand=True,
)
if title is not None:
section.add(
Label(
name="control-center-section-title",
label=title,
h_align="start",
)
)
return section
def _build_settings_section(self) -> Box:
section = self._build_section("control-center-settings", "Settings")
row = Box(
name="control-center-settings-row",
orientation="h",
spacing=8,
)
row.pack_start(
Label(
name="control-center-settings-label",
label="Vinyl Passthrough",
h_align="start",
),
True,
True,
0,
)
row.pack_end(self._vinyl_button, False, False, 0)
section.add(row)
return section
def _build_calendar_section(self) -> Box:
section = self._build_section("control-center-calendar", "Calendar")
self._calendar_events_box = Box(
name="control-center-events",
orientation="v",
spacing=4,
h_expand=True,
)
section.add(self._calendar_events_box)
return section
def _build_notifications_section(self) -> Box:
section = self._build_section("control-center-notifications", None)
clear_button = Button(
name="control-center-notifications-clear",
label="Clear all",
on_clicked=lambda *_: self._history.clear(),
)
header = Box(
name="control-center-notifications-header",
orientation="h",
spacing=8,
)
header.pack_start(
Label(
name="control-center-section-title",
label="Notifications",
h_align="start",
),
True,
True,
0,
)
header.pack_end(clear_button, False, False, 0)
self._notifications_empty = Label(
name="control-center-notifications-empty",
label="No notifications",
h_align="start",
)
self._notifications_list = Box(
name="control-center-notifications-list",
orientation="v",
spacing=6,
h_expand=True,
)
section.add(header)
section.add(self._notifications_list)
return section
def add_visibility_listener(self, callback) -> None:
self._visibility_listeners.append(callback)
def _notify_visibility(self, visible: bool) -> None:
for callback in self._visibility_listeners:
callback(visible)
def toggle(self) -> None:
if self.get_visible():
self.hide()
else:
self.show()
def show(self) -> None: # type: ignore[override]
self._history.mark_all_seen()
super().show()
self.show_all()
self._notify_visibility(True)
def hide(self) -> None: # type: ignore[override]
super().hide()
self._notify_visibility(False)
def _on_key_press(self, _widget, event):
if event.keyval == Gdk.KEY_Escape:
self.hide()
return True
return False
def _refresh_notifications(self) -> None:
for child in self._notifications_list.get_children():
self._notifications_list.remove(child)
if child is not self._notifications_empty:
child.destroy()
entries = self._history.entries
if not entries:
self._notifications_list.add(self._notifications_empty)
self._notifications_empty.show_all()
return
for entry in entries:
self._notifications_list.add(
NotificationHistoryEntryWidget(
entry, on_dismiss=self._history.remove
)
)
self._notifications_list.show_all()
def _refresh_calendar(self, events) -> None:
for child in self._calendar_events_box.get_children():
self._calendar_events_box.remove(child)
child.destroy()
if not events:
self._calendar_events_box.add(
Label(
name="control-center-no-events",
label="No events today",
h_align="start",
)
)
self._calendar_events_box.show_all()
return
now = datetime.now()
current_time = now.strftime("%H:%M")
current_time_added = False
for event in events:
title = event.get("title", "No title")
start_raw = event.get("start", "")
end_raw = event.get("end", "")
start_time = start_raw.split()[1] if start_raw else ""
end_time = end_raw.split()[1] if end_raw else ""
location = event.get("location", "")
if not current_time_added and start_time and start_time > current_time:
self._calendar_events_box.add(self._build_now_indicator(current_time))
current_time_added = True
if start_time and end_time:
time_str = f"{start_time} - {end_time}"
elif start_time:
time_str = start_time
else:
time_str = "All day"
event_box = Box(
name="event-item",
orientation="h",
spacing=12,
style_classes=["event-item"],
)
event_box.add(
Label(
time_str,
name="event-time",
style_classes=["event-time"],
style="min-width: 90px;",
)
)
content_box = Box(
name="event-content",
orientation="v",
spacing=2,
)
content_box.add(
Label(
title,
name="event-title",
style_classes=["event-title"],
h_align="start",
)
)
if location:
content_box.add(
Label(
f"📍 {location}",
name="event-location",
style_classes=["event-location"],
h_align="start",
)
)
event_box.add(content_box)
self._calendar_events_box.add(event_box)
if not current_time_added:
self._calendar_events_box.add(self._build_now_indicator(current_time))
self._calendar_events_box.show_all()
def _build_now_indicator(self, current_time: str) -> Box:
indicator = Box(
name="current-time-indicator",
orientation="h",
spacing=8,
style_classes=["current-time-indicator"],
)
indicator.add(
Label(
current_time,
name="current-time-label",
style_classes=["current-time-label"],
style="min-width: 90px; font-weight: bold;",
)
)
indicator.add(
Label(
"━━━ NOW",
name="current-time-line",
style_classes=["current-time-line"],
)
)
return indicator

176
sims/modules/icons.py Normal file
View File

@@ -0,0 +1,176 @@
# Parameters
font_family: str = "tabler-icons"
font_weight: str = "normal"
span: str = f"<span font-family='{font_family}' font-weight='{font_weight}'>"
# Panels
apps: str = "&#xf1fd;"
dashboard: str = "&#xea87;"
chat: str = "&#xf59f;"
wallpapers: str = "&#xeb01;"
windows: str = "&#xefe6;"
# Bar
colorpicker: str = "&#xebe6;"
media: str = "&#xf00d;"
# Toolbox
toolbox: str = "&#xebca;"
ssfull: str = "&#xec3c;"
ssregion: str = "&#xf201;"
sswindow: str = "&#xeaea;"
screenshots: str = "&#xeb0a;"
screenrecord: str = "&#xed22;"
recordings: str = "&#xeafa;"
ocr: str = "&#xfcc3;"
gamemode: str = "&#xf026;"
gamemode_off: str = "&#xf111;"
close: str = "&#xeb55;"
# Circles
temp: str = "&#xeb38;"
disk: str = "&#xea88;"
battery: str = "&#xea38;"
memory: str = "&#xfa97;"
cpu: str = "&#xef8e;"
gpu: str = "&#xf233;"
# AIchat
reload: str = "&#xf3ae;"
detach: str = "&#xea99;"
# Wallpapers
add: str = "&#xeb0b;"
sort: str = "&#xeb5a;"
circle: str = "&#xf671;"
# Chevrons
chevron_up: str = "&#xea62;"
chevron_down: str = "&#xea5f;"
chevron_left: str = "&#xea60;"
chevron_right: str = "&#xea61;"
# Power
lock: str = "&#xeae2;"
suspend: str = "&#xece7;"
logout: str = "&#xeba8;"
reboot: str = "&#xeb13;"
shutdown: str = "&#xeb0d;"
# Power Manager
power_saving: str = "&#xed4f;"
power_balanced: str = "&#xfa77;"
power_performance: str = "&#xec45;"
charging: str = "&#xefef;"
discharging: str = "&#xefe9;"
alert: str = "&#xea06;"
bat_charging: str = "&#xeeca;"
bat_discharging: str = "&#xf0a1;"
bat_low: str = "&#xff1d;"
bat_full: str = "&#xea38;"
# Applets
wifi_0: str = "&#xeba3;"
wifi_1: str = "&#xeba4;"
wifi_2: str = "&#xeba5;"
wifi_3: str = "&#xeb52;"
world: str = "&#xeb54;"
world_off: str = "&#xf1ca;"
bluetooth: str = "&#xea37;"
night: str = "&#xeaf8;"
coffee: str = "&#xef0e;"
notifications: str = "&#xea35;"
wifi_off: str = "&#xecfa;"
bluetooth_off: str = "&#xeceb;"
night_off: str = "&#xf162;"
notifications_off: str = "&#xece9;"
notifications_clear: str = "&#xf814;"
download: str = "&#xea96;"
upload: str = "&#xeb47;"
# Bluetooth
bluetooth_connected: str = "&#xecea;"
bluetooth_disconnected: str = "&#xf081;"
# Player
pause: str = "&#xf690;"
play: str = "&#xf691;"
stop: str = "&#xf695;"
skip_back: str = "&#xf693;"
skip_forward: str = "&#xf694;"
prev: str = "&#xf697;"
next: str = "&#xf696;"
shuffle: str = "&#xf000;"
repeat: str = "&#xeb72;"
music: str = "&#xeafc;"
rewind_backward_5: str = "&#xfabf;"
rewind_forward_5: str = "&#xfac7;"
# Volume
vol_off: str = "&#xf1c3;"
vol_mute: str = "&#xeb50;"
vol_medium: str = "&#xeb4f;"
vol_high: str = "&#xeb51;"
mic: str = "&#xeaf0;"
mic_mute: str = "&#xed16;"
# Overview
circle_plus: str = "&#xea69;"
# Pins
paperclip: str = "&#xeb02;"
# Clipboard Manager
clipboard: str = "&#xea6f;"
clip_text: str = "&#xf089;"
# Confirm
accept: str = "&#xea5e;"
cancel: str = "&#xeb55;"
trash: str = "&#xeb41;"
# Config
config: str = "&#xeb20;"
# Icons
firefox: str = "&#xecfd;"
chromium: str = "&#xec18;"
spotify: str = "&#xfe86;"
disc: str = "&#x1003e;"
disc_off: str = "&#xf118;"
# Brightness
brightness_low: str = "&#xeb7d;"
brightness_medium: str = "&#xeb7e;"
brightness_high: str = "&#xeb30;"
# Misc
dot: str = "&#xf698;"
palette: str = "&#xeb01;"
cloud_off: str = "&#xed3e;"
loader: str = "&#xeca3;"
radar: str = "&#xf017;"
emoji: str = "&#xeaf7;"
keyboard: str = "&#xebd6;"
terminal: str = "&#xebef;"
timer_off: str = "&#xf146;"
timer_on: str = "&#xf756;"
spy: str = "&#xf227;"
exceptions: list[str] = ["font_family", "font_weight", "span"]
def apply_span() -> None:
global_dict = globals()
for key in global_dict:
if key not in exceptions and not key.startswith("__"):
global_dict[key] = f"{span}{global_dict[key]}</span>"
apply_span()

View File

@@ -0,0 +1,10 @@
from .base import FuzzyMenu, LauncherProvider, StaticAction, StaticActionProvider
from .windows import WindowProvider
__all__ = [
"FuzzyMenu",
"LauncherProvider",
"StaticAction",
"StaticActionProvider",
"WindowProvider",
]

View File

@@ -0,0 +1,87 @@
import re
import shlex
import subprocess
from fabric.utils.helpers import DesktopApp, get_desktop_applications
from fabric.widgets.box import Box
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from gi.repository import Gtk
from .base import FuzzyMenu
ICON_SIZE = 32
_FIELD_CODE_RE = re.compile(r"^%[fFuUickdDnNvm]$")
class AppProvider:
def items(self) -> list[DesktopApp]:
return get_desktop_applications()
def filter(self, items: list[DesktopApp], query: str) -> list[DesktopApp]:
if not query:
return items
q = query.lower()
return [a for a in items if _matches(a, q)]
def render(self, item: DesktopApp) -> Gtk.Widget:
children: list[Gtk.Widget] = []
pixbuf = item.get_icon_pixbuf(size=ICON_SIZE)
if pixbuf is not None:
children.append(Image(pixbuf=pixbuf, name="app-icon"))
primary = item.display_name or item.name or ""
text_box = Box(name="app-text", orientation="v", spacing=0)
text_box.add(Label(label=primary, name="app-name", h_align="start"))
if item.generic_name and item.generic_name != primary:
text_box.add(
Label(label=item.generic_name, name="app-generic", h_align="start")
)
children.append(text_box)
return Box(name="slot-box", orientation="h", spacing=10, children=children)
def activate(self, item: DesktopApp) -> None:
# Launch in a transient systemd --user scope so the app gets its own
# cgroup instead of inheriting sims.service's. start_new_session alone
# only changes POSIX session/pgid; systemd tracks units by cgroup and
# would kill children with sims on stop (default KillMode=control-group).
if item.command_line:
argv = [
t for t in shlex.split(item.command_line) if not _FIELD_CODE_RE.match(t)
]
if argv:
subprocess.Popen(
[
"systemd-run",
"--quiet",
"--user",
"--scope",
"--collect",
"--",
*argv,
],
start_new_session=True,
)
return
item.launch()
def _matches(app: DesktopApp, q: str) -> bool:
for field in (app.name, app.display_name, app.generic_name, app.executable):
if field and q in field.lower():
return True
return False
def AppLauncher(monitor: int = 0) -> FuzzyMenu:
return FuzzyMenu(
provider=AppProvider(),
monitor=monitor,
placeholder="Search Apps...",
window_name="app-launcher",
max_results=8,
)

View File

@@ -0,0 +1,205 @@
from dataclasses import dataclass
from typing import Any, Callable, Protocol
from fabric.widgets.box import Box
from fabric.widgets.entry import Entry
from fabric.widgets.label import Label
from fabric.widgets.wayland import WaylandWindow as Window
from gi.repository import Gdk, Gtk
from sims.services.fenster import focused_output_index
class LauncherProvider(Protocol):
def items(self) -> list[Any]: ...
def filter(self, items: list[Any], query: str) -> list[Any]: ...
def render(self, item: Any) -> Gtk.Widget: ...
def activate(self, item: Any) -> None: ...
@dataclass
class StaticAction:
label: str
handler: Callable[[], None]
class StaticActionProvider:
"""Provider for menus whose items are a fixed list of (label, handler) pairs.
Pass either StaticAction instances or (label, handler) tuples; tuples are
coerced. items_factory lets the list re-evaluate on each open (e.g. for
state-dependent menus) — otherwise the list is captured at construction.
"""
def __init__(
self,
actions: list[StaticAction | tuple[str, Callable[[], None]]] | None = None,
items_factory: Callable[[], list[StaticAction | tuple[str, Callable[[], None]]]] | None = None,
):
if (actions is None) == (items_factory is None):
raise ValueError("pass exactly one of actions or items_factory")
self._static = [_coerce(a) for a in actions] if actions is not None else None
self._factory = items_factory
def items(self) -> list[StaticAction]:
if self._factory is not None:
return [_coerce(a) for a in self._factory()]
return list(self._static or [])
def filter(self, items: list[StaticAction], query: str) -> list[StaticAction]:
if not query:
return items
q = query.lower()
return [i for i in items if q in i.label.lower()]
def render(self, item: StaticAction) -> Gtk.Widget:
return Box(
name="slot-box",
orientation="h",
children=[Label(label=item.label, h_align="start")],
)
def activate(self, item: StaticAction) -> None:
item.handler()
def _coerce(a: StaticAction | tuple[str, Callable[[], None]]) -> StaticAction:
if isinstance(a, StaticAction):
return a
label, handler = a
return StaticAction(label=label, handler=handler)
class FuzzyMenu(Window):
def __init__(
self,
provider: LauncherProvider,
monitor: int = 0,
placeholder: str = "Search...",
window_name: str = "finder",
max_results: int | None = None,
):
self._max_results = max_results
super().__init__(
name=window_name,
anchor="center",
monitor=monitor,
keyboard_mode="exclusive",
type="popup",
visible=False,
)
self._provider = provider
self._items: list[Any] = []
self._filtered: list[Any] = []
self._selected_index: int = 0
self._scroll_offset: int = 0
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.search_entry = Entry(
name="search-entry",
placeholder=placeholder,
h_expand=True,
editable=True,
notify_text=self._on_text_changed,
)
self.picker_box = Box(
name="picker-box",
spacing=4,
orientation="v",
children=[self.search_entry, self.viewport],
)
self.add(self.picker_box)
self.connect("key-press-event", self._on_key_press)
self._refresh_viewport("")
def show(self):
self._items = self._provider.items()
self.search_entry.set_text("")
self._selected_index = 0
self._scroll_offset = 0
self._refresh_viewport("")
self.monitor = focused_output_index()
super().show()
self.search_entry.grab_focus()
def _on_text_changed(self, entry, *_):
self._selected_index = 0
self._scroll_offset = 0
self._refresh_viewport(entry.get_text())
def _on_key_press(self, _widget, event):
ctrl = bool(event.state & Gdk.ModifierType.CONTROL_MASK)
keyval = event.keyval
if keyval == Gdk.KEY_Escape:
self.hide()
return True
if ctrl and keyval in (Gdk.KEY_g, Gdk.KEY_G):
self.hide()
return True
if keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
self._activate_selected()
return True
if keyval == Gdk.KEY_Down or (ctrl and keyval in (Gdk.KEY_n, Gdk.KEY_N)):
self._move_selection(1)
return True
if keyval == Gdk.KEY_Up or (ctrl and keyval in (Gdk.KEY_p, Gdk.KEY_P)):
self._move_selection(-1)
return True
return False
def _window_size(self) -> int:
return self._max_results if self._max_results is not None else len(self._filtered)
def _move_selection(self, delta: int):
if not self._filtered:
return
new_index = self._selected_index + delta
new_index = max(0, min(new_index, len(self._filtered) - 1))
if new_index == self._selected_index:
return
self._selected_index = new_index
window = self._window_size()
if window <= 0:
self._scroll_offset = 0
elif self._selected_index < self._scroll_offset:
self._scroll_offset = self._selected_index
elif self._selected_index >= self._scroll_offset + window:
self._scroll_offset = self._selected_index - window + 1
self._render_visible()
def _refresh_viewport(self, query: str):
self._filtered = self._provider.filter(self._items, query)
if self._selected_index >= len(self._filtered):
self._selected_index = 0
self._scroll_offset = 0
self._render_visible()
def _render_visible(self):
window = self._window_size()
if window <= 0:
visible: list[Any] = []
else:
max_offset = max(0, len(self._filtered) - window)
self._scroll_offset = min(self._scroll_offset, max_offset)
visible = self._filtered[self._scroll_offset : self._scroll_offset + window]
self.viewport.children = []
for item in visible:
self.viewport.add(self._provider.render(item))
self._update_selection_highlight()
def _update_selection_highlight(self):
visible_index = self._selected_index - self._scroll_offset
for i, child in enumerate(self.viewport.get_children()):
ctx = child.get_style_context()
if i == visible_index:
ctx.add_class("selected")
else:
ctx.remove_class("selected")
def _activate_selected(self):
if self._filtered and 0 <= self._selected_index < len(self._filtered):
self._provider.activate(self._filtered[self._selected_index])
self.hide()

View File

@@ -0,0 +1,75 @@
import subprocess
from dataclasses import dataclass
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from gi.repository import Gtk
from .base import FuzzyMenu
@dataclass
class ClipEntry:
raw: str # full "<id>\t<preview>" line as emitted by cliphist
preview: str
class ClipboardProvider:
def items(self) -> list[ClipEntry]:
proc = subprocess.run(
["cliphist", "list"],
capture_output=True,
text=True,
)
if proc.returncode != 0:
return []
entries: list[ClipEntry] = []
for line in proc.stdout.splitlines():
if not line:
continue
_id, sep, preview = line.partition("\t")
if not sep:
continue
entries.append(ClipEntry(raw=line, preview=preview))
return entries
def filter(self, items: list[ClipEntry], query: str) -> list[ClipEntry]:
if not query:
return items
q = query.lower()
return [e for e in items if q in e.preview.lower()]
def render(self, item: ClipEntry) -> Gtk.Widget:
return Box(
name="slot-box",
orientation="h",
children=[
Label(
label=item.preview,
h_align="start",
ellipsization="end",
max_chars_width=120,
name="clip-preview",
),
],
)
def activate(self, item: ClipEntry) -> None:
decoded = subprocess.run(
["cliphist", "decode"],
input=item.raw.encode("utf-8"),
capture_output=True,
)
if decoded.returncode != 0:
return
subprocess.run(["wl-copy"], input=decoded.stdout)
def ClipboardMenu(monitor: int = 0) -> FuzzyMenu:
return FuzzyMenu(
provider=ClipboardProvider(),
monitor=monitor,
placeholder="Clipboard...",
window_name="clipboard-menu",
max_results=12,
)

View File

@@ -0,0 +1,284 @@
"""Live notmuch search launcher.
A FuzzyMenu variant that runs `notmuch search` per keystroke (debounced),
renders thread summaries, and on activation opens the thread in emacs notmuch.
A bare-query handoff item is always appended so the user can defer to
notmuch-search inside emacs without having a matching result selected.
"""
from __future__ import annotations
import json
import subprocess
from dataclasses import dataclass
from typing import Any
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from gi.repository import GLib, Gtk
from loguru import logger
from sims.config import NOTMUCH
from .base import FuzzyMenu
DEBOUNCE_MS = 120
MIN_QUERY_LEN = 2
SEARCH_LIMIT = 30
@dataclass
class NotmuchHit:
thread: str
subject: str
authors: str
date_relative: str
@property
def query(self) -> str:
return f"thread:{self.thread}"
@dataclass
class SavedSearch:
name: str
query: str
@dataclass
class BareQueryHandoff:
query: str
def _elisp_escape(s: str) -> str:
return s.replace("\\", "\\\\").replace('"', '\\"')
class NotmuchSearchProvider:
def __init__(self):
self._notmuch_path = NOTMUCH.get("notmuch_path", "notmuch")
self._emacsclient = NOTMUCH.get("emacsclient_command", "emacsclient")
raw_saved = NOTMUCH.get("saved_searches", []) or []
self._saved: list[SavedSearch] = []
for entry in raw_saved:
query = (entry.get("query") or "").strip()
if not query:
continue
name = entry.get("name") or query
self._saved.append(SavedSearch(name=name, query=query))
def saved_searches(self) -> list[SavedSearch]:
return list(self._saved)
def search(self, query: str) -> list[NotmuchHit]:
cmd = [
self._notmuch_path,
"search",
"--format=json",
"--output=summary",
f"--limit={SEARCH_LIMIT}",
query,
]
try:
proc = subprocess.run(
cmd, capture_output=True, text=True, check=True, timeout=2
)
except subprocess.CalledProcessError as e:
logger.warning(
f"[NotmuchSearch] search failed for {query!r}: {e.stderr.strip()}"
)
return []
except (subprocess.TimeoutExpired, FileNotFoundError) as e:
logger.warning(f"[NotmuchSearch] {e}")
return []
try:
raw = json.loads(proc.stdout) or []
except json.JSONDecodeError:
return []
hits: list[NotmuchHit] = []
for r in raw:
hits.append(
NotmuchHit(
thread=str(r.get("thread", "")),
subject=r.get("subject") or "(no subject)",
authors=r.get("authors") or "",
date_relative=r.get("date_relative") or "",
)
)
return hits
def render_hit(self, hit: NotmuchHit) -> Gtk.Widget:
text = Box(name="notmuch-text", orientation="v", spacing=0, h_expand=True)
text.add(
Label(
label=hit.subject,
name="notmuch-subject",
h_align="start",
ellipsization="end",
max_chars_width=80,
)
)
text.add(
Label(
label=hit.authors,
name="notmuch-authors",
h_align="start",
ellipsization="end",
max_chars_width=80,
)
)
meta = Label(
label=hit.date_relative, name="notmuch-date", h_align="end"
)
return Box(
name="slot-box",
orientation="h",
spacing=10,
children=[text, meta],
)
def render_saved(self, item: SavedSearch) -> Gtk.Widget:
text = Box(name="notmuch-text", orientation="v", spacing=0, h_expand=True)
text.add(
Label(label=item.name, name="notmuch-saved-name", h_align="start")
)
text.add(
Label(
label=item.query,
name="notmuch-saved-query",
h_align="start",
ellipsization="end",
max_chars_width=80,
)
)
return Box(
name="slot-box", orientation="h", spacing=10, children=[text]
)
def render_bare(self, item: BareQueryHandoff) -> Gtk.Widget:
return Box(
name="slot-box",
orientation="h",
children=[
Label(
label=f"→ Search '{item.query}' in emacs",
name="notmuch-bare",
h_align="start",
),
],
)
def open_thread(self, hit: NotmuchHit) -> None:
self._emacs_eval(f'(notmuch-show "{_elisp_escape(hit.query)}")')
def open_search(self, query: str) -> None:
self._emacs_eval(f'(notmuch-search "{_elisp_escape(query)}")')
def _emacs_eval(self, sexp: str) -> None:
try:
subprocess.Popen(
[self._emacsclient, "-c", "-e", sexp],
start_new_session=True,
)
except Exception as e:
logger.error(f"[NotmuchSearch] failed to launch emacsclient: {e}")
class _MenuProvider:
"""LauncherProvider that defers to NotmuchSearchProvider.
items() returns saved searches (shown when the entry is empty).
filter() is identity — NotmuchSearchMenu manages self._items directly
on every keystroke (live search instead of in-memory filtering).
"""
def __init__(self, search: NotmuchSearchProvider):
self._search = search
def items(self) -> list[Any]:
return list(self._search.saved_searches())
def filter(self, items: list[Any], query: str) -> list[Any]:
return items
def render(self, item: Any) -> Gtk.Widget:
if isinstance(item, NotmuchHit):
return self._search.render_hit(item)
if isinstance(item, SavedSearch):
return self._search.render_saved(item)
if isinstance(item, BareQueryHandoff):
return self._search.render_bare(item)
return Box()
def activate(self, item: Any) -> None:
if isinstance(item, NotmuchHit):
self._search.open_thread(item)
elif isinstance(item, SavedSearch):
self._search.open_search(item.query)
elif isinstance(item, BareQueryHandoff):
self._search.open_search(item.query)
class NotmuchSearchMenu(FuzzyMenu):
def __init__(self, monitor: int = 0):
self._search = NotmuchSearchProvider()
super().__init__(
provider=_MenuProvider(self._search),
monitor=monitor,
placeholder="notmuch search…",
window_name="notmuch-search",
max_results=12,
)
self._debounce_id: int | None = None
def show(self):
self._cancel_debounce()
super().show()
def hide(self):
self._cancel_debounce()
super().hide()
def _on_text_changed(self, entry, *_):
text = entry.get_text()
self._cancel_debounce()
self._selected_index = 0
self._scroll_offset = 0
if not text:
# Empty query: re-show saved searches via the provider.
self._items = self._search.saved_searches()
self._refresh_viewport(text)
return
if len(text) < MIN_QUERY_LEN:
# Too short to query notmuch; offer just the bare-query handoff.
self._items = [BareQueryHandoff(query=text)]
self._refresh_viewport(text)
return
# Show the bare-query handoff immediately while we wait for the search
# — gives the user a way to commit before the debounce fires.
self._items = [BareQueryHandoff(query=text)]
self._refresh_viewport(text)
self._debounce_id = GLib.timeout_add(
DEBOUNCE_MS, self._on_debounce_fire, text
)
def _cancel_debounce(self):
if self._debounce_id is not None:
GLib.source_remove(self._debounce_id)
self._debounce_id = None
def _on_debounce_fire(self, text: str):
self._debounce_id = None
if self.search_entry.get_text() != text:
return False
hits = self._search.search(text)
items: list[Any] = list(hits)
items.append(BareQueryHandoff(query=text))
self._items = items
self._selected_index = 0
self._scroll_offset = 0
self._refresh_viewport(text)
return False

View File

@@ -0,0 +1,25 @@
import subprocess
from .base import FuzzyMenu, StaticActionProvider
def _spawn(argv: list[str]) -> None:
subprocess.Popen(argv, start_new_session=True)
def PowerMenu(monitor: int = 0, lock_command: list[str] | None = None) -> FuzzyMenu:
lock = lock_command or ["waylock"]
provider = StaticActionProvider(
actions=[
("⏻ Poweroff", lambda: _spawn(["systemctl", "poweroff"])),
("🔁 Reboot", lambda: _spawn(["systemctl", "reboot"])),
("⏾ Suspend", lambda: _spawn(["systemctl", "suspend"])),
("Lock", lambda: _spawn(lock)),
]
)
return FuzzyMenu(
provider=provider,
monitor=monitor,
placeholder="Power Menu...",
window_name="power-menu",
)

View File

@@ -0,0 +1,30 @@
from sims.services.screenrec import ScreenrecService
from .base import FuzzyMenu, StaticActionProvider
def _idle_actions(service: ScreenrecService):
return [
("Monitor → Videos", lambda: service.start_monitor("videos")),
("Region → Videos", lambda: service.start_region("videos")),
("Monitor → Clipboard", lambda: service.start_monitor("clipboard")),
("Region → Clipboard", lambda: service.start_region("clipboard")),
]
def ScreenrecProvider(service: ScreenrecService) -> StaticActionProvider:
def items():
if service.recording:
return [("Stop Recording", service.stop)]
return _idle_actions(service)
return StaticActionProvider(items_factory=items)
def ScreenrecMenu(service: ScreenrecService, monitor: int = 0) -> FuzzyMenu:
return FuzzyMenu(
provider=ScreenrecProvider(service),
monitor=monitor,
placeholder="Screen Recording...",
window_name="screenrec-menu",
)

View File

@@ -0,0 +1,23 @@
import subprocess
from .base import FuzzyMenu, StaticActionProvider
def _spawn(argv: list[str]) -> None:
subprocess.Popen(argv, start_new_session=True)
def ScreenshotMenu(monitor: int = 0) -> FuzzyMenu:
provider = StaticActionProvider(
actions=[
("Normal", lambda: _spawn(["grimnorm"])),
("To Clipboard", lambda: _spawn(["grim2clip"])),
("To Imv", lambda: _spawn(["grim2imv"])),
]
)
return FuzzyMenu(
provider=provider,
monitor=monitor,
placeholder="Screenshot...",
window_name="screenshot-menu",
)

View File

@@ -0,0 +1,60 @@
from sims.services.i3 import I3, I3MessageType
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from gi.repository import Gtk
class WindowProvider:
def items(self) -> list[dict]:
windows: list[dict] = []
tree_reply = I3.send_command("", I3MessageType.GET_TREE)
if not (tree_reply.is_ok and isinstance(tree_reply.reply, dict)):
return windows
tree = tree_reply.reply
for output_node in tree.get("nodes", []):
for ws_node in output_node.get("nodes", []):
ws_num = ws_node.get("num", 0)
for con in ws_node.get("nodes", []):
if con.get("type") == "con":
windows.append({
"id": con.get("id"),
"app_id": con.get("app_id") or "",
"title": con.get("name") or "",
"workspace": ws_num,
})
for con in ws_node.get("floating_nodes", []):
if con.get("type") == "con":
windows.append({
"id": con.get("id"),
"app_id": con.get("app_id") or "",
"title": con.get("name") or "",
"workspace": ws_num,
})
return windows
def filter(self, items: list[dict], query: str) -> list[dict]:
if not query:
return items
q = query.lower()
return [
w for w in items
if q in w.get("title", "").lower()
or q in w.get("app_id", "").lower()
]
def render(self, item: dict) -> Gtk.Widget:
title = item.get("title", "")
app_id = item.get("app_id", "")
ws_num = item.get("workspace", 0)
text = f"[{ws_num}] {app_id}: {title}" if app_id else f"[{ws_num}] {title}"
return Box(
name="slot-box",
orientation="h",
children=[Label(label=text)],
)
def activate(self, item: dict) -> None:
window_id = item.get("id")
if window_id is not None:
I3.send_command(f"[con_id={window_id}] focus")

View File

@@ -0,0 +1,54 @@
from typing import cast
from fabric.notifications import Notification, Notifications
from fabric.widgets.box import Box
from fabric.widgets.wayland import WaylandWindow as Window
from loguru import logger
from sims.widgets.notification import NotificationWidget
class NotificationToasts(Window):
def __init__(
self,
service: Notifications,
monitor: int = 0,
anchor: str = "top center",
margin: str = "8px",
width: int = 360,
timeout_ms: int = 10_000,
):
super().__init__(
name="notification-toasts",
anchor=anchor,
monitor=monitor,
margin=margin,
exclusivity="none",
visible=True,
all_visible=True,
)
self._width = width
self._timeout_ms = timeout_ms
self._stack = Box(
size=2, # so the compositor doesn't optimize the empty surface away
spacing=4,
orientation="v",
)
self.add(self._stack)
self._service = service
self._service.connect("notification-added", self._on_added)
def _on_added(self, service: Notifications, nid: int):
notification = cast(Notification, service.get_notification_from_id(nid))
if notification is None:
logger.warning(f"[Notifications] no notification for id {nid}")
return
self._stack.add(
NotificationWidget(
notification,
width=self._width,
timeout_ms=self._timeout_ms,
)
)

208
sims/modules/notmuch.py Normal file
View File

@@ -0,0 +1,208 @@
import os
import subprocess
import shutil
# Add common binary paths to PATH for user binaries
os.environ['PATH'] = '/run/current-system/sw/bin:/home/' + os.environ.get('USER', 'user') + '/.nix-profile/bin:' + os.environ.get('PATH', '')
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from loguru import logger
from sims.config import NOTMUCH
DEFAULT_DEBT_QUERY = "tag:unread and date:..1w"
DEFAULT_DEBT_WARN_AT = 1
DEFAULT_DEBT_ALARM_AT = 6
class NotmuchService:
def __init__(self, update_interval=60000): # 1 minute default
self.unread_count = 0
self.debt_count = 0
self.callbacks = []
self._update_interval = update_interval
self._timer_id = None
# Initial load
self.update_counts()
# Start periodic updates
self.start_monitoring()
def connect(self, signal_name, callback):
"""Simple callback system to replace signals"""
if signal_name == "counts-changed":
self.callbacks.append(callback)
def emit_counts_changed(self):
"""Emit counts changed to all callbacks"""
for callback in self.callbacks:
callback(self, self.unread_count, self.debt_count)
def start_monitoring(self):
"""Start periodic unread count updates"""
if self._timer_id is None:
from fabric.utils import invoke_repeater
self._timer_id = invoke_repeater(
self._update_interval, self._periodic_update
)
logger.info(
f"[Notmuch] Started periodic updates every {self._update_interval/1000} seconds"
)
def stop_monitoring(self):
"""Stop periodic unread count updates"""
if self._timer_id is not None:
from gi.repository import GLib
GLib.source_remove(self._timer_id)
self._timer_id = None
logger.info("[Notmuch] Stopped periodic updates")
def _periodic_update(self):
"""Periodic update callback"""
logger.info("[Notmuch] Performing periodic count update")
self.update_counts()
return True # Keep the timer running
def get_cached_count(self):
"""Get cached unread count without triggering update"""
return self.unread_count
def get_cached_debt_count(self):
"""Get cached debt count without triggering update"""
return self.debt_count
def _run_count(self, notmuch_path, query):
cmd = [notmuch_path, "count", query]
logger.info(f"[Notmuch] Running command: {' '.join(cmd)}")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=True,
)
out = result.stdout.strip()
return int(out) if out else 0
def update_counts(self):
"""Fetch unread + debt counts from notmuch"""
# Check if notmuch is enabled
if not NOTMUCH.get("enable", True):
logger.info("[Notmuch] Notmuch is disabled in config")
self.unread_count = 0
self.debt_count = 0
self.emit_counts_changed()
return
# Get notmuch path from config
notmuch_path = NOTMUCH.get("notmuch_path", "notmuch")
# Check if notmuch is available
if not shutil.which(notmuch_path):
logger.warning(f"[Notmuch] notmuch not found at '{notmuch_path}'. Please install notmuch or configure the correct path.")
self.unread_count = 0
self.debt_count = 0
self.emit_counts_changed()
return
debt_query = NOTMUCH.get("debt_query", DEFAULT_DEBT_QUERY)
try:
self.unread_count = self._run_count(notmuch_path, "tag:unread")
self.debt_count = self._run_count(notmuch_path, debt_query)
logger.info(
f"[Notmuch] {self.unread_count} unread, {self.debt_count} aging (debt query: {debt_query!r})"
)
self.emit_counts_changed()
except subprocess.CalledProcessError as e:
logger.error(f"[Notmuch] Failed to fetch counts: {e}")
self.unread_count = 0
self.debt_count = 0
self.emit_counts_changed()
except ValueError as e:
logger.error(f"[Notmuch] Error parsing count: {e}")
self.unread_count = 0
self.debt_count = 0
self.emit_counts_changed()
except Exception as e:
logger.error(f"[Notmuch] Error getting counts: {e}")
self.unread_count = 0
self.debt_count = 0
self.emit_counts_changed()
class NotmuchWidget(Button):
def __init__(self, **kwargs):
# Create the widget content
self.icon = Image(icon_name="mail-unread-symbolic", icon_size=16)
self.label = Label("0", name="unread-count")
# Container for icon and label
container = Box(
orientation="h",
spacing=4,
children=[self.icon, self.label]
)
super().__init__(
name="notmuch-widget",
child=container,
on_clicked=self.open_email_client,
**kwargs,
)
# Initialize the service
self.service = NotmuchService()
self.service.connect("counts-changed", self.update_display)
logger.info("[Notmuch] Notmuch widget initialized")
# Initial update
self.update_display(
self.service, self.service.unread_count, self.service.debt_count
)
def open_email_client(self, button=None):
"""Open notmuch in emacsclient"""
emacsclient_command = NOTMUCH.get("emacsclient_command", "emacsclient")
try:
# Open emacsclient with notmuch function
cmd = [emacsclient_command, "-c", "-e", "(notmuch)"]
logger.info(f"[Notmuch] Running emacsclient command: {' '.join(cmd)}")
subprocess.Popen(cmd, start_new_session=True)
logger.info(f"[Notmuch] Successfully started emacsclient process")
except Exception as e:
logger.error(f"[Notmuch] Failed to open notmuch in emacsclient '{emacsclient_command}': {e}")
def update_display(self, service, unread, debt):
"""Update the widget display with unread + debt counts"""
warn_at = NOTMUCH.get("debt_warn_at", DEFAULT_DEBT_WARN_AT)
alarm_at = NOTMUCH.get("debt_alarm_at", DEFAULT_DEBT_ALARM_AT)
classes = ["notmuch-widget"]
if unread > 0:
self.label.set_text(str(unread))
self.label.set_visible(True)
self.icon.set_property("icon-name", "mail-unread-symbolic")
classes.append("has-unread")
else:
self.label.set_text("")
self.label.set_visible(False)
self.icon.set_property("icon-name", "mail-read-symbolic")
classes.append("no-unread")
if debt >= alarm_at:
classes.append("debt-alarm")
elif debt >= warn_at:
classes.append("debt-warn")
self.set_style_classes(classes)
self.set_tooltip_text(f"{unread} unread · {debt} aging")
logger.info(
f"[Notmuch] Updated display: {unread} unread, {debt} aging — classes={classes}"
)

931
sims/modules/player.py Normal file
View File

@@ -0,0 +1,931 @@
import contextlib
import os
import urllib.parse
import urllib.request
import tempfile
from gi.repository import Gtk, GLib, Gio, Gdk, Pango
from fabric.widgets.box import Box
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.label import Label
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.widgets.circularprogressbar import CircularProgressBar
from fabric.widgets.overlay import Overlay
from fabric.widgets.stack import Stack
from ..widgets.circle_image import CircleImage
import sims.modules.icons as icons
from sims.services.mpris import MprisPlayerManager, MprisPlayer
from fabric import Fabricator
# from sims.modules.cavalcade import SpectrumRender
def get_player_progress(fabricator, mpris_player):
"""Get player progress for Fabricator"""
if not mpris_player:
return (0, 0, 0.0)
try:
current = mpris_player.position
except Exception:
current = 0
try:
total = int(mpris_player.length or 0)
except Exception:
total = 0
progress = current / total if total > 0 else 0.0
return (current, total, progress)
def get_player_icon_markup_by_name(player_name):
if player_name:
pn = player_name.lower()
if pn == "firefox":
return icons.firefox
elif pn == "spotify":
return icons.spotify
elif pn in ("chromium", "brave"):
return icons.chromium
return icons.disc
def add_hover_cursor(widget):
widget.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK)
widget.connect(
"enter-notify-event",
lambda w, event: w.get_window().set_cursor(
Gdk.Cursor.new_from_name(Gdk.Display.get_default(), "pointer")
),
)
widget.connect(
"leave-notify-event", lambda w, event: w.get_window().set_cursor(None)
)
class PlayerBox(Box):
def __init__(self, mpris_player=None):
super().__init__(
orientation="v", h_align="fill", spacing=0, h_expand=False, v_expand=True
)
self.mpris_player = mpris_player
self._progress_timer_id = None # Initialize timer ID
self.cover = CircleImage(
name="player-cover",
image_file=os.path.expanduser("~/Pictures/wallpaper/background.jpg"),
size=162,
h_align="center",
v_align="center",
)
self.cover_placerholder = CircleImage(
name="player-cover",
size=198,
h_align="center",
v_align="center",
)
self.title = Label(
name="player-title",
h_expand=True,
h_align="fill",
ellipsization="end",
max_chars_width=1,
)
self.album = Label(
name="player-album",
h_expand=True,
h_align="fill",
ellipsization="end",
max_chars_width=1,
)
self.artist = Label(
name="player-artist",
h_expand=True,
h_align="fill",
ellipsization="end",
max_chars_width=1,
)
self.progressbar = CircularProgressBar(
name="player-progress",
size=198,
h_align="center",
v_align="center",
start_angle=180,
end_angle=360,
)
self.time = Label(name="player-time", label="--:-- / --:--")
self.overlay = Overlay(
child=self.cover_placerholder,
overlays=[self.progressbar, self.cover],
)
self.overlay_container = CenterBox(
name="player-overlay", center_children=[self.overlay]
)
self.title.set_label("Nothing Playing")
self.album.set_label("Enjoy the silence")
self.artist.set_label("¯\\_(ツ)_/¯")
self.progressbar.set_value(0.0)
self.prev = Button(
name="player-btn",
child=Label(name="player-btn-label", markup=icons.prev),
)
self.backward = Button(
name="player-btn",
child=Label(name="player-btn-label", markup=icons.skip_back),
)
self.play_pause = Button(
name="player-btn",
child=Label(name="player-btn-label", markup=icons.play),
)
self.forward = Button(
name="player-btn",
child=Label(name="player-btn-label", markup=icons.skip_forward),
)
self.next = Button(
name="player-btn",
child=Label(name="player-btn-label", markup=icons.next),
)
# Add hover effect to buttons
add_hover_cursor(self.prev)
add_hover_cursor(self.backward)
add_hover_cursor(self.play_pause)
add_hover_cursor(self.forward)
add_hover_cursor(self.next)
self.btn_box = CenterBox(
name="player-btn-box",
orientation="h",
center_children=[
Box(
orientation="h",
spacing=8,
h_expand=True,
h_align="fill",
children=[
self.prev,
self.backward,
self.play_pause,
self.forward,
self.next,
],
)
],
)
self.player_box = Box(
name="player-box",
orientation="v",
spacing=8,
children=[
self.overlay_container,
self.title,
self.album,
self.artist,
self.btn_box,
self.time,
],
)
self.add(self.player_box)
if mpris_player:
self._apply_mpris_properties() # This will handle starting the timer if needed
self.prev.connect("clicked", self._on_prev_clicked)
self.play_pause.connect("clicked", self._on_play_pause_clicked)
self.backward.connect("clicked", self._on_backward_clicked)
self.forward.connect("clicked", self._on_forward_clicked)
self.next.connect("clicked", self._on_next_clicked)
self.mpris_player.connect("changed", self._on_mpris_changed)
else:
self.play_pause.get_child().set_markup(icons.stop)
# Ensure buttons are disabled visually if no player
self.backward.add_style_class("disabled")
self.forward.add_style_class("disabled")
self.prev.add_style_class("disabled")
self.next.add_style_class("disabled")
self.progressbar.set_value(0.0)
self.time.set_text("--:-- / --:--")
def _apply_mpris_properties(self):
mp = self.mpris_player
self.title.set_visible(bool(mp.title and mp.title.strip()))
if mp.title and mp.title.strip():
self.title.set_text(mp.title)
self.album.set_visible(bool(mp.album and mp.album.strip()))
if mp.album and mp.album.strip():
self.album.set_text(mp.album)
self.artist.set_visible(bool(mp.artist and mp.artist.strip()))
if mp.artist and mp.artist.strip():
self.artist.set_text(mp.artist)
if mp.arturl:
parsed = urllib.parse.urlparse(mp.arturl)
if parsed.scheme == "file":
local_arturl = urllib.parse.unquote(parsed.path)
self._set_cover_image(local_arturl)
elif parsed.scheme in ("http", "https"):
GLib.Thread.new(
"download-artwork", self._download_and_set_artwork, mp.arturl
)
else:
self._set_cover_image(mp.arturl)
else:
fallback = os.path.expanduser("~/Pictures/wallpaper/background.jpg")
self._set_cover_image(fallback)
file_obj = Gio.File.new_for_path(fallback)
monitor = file_obj.monitor_file(Gio.FileMonitorFlags.NONE, None)
monitor.connect("changed", self.on_wallpaper_changed)
self._wallpaper_monitor = monitor
self.update_play_pause_icon()
# Keep progress bar and time visible always
self.progressbar.set_visible(True)
self.time.set_visible(True)
player_name = (
mp.player_name.lower()
if hasattr(mp, "player_name") and mp.player_name
else ""
)
can_seek = hasattr(mp, "can_seek") and mp.can_seek
if player_name == "firefox" or not can_seek:
# Disable seeking buttons and reset progress/time display
self.backward.add_style_class("disabled")
self.forward.add_style_class("disabled")
self.progressbar.set_value(0.0)
self.time.set_text("--:-- / --:--")
# Stop the timer if it's running
if self._progress_timer_id:
GLib.source_remove(self._progress_timer_id)
self._progress_timer_id = None
else:
# Enable seeking buttons
self.backward.remove_style_class("disabled")
self.forward.remove_style_class("disabled")
# Start the timer if it's not already running
if not self._progress_timer_id:
self._progress_timer_id = GLib.timeout_add(1000, self._update_progress)
# Initial progress update if possible
self._update_progress() # Call once for immediate update
# Enable/disable prev/next based on capabilities
if hasattr(mp, "can_go_previous") and mp.can_go_previous:
self.prev.remove_style_class("disabled")
else:
self.prev.add_style_class("disabled")
if hasattr(mp, "can_go_next") and mp.can_go_next:
self.next.remove_style_class("disabled")
else:
self.next.add_style_class("disabled")
def _set_cover_image(self, image_path):
if image_path and os.path.isfile(image_path):
self.cover.set_image_from_file(image_path)
else:
fallback = os.path.expanduser("~/Pictures/wallpaper/background.jpg")
self.cover.set_image_from_file(fallback)
file_obj = Gio.File.new_for_path(fallback)
monitor = file_obj.monitor_file(Gio.FileMonitorFlags.NONE, None)
monitor.connect("changed", self.on_wallpaper_changed)
self._wallpaper_monitor = monitor
def _download_and_set_artwork(self, arturl):
"""
Download the artwork from the given URL asynchronously and update the cover image
using GLib.idle_add to ensure UI updates occur on the main thread.
"""
try:
parsed = urllib.parse.urlparse(arturl)
suffix = os.path.splitext(parsed.path)[1] or ".png"
with urllib.request.urlopen(arturl) as response:
data = response.read()
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
temp_file.write(data)
temp_file.close()
local_arturl = temp_file.name
except Exception:
local_arturl = os.path.expanduser("~/.current.wall")
GLib.idle_add(self._set_cover_image, local_arturl)
return None
def update_play_pause_icon(self):
if self.mpris_player.playback_status == "playing":
self.play_pause.get_child().set_markup(icons.pause)
else:
self.play_pause.get_child().set_markup(icons.play)
def on_wallpaper_changed(self, monitor, file, other_file, event):
self.cover.set_image_from_file(os.path.expanduser("~/.current.wall"))
# --- Control methods, defined only once each ---
def _on_prev_clicked(self, button):
if self.mpris_player:
self.mpris_player.previous()
def _on_play_pause_clicked(self, button):
if self.mpris_player:
self.mpris_player.play_pause()
self.update_play_pause_icon()
def _on_backward_clicked(self, button):
# Only seek if player exists, can seek, and button is not disabled
if (
self.mpris_player
and self.mpris_player.can_seek
and "disabled" not in self.backward.get_style_context().list_classes()
):
new_pos = max(0, self.mpris_player.position - 5000000) # 5 seconds backward
self.mpris_player.position = new_pos
def _on_forward_clicked(self, button):
# Only seek if player exists, can seek, and button is not disabled
if (
self.mpris_player
and self.mpris_player.can_seek
and "disabled" not in self.forward.get_style_context().list_classes()
):
new_pos = self.mpris_player.position + 5000000 # 5 seconds forward
self.mpris_player.position = new_pos
def _on_next_clicked(self, button):
if self.mpris_player:
self.mpris_player.next()
def _update_progress(self):
# Timer is now only active if can_seek is true, so no need for the initial check
if not self.mpris_player: # Still need to check if player exists
# Should not happen if timer logic is correct, but good safeguard
if self._progress_timer_id:
GLib.source_remove(self._progress_timer_id)
self._progress_timer_id = None
return False # Stop timer
try:
current = self.mpris_player.position
except Exception:
current = 0
try:
total = int(self.mpris_player.length or 0)
except Exception:
total = 0
# Prevent division by zero or invalid updates
if total <= 0:
progress = 0.0
self.time.set_text("--:-- / --:--")
# Don't stop the timer here, length might become available later
else:
progress = current / total
self.time.set_text(
f"{self._format_time(current)} / {self._format_time(total)}"
)
self.progressbar.set_value(progress)
return True # Continue the timer
def _format_time(self, us):
seconds = int(us / 1000000)
minutes = seconds // 60
seconds = seconds % 60
return f"{minutes}:{seconds:02}"
def _update_metadata(self):
if not self.mpris_player:
return False
self._apply_mpris_properties()
return True
def _on_mpris_changed(self, *args):
# Debounce metadata updates to avoid excessive work on the main thread.
if not hasattr(self, "_update_pending") or not self._update_pending:
self._update_pending = True
# Use idle_add for potentially faster UI response than timeout_add(100)
GLib.idle_add(self._apply_mpris_properties_debounced)
def _apply_mpris_properties_debounced(self):
# Ensure player still exists before applying properties
if self.mpris_player:
self._apply_mpris_properties()
else:
# Player vanished, ensure timer is stopped if it was running
if self._progress_timer_id:
GLib.source_remove(self._progress_timer_id)
self._progress_timer_id = None
self._update_pending = False
return False
class Player(Box):
def __init__(self):
super().__init__(
name="player",
orientation="v",
h_align="fill",
spacing=0,
h_expand=False,
v_expand=True,
)
self.player_stack = Stack(
name="player-stack",
transition_type="slide-left-right",
transition_duration=500,
v_align="center",
v_expand=True,
)
self.switcher = Gtk.StackSwitcher(
name="player-switcher",
spacing=8,
)
self.switcher.set_stack(self.player_stack)
self.switcher.set_halign(Gtk.Align.CENTER)
self.mpris_manager = MprisPlayerManager()
players = self.mpris_manager.players
if players:
for p in players:
mp = MprisPlayer(p)
pb = PlayerBox(mpris_player=mp)
self.player_stack.add_titled(pb, mp.player_name, mp.player_name)
else:
pb = PlayerBox(mpris_player=None)
self.player_stack.add_titled(pb, "nothing", "Nothing Playing")
self.mpris_manager.connect("player-appeared", self.on_player_appeared)
self.mpris_manager.connect("player-vanished", self.on_player_vanished)
self.switcher.set_visible(True)
self.add(self.player_stack)
self.add(self.switcher)
GLib.idle_add(self._replace_switcher_labels)
def on_player_appeared(self, manager, player):
children = self.player_stack.get_children()
if len(children) == 1 and not getattr(children[0], "mpris_player", None):
self.player_stack.remove(children[0])
mp = MprisPlayer(player)
pb = PlayerBox(mpris_player=mp)
self.player_stack.add_titled(pb, mp.player_name, mp.player_name)
# Timer is now started conditionally within PlayerBox.__init__
self.switcher.set_visible(True)
GLib.idle_add(lambda: self._update_switcher_for_player(mp.player_name))
GLib.idle_add(self._replace_switcher_labels)
def on_player_vanished(self, manager, player_name):
for child in self.player_stack.get_children():
if (
hasattr(child, "mpris_player")
and child.mpris_player
and child.mpris_player.player_name == player_name
):
self.player_stack.remove(child)
break
if not any(
getattr(child, "mpris_player", None)
for child in self.player_stack.get_children()
):
pb = PlayerBox(mpris_player=None)
self.player_stack.add_titled(pb, "nothing", "Nothing Playing")
self.switcher.set_visible(True)
GLib.idle_add(self._replace_switcher_labels)
def _replace_switcher_labels(self):
buttons = self.switcher.get_children()
for btn in buttons:
if isinstance(btn, Gtk.ToggleButton):
default_label = None
for child in btn.get_children():
if isinstance(child, Gtk.Label):
default_label = child
break
if default_label:
label_player_name = getattr(
default_label, "player_name", default_label.get_text().lower()
)
icon_markup = get_player_icon_markup_by_name(label_player_name)
btn.remove(default_label)
new_label = Label(name="player-label", markup=icon_markup)
new_label.player_name = label_player_name
btn.add(new_label)
new_label.show_all()
return False
def _update_switcher_for_player(self, player_name):
for btn in self.switcher.get_children():
if isinstance(btn, Gtk.ToggleButton):
default_label = None
for child in btn.get_children():
if isinstance(child, Gtk.Label):
default_label = child
break
if default_label:
label_player_name = getattr(
default_label, "player_name", default_label.get_text().lower()
)
if label_player_name == player_name.lower():
icon_markup = get_player_icon_markup_by_name(player_name)
btn.remove(default_label)
new_label = Label(name="player-label", markup=icon_markup)
new_label.player_name = player_name.lower()
btn.add(new_label)
new_label.show_all()
return False
class PlayerSmall(Box):
PLAY_ICON = "media-playback-start-symbolic"
PAUSE_ICON = "media-playback-pause-symbolic"
PREV_ICON = "media-skip-backward-symbolic"
NEXT_ICON = "media-skip-forward-symbolic"
FALLBACK_ICON = "audio-x-generic-symbolic"
COVER_SIZE = 22
def __init__(self):
super().__init__(
name="player-small", orientation="h", v_align="center"
)
self._display_options = ["title", "artist"]
self._display_index = 0
self._current_display = "title"
self._spin_timer_id = None
self._spin_step = 2 # deg per tick → ~9s per rotation at 50ms
self._spin_interval_ms = 50
self.cover = CircleImage(
name="compact-mpris-cover",
size=self.COVER_SIZE,
h_align="center",
v_align="center",
)
self.fallback_icon = Image(
name="compact-mpris-fallback",
icon_name=self.FALLBACK_ICON,
icon_size=16,
)
self.cover_stack = Stack(
name="compact-mpris-cover-stack",
transition_type="crossfade",
transition_duration=200,
children=[self.fallback_icon, self.cover],
)
self.cover_stack.set_visible_child(self.fallback_icon)
self.mpris_icon = Button(
name="compact-mpris-icon",
h_align="center",
v_align="center",
child=self.cover_stack,
)
self.mpris_icon.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.mpris_icon.connect("button-press-event", self._on_icon_button_press)
add_hover_cursor(self.mpris_icon)
self.mpris_label = Label(
name="compact-mpris-label",
label="Nothing Playing",
ellipsization="end",
max_chars_width=26,
h_align="center",
)
self._width_tween_id = None
self._current_label_width_px = None
self._width_tween_duration_ms = 220
self.play_image = Image(
name="compact-mpris-button-icon",
icon_name=self.PLAY_ICON,
icon_size=16,
)
self.mpris_button = Button(
name="compact-mpris-button",
h_align="center",
v_align="center",
child=self.play_image,
)
self.mpris_button.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.mpris_button.connect(
"button-press-event", self._on_play_pause_button_press
)
add_hover_cursor(self.mpris_button)
self.center_stack = Stack(
name="compact-mpris",
transition_type="crossfade",
transition_duration=100,
v_align="center",
v_expand=False,
children=[self.mpris_label],
)
self.mpris_small = CenterBox(
name="compact-mpris",
orientation="h",
h_expand=True,
h_align="fill",
v_align="center",
v_expand=False,
start_children=self.mpris_icon,
center_children=self.center_stack,
end_children=self.mpris_button,
)
self.add(self.mpris_small)
self.mpris_manager = MprisPlayerManager()
self.mpris_player = None
self._players = {}
self._player_handlers = {}
self._last_status = {}
for p in self.mpris_manager.players:
self._track_player(p)
self._select_initial_player()
self._apply_mpris_properties()
self.mpris_manager.connect("player-appeared", self.on_player_appeared)
self.mpris_manager.connect("player-vanished", self.on_player_vanished)
def _char_width_px(self):
metrics = self.mpris_label.get_pango_context().get_metrics(None, None)
return max(1.0, metrics.get_approximate_char_width() / Pango.SCALE)
def _measure_text_width(self, text):
if not text:
return 0
layout = self.mpris_label.create_pango_layout(text)
text_width_px, _ = layout.get_pixel_size()
max_px = int(self._char_width_px() * 26)
return min(text_width_px, max_px)
def _apply_label_width(self, width_px):
if width_px <= 0:
self.mpris_label.set_size_request(0, -1)
if self.mpris_label.get_margin_start() != 0:
self.mpris_label.set_margin_start(0)
self.mpris_label.set_margin_end(0)
if self.mpris_label.get_visible():
self.mpris_label.set_visible(False)
self._current_label_width_px = 0
return
if not self.mpris_label.get_visible():
self.mpris_label.set_visible(True)
chars = max(1, int(round(width_px / self._char_width_px())))
if chars != self.mpris_label.get_max_width_chars():
self.mpris_label.set_max_width_chars(chars)
self.mpris_label.set_size_request(width_px, -1)
margin = min(6, width_px // 2)
if self.mpris_label.get_margin_start() != margin:
self.mpris_label.set_margin_start(margin)
self.mpris_label.set_margin_end(margin)
self._current_label_width_px = width_px
def _set_label_text(self, text):
target_text = text or ""
target_px = self._measure_text_width(target_text)
if self._width_tween_id is not None:
GLib.source_remove(self._width_tween_id)
self._width_tween_id = None
# First call — snap to target without animation.
if self._current_label_width_px is None:
self.mpris_label.set_text(target_text)
self._apply_label_width(target_px)
return
start_px = self._current_label_width_px
# Growing from collapsed: set new text first so it's ready to reveal.
# Cross-fading between two non-empty texts: also swap text immediately.
# Shrinking to empty: keep old text visible while it shrinks, clear at end.
if target_px > 0:
self.mpris_label.set_text(target_text)
if start_px == target_px:
self._apply_label_width(target_px)
return
duration_ms = self._width_tween_duration_ms
start_time = GLib.get_monotonic_time()
def tick():
elapsed_ms = (GLib.get_monotonic_time() - start_time) / 1000.0
progress = min(1.0, elapsed_ms / duration_ms)
t = 1 - (1 - progress) ** 3 # ease-out cubic
cur_px = int(start_px + (target_px - start_px) * t)
self._apply_label_width(cur_px)
if progress >= 1.0:
self._apply_label_width(target_px)
if target_px == 0:
self.mpris_label.set_text("")
self._width_tween_id = None
return False
return True
self._width_tween_id = GLib.timeout_add(16, tick)
def _set_cover_from_path(self, image_path):
if image_path and os.path.isfile(image_path):
try:
self.cover.set_image_from_file(image_path)
self.cover_stack.set_visible_child(self.cover)
self._update_spin()
return False
except Exception:
pass
self.cover_stack.set_visible_child(self.fallback_icon)
self._update_spin()
return False
def _start_spin(self):
if self._spin_timer_id is None:
self._spin_timer_id = GLib.timeout_add(
self._spin_interval_ms, self._advance_spin
)
def _stop_spin(self):
if self._spin_timer_id is not None:
GLib.source_remove(self._spin_timer_id)
self._spin_timer_id = None
def _advance_spin(self):
self.cover.angle = (self.cover.angle + self._spin_step) % 360
return True
def _update_spin(self):
showing_cover = self.cover_stack.get_visible_child() is self.cover
is_playing = (
self.mpris_player is not None
and self.mpris_player.playback_status == "playing"
)
if showing_cover and is_playing:
self._start_spin()
else:
self._stop_spin()
def _download_artwork(self, arturl):
try:
parsed = urllib.parse.urlparse(arturl)
suffix = os.path.splitext(parsed.path)[1] or ".png"
with urllib.request.urlopen(arturl) as response:
data = response.read()
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
tmp.write(data)
tmp.close()
local_path = tmp.name
except Exception:
local_path = None
GLib.idle_add(self._set_cover_from_path, local_path)
return None
def _update_cover(self, mp):
if not mp or not mp.arturl:
self.cover_stack.set_visible_child(self.fallback_icon)
return
parsed = urllib.parse.urlparse(mp.arturl)
if parsed.scheme == "file":
self._set_cover_from_path(urllib.parse.unquote(parsed.path))
elif parsed.scheme in ("http", "https"):
GLib.Thread.new("compact-artwork", self._download_artwork, mp.arturl)
else:
self._set_cover_from_path(mp.arturl)
def _apply_mpris_properties(self):
if not self.mpris_player:
self._set_label_text("")
self.play_image.set_property("icon-name", self.PLAY_ICON)
self.cover_stack.set_visible_child(self.fallback_icon)
self.center_stack.set_visible_child(self.mpris_label)
self._update_spin()
return
mp = self.mpris_player
self._update_cover(mp)
self.update_play_pause_icon()
if self._current_display == "title":
text = mp.title.strip() if mp.title and mp.title.strip() else ""
else: # "artist"
text = mp.artist.strip() if mp.artist and mp.artist.strip() else ""
self._set_label_text(text)
self.center_stack.set_visible_child(self.mpris_label)
def _on_icon_button_press(self, widget, event):
if event.type != Gdk.EventType.BUTTON_PRESS:
return True
if event.button == 2:
if not self.mpris_player:
return True
self._display_index = (self._display_index + 1) % len(self._display_options)
self._current_display = self._display_options[self._display_index]
self._apply_mpris_properties()
return True
players = list(self._players.values())
if not players:
return True
idx = players.index(self.mpris_player) if self.mpris_player in players else -1
if event.button == 1:
idx = (idx + 1) % len(players)
elif event.button == 3:
idx = (idx - 1) % len(players)
else:
return True
self.mpris_player = players[idx]
self._apply_mpris_properties()
return True
def _on_play_pause_button_press(self, widget, event):
if event.type != Gdk.EventType.BUTTON_PRESS or not self.mpris_player:
return True
if event.button == 1:
self.mpris_player.play_pause()
self.update_play_pause_icon()
elif event.button == 3:
self.mpris_player.next()
self.play_image.set_property("icon-name", self.NEXT_ICON)
GLib.timeout_add(500, self._restore_play_pause_icon)
elif event.button == 2:
self.mpris_player.previous()
self.play_image.set_property("icon-name", self.PREV_ICON)
GLib.timeout_add(500, self._restore_play_pause_icon)
return True
def _restore_play_pause_icon(self):
self.update_play_pause_icon()
return False
def update_play_pause_icon(self):
playing = (
self.mpris_player
and self.mpris_player.playback_status == "playing"
)
self.play_image.set_property(
"icon-name", self.PAUSE_ICON if playing else self.PLAY_ICON
)
self._update_spin()
def _track_player(self, playerctl_player):
mp = MprisPlayer(playerctl_player)
name = mp.player_name
handler_id = mp.connect("changed", self._on_any_player_changed)
self._players[name] = mp
self._player_handlers[name] = handler_id
self._last_status[name] = mp.playback_status
def _untrack_player(self, name):
mp = self._players.pop(name, None)
handler_id = self._player_handlers.pop(name, None)
self._last_status.pop(name, None)
if mp and handler_id is not None:
with contextlib.suppress(Exception):
mp.disconnect(handler_id)
def _select_initial_player(self):
for mp in self._players.values():
if mp.playback_status == "playing":
self.mpris_player = mp
return
if self._players:
self.mpris_player = next(iter(self._players.values()))
def _on_any_player_changed(self, player):
name = player.player_name
prev_status = self._last_status.get(name)
cur_status = player.playback_status
self._last_status[name] = cur_status
if player is self.mpris_player:
self._apply_mpris_properties()
return
# Auto-follow: only on a fresh transition into "playing", and only
# if the active player isn't already playing (so a manual selection
# of a paused player isn't overridden by the player it was already
# competing with).
if cur_status == "playing" and prev_status != "playing":
active_playing = (
self.mpris_player
and self.mpris_player.playback_status == "playing"
)
if not active_playing:
self.mpris_player = player
self._apply_mpris_properties()
def on_player_appeared(self, manager, player):
self._track_player(player)
if not self.mpris_player:
name = player.get_property("player-name")
self.mpris_player = self._players.get(name)
self._apply_mpris_properties()
def on_player_vanished(self, manager, player_name):
was_active = (
self.mpris_player and self.mpris_player.player_name == player_name
)
self._untrack_player(player_name)
if was_active:
replacement = next(
(mp for mp in self._players.values() if mp.playback_status == "playing"),
None,
)
if replacement is None and self._players:
replacement = next(iter(self._players.values()))
self.mpris_player = replacement
self._apply_mpris_properties()

112
sims/modules/power.py Normal file
View File

@@ -0,0 +1,112 @@
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.button import Button
from fabric.utils.helpers import exec_shell_command_async
import modules.icons as icons
class PowerMenu(Box):
def __init__(self, **kwargs):
super().__init__(
name="power-menu",
orientation="h",
spacing=4,
v_align="center",
h_align="center",
visible=True,
**kwargs,
)
self.notch = kwargs["notch"]
self.btn_lock = Button(
name="power-menu-button",
child=Label(name="button-label", markup=icons.lock),
on_clicked=self.lock,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_suspend = Button(
name="power-menu-button",
child=Label(name="button-label", markup=icons.suspend),
on_clicked=self.suspend,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_logout = Button(
name="power-menu-button",
child=Label(name="button-label", markup=icons.logout),
on_clicked=self.logout,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_reboot = Button(
name="power-menu-button",
child=Label(name="button-label", markup=icons.reboot),
on_clicked=self.reboot,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.btn_shutdown = Button(
name="power-menu-button",
child=Label(name="button-label", markup=icons.shutdown),
on_clicked=self.poweroff,
h_expand=False,
v_expand=False,
h_align="center",
v_align="center",
)
self.buttons = [
self.btn_lock,
self.btn_suspend,
self.btn_logout,
self.btn_reboot,
self.btn_shutdown,
]
for button in self.buttons:
self.add(button)
self.show_all()
def close_menu(self):
self.notch.close_notch()
# Métodos de acción
def lock(self, *args):
print("Locking screen...")
exec_shell_command_async("loginctl lock-session")
self.close_menu()
def suspend(self, *args):
print("Suspending system...")
exec_shell_command_async("systemctl suspend")
self.close_menu()
def logout(self, *args):
print("Logging out...")
exec_shell_command_async("hyprctl dispatch exit")
self.close_menu()
def reboot(self, *args):
print("Rebooting system...")
exec_shell_command_async("systemctl reboot")
self.close_menu()
def poweroff(self, *args):
print("Powering off...")
exec_shell_command_async("systemctl poweroff")
self.close_menu()

59
sims/modules/screenrec.py Normal file
View File

@@ -0,0 +1,59 @@
import time
from fabric.utils import invoke_repeater
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from gi.repository import GLib
from sims.services.screenrec import ScreenrecService
class ScreenrecWidget(Button):
def __init__(self, service: ScreenrecService, **kwargs):
self._service = service
self._timer_id: int | None = None
self._dot = Label(name="screenrec-dot", label="")
self._elapsed = Label(name="screenrec-elapsed", label="00:00")
super().__init__(
name="screenrec-widget",
child=Box(
orientation="h",
spacing=6,
children=[self._dot, self._elapsed],
),
on_clicked=lambda *_: self._service.stop(),
visible=False,
**kwargs,
)
self.set_no_show_all(True)
self._service.connect("recording-changed", self._on_recording_changed)
if self._service.recording:
self._on_recording_changed(self._service, True)
def _on_recording_changed(self, _service, recording: bool):
if recording:
self._update_elapsed()
self.set_visible(True)
if self._timer_id is None:
self._timer_id = invoke_repeater(1000, self._update_elapsed)
else:
self.set_visible(False)
if self._timer_id is not None:
try:
GLib.source_remove(self._timer_id)
except Exception:
pass
self._timer_id = None
def _update_elapsed(self) -> bool:
started = self._service.started_at
if started is None:
self._elapsed.set_text("00:00")
return True
secs = int(time.monotonic() - started)
self._elapsed.set_text(f"{secs // 60:02d}:{secs % 60:02d}")
return True

475
sims/modules/stylix.py Normal file
View File

@@ -0,0 +1,475 @@
from sims.config import STYLIX
import tempfile
import os
def generate_stylix_css():
"""Generate CSS using Stylix colors if enabled"""
if not STYLIX.get("enable", False):
return None
colors = STYLIX.get("colors", {})
fonts = STYLIX.get("fonts", {})
# Default colors if Stylix is not properly configured
default_colors = {
"base00": "1e1e2e", # background
"base01": "313244", # lighter background
"base02": "45475a", # selection background
"base03": "585b70", # comments
"base04": "bac2de", # dark foreground
"base05": "cdd6f4", # foreground
"base06": "f5e0dc", # light foreground
"base07": "b4befe", # light background
"base08": "f38ba8", # red
"base09": "fab387", # orange
"base0A": "f9e2af", # yellow
"base0B": "a6e3a1", # green
"base0C": "94e2d5", # cyan
"base0D": "89b4fa", # blue
"base0E": "cba6f7", # purple
"base0F": "f2cdcd", # brown
}
# Use Stylix colors or fallback to defaults
for key in default_colors:
if key not in colors:
colors[key] = default_colors[key]
# Default font
font_family = fonts.get("sansSerif", "sans-serif")
font_sizes = fonts.get("sizes", {})
# Use desktop font size for the bar, fallback to applications, then default
font_size = font_sizes.get("desktop", font_sizes.get("applications", 14))
# Calculate relative font sizes
small_font = max(int(font_size * 0.85), 10) # Minimum 10px
large_font = int(font_size * 1.1)
# Debug logging
from loguru import logger
logger.info(f"[Stylix] Using font sizes - Base: {font_size}px, Small: {small_font}px, Large: {large_font}px")
# Generate GTK CSS with Stylix colors
css_content = f"""/* Stylix-generated theme */
/* Apply Stylix font */
* {{
font-family: "{font_family}", sans-serif;
font-size: {font_size}px;
}}
/* Bar styling */
#sims-inner {{
padding: 4px;
border-bottom: solid 2px;
border-color: #{colors["base02"]};
background-color: #{colors["base00"]};
border-radius: 0;
transition: border-radius 200ms ease;
}}
#sims-inner.rounded-bottom {{
border-radius: 0 0 28px 28px;
}}
#center-container {{
color: #{colors["base05"]};
}}
.active-window {{
color: #{colors["base05"]};
font-weight: bold;
}}
/* Battery */
#battery-widget {{
background-color: #{colors["base01"]};
padding: 4px 8px;
border-radius: 12px;
}}
#bat-icon {{
color: #{colors["base0D"]};
margin-right: 2px;
}}
#bat-label {{
color: #{colors["base05"]};
font-size: {font_size}px;
}}
#bat-label.battery-low {{
color: #{colors["base08"]};
font-weight: bold;
}}
/* Progress bars */
#cpu-progress-bar,
#ram-progress-bar,
#volume-progress-bar {{
color: transparent;
background-color: transparent;
}}
#cpu-progress-bar {{
border: solid 0px alpha(#{colors["base0E"]}, 0.8);
}}
#ram-progress-bar,
#volume-progress-bar {{
border: solid 0px #{colors["base0D"]};
}}
/* Widgets container */
#widgets-container {{
background-color: #{colors["base01"]};
padding: 2px;
border-radius: 16px;
}}
/* NixOS label */
#nixos-label {{
color: #{colors["base0D"]};
}}
/* Date time */
#date-time {{
color: #{colors["base05"]};
background-color: #{colors["base01"]};
padding: 4px 8px;
border-radius: 12px;
}}
#date-time-button {{
background: transparent;
border: none;
padding: 0;
margin: 0;
box-shadow: none;
}}
/* Generic popup styling */
.popup-window,
#calendar-popup,
#quick-menu {{
background-color: #{colors["base00"]};
border: solid 2px #{colors["base02"]};
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), 0 2px 8px rgba(0, 0, 0, 0.2);
animation: slide-down 200ms ease-out;
/* Add subtle inner glow for better depth perception */
outline: 1px solid rgba(255, 255, 255, 0.05);
outline-offset: -1px;
}}
@keyframes slide-down {{
from {{
opacity: 0;
margin-top: -20px;
}}
to {{
opacity: 1;
margin-top: 10px;
}}
}}
#calendar-title {{
color: #{colors["base05"]};
font-weight: bold;
font-size: {large_font}px;
margin-bottom: 8px;
}}
#events-box {{
background-color: #{colors["base00"]};
border: solid 1px #{colors["base02"]};
border-radius: 8px;
padding: 16px;
}}
#no-events {{
color: #{colors["base03"]};
}}
/* Calendar event items */
.event-item {{
border-radius: 6px;
padding: 8px 12px;
margin: 4px 0px;
transition: background-color 0.15s ease;
}}
#event-content {{
margin-left: 8px;
}}
.event-item.upcoming {{
background-color: #{colors["base01"]};
}}
.event-item.past {{
background-color: #{colors["base01"]};
opacity: 0.6;
}}
.event-title {{
font-weight: bold;
font-size: {font_size}px;
}}
.event-title.upcoming {{
color: #{colors["base05"]};
}}
.event-title.past {{
color: #{colors["base04"]};
}}
.event-time {{
font-size: {small_font}px;
}}
.event-time.upcoming {{
color: #{colors["base04"]};
}}
.event-time.past {{
color: #{colors["base03"]};
}}
.event-location {{
font-size: {small_font}px;
}}
.event-location.upcoming {{
color: #{colors["base03"]};
}}
.event-location.past {{
color: #{colors["base03"]};
opacity: 0.8;
}}
/* Tooltips */
tooltip {{
border: solid 2px;
border-color: #{colors["base02"]};
background-color: #{colors["base00"]};
color: #{colors["base05"]};
border-radius: 16px;
}}
tooltip>* {{
padding: 2px 4px;
}}
/* Workspaces */
#workspaces {{
background-color: #{colors["base01"]};
padding: 6px 6px;
border-radius: 16px;
}}
#workspaces>button {{
background-color: #{colors["base05"]};
}}
#workspaces>button.empty:not(.active):not(.visible) {{
background-color: #{colors["base03"]};
}}
#workspaces>button.visible:not(.active) {{
background-color: #{colors["base0E"]};
}}
#workspaces>button.active {{
background-color: #{colors["base0D"]};
}}
#workspaces>button.urgent {{
background-color: #{colors["base08"]};
}}
/* Workspace shown on a different monitor than this bar — dim it. */
#workspaces>button.foreign {{
opacity: 0.45;
}}
#workspaces>button>label {{
font-size: 0px;
}}
/* Compact MPRIS player */
#player-small {{
background-color: #{colors["base01"]};
padding: 6px;
border-radius: 100px;
}}
#compact-mpris-icon,
#compact-mpris-button {{
background: transparent;
border: none;
padding: 0 4px;
margin: 0;
box-shadow: none;
min-height: 0;
min-width: 0;
}}
#compact-mpris-button-icon,
#compact-mpris-fallback {{
color: #{colors["base05"]};
}}
#compact-mpris-button:hover #compact-mpris-button-icon {{
color: #{colors["base0D"]};
}}
#compact-mpris-fallback {{
opacity: 0.7;
}}
#compact-mpris-label {{
color: #{colors["base05"]};
font-size: {font_size}px;
margin: 0 6px;
}}
/* Quick Menu styling */
#quick-menu-container {{
background-color: #{colors["base00"]};
border-radius: 8px;
}}
#quick-menu-button {{
background: transparent;
border: none;
padding: 4px;
margin: 0;
box-shadow: none;
color: #{colors["base05"]};
}}
#quick-menu-button:hover {{
background-color: #{colors["base01"]};
border-radius: 8px;
}}
.quick-menu-item {{
border-radius: 6px;
transition: background-color 0.15s ease;
}}
.quick-menu-item:hover {{
background-color: #{colors["base01"]};
}}
.section-title {{
color: #{colors["base04"]};
font-weight: bold;
font-size: {small_font}px;
}}
/* Vinyl button styling */
#vinyl-button {{
background-color: transparent;
color: #{colors["base05"]};
border: none;
padding: 4px;
margin: 0px;
border-radius: 8px;
}}
#vinyl-button.active {{
background-color: #{colors["base0B"]};
color: #{colors["base00"]};
}}
#vinyl-icon {{
color: inherit;
}}
/* Toggle switch styling for quick menu */
.toggle-active {{
background-color: #{colors["base0B"]};
}}
.toggle-inactive {{
background-color: #{colors["base02"]};
}}
/* Launcher (FuzzyMenu — finder, app launcher, screenrec menu) */
#picker-box {{
background-color: #{colors["base00"]};
border: solid 1px #{colors["base02"]};
border-radius: 8px;
padding: 12px;
color: #{colors["base05"]};
}}
#search-entry {{
background-color: #{colors["base01"]};
color: #{colors["base05"]};
border: solid 1px #{colors["base02"]};
border-radius: 6px;
padding: 6px 10px;
}}
#viewport {{
background-color: #{colors["base00"]};
border-radius: 6px;
padding: 4px;
color: #{colors["base05"]};
}}
#viewport > * {{
background-color: #{colors["base01"]};
border-left: 3px solid transparent;
border-radius: 4px;
padding: 8px 12px;
margin-bottom: 4px;
transition: background-color 80ms ease, border-color 80ms ease;
}}
#viewport > *.selected {{
background-color: alpha(#{colors["base0D"]}, 0.28);
border-left-color: #{colors["base0D"]};
color: #{colors["base05"]};
font-weight: 600;
}}
#viewport > *.selected label {{
color: #{colors["base05"]};
}}
#app-icon {{
margin-right: 4px;
}}
#app-name {{
color: #{colors["base05"]};
font-weight: 500;
}}
#app-generic {{
color: #{colors["base04"]};
font-size: {small_font}px;
}}
"""
# Write to temporary file
temp_fd, temp_path = tempfile.mkstemp(suffix=".css", prefix="stylix_")
try:
with os.fdopen(temp_fd, "w") as f:
f.write(css_content)
return temp_path
except Exception:
os.close(temp_fd)
return None
def get_stylix_css_path():
"""Get the path to the Stylix CSS file"""
return generate_stylix_css()

85
sims/modules/vinyl.py Normal file
View File

@@ -0,0 +1,85 @@
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.core.service import Property
import subprocess
class VinylButton(Button):
@Property(bool, "read-write", default_value=False)
def active(self) -> bool:
return self._active
@active.setter
def active(self, value: bool):
self._active = value
# Update appearance based on state
self._update_appearance()
# Execute shell command based on new state
if self._active:
self._execute_active_command()
else:
self._execute_inactive_command()
def __init__(
self,
active_command=[
"pw-link alsa_input.pci-0000_12_00.6.analog-stereo:capture_FL alsa_output.usb-BEHRINGER_UMC1820_A71E9E3E-00.multichannel-output:playback_AUX0",
"pw-link alsa_input.pci-0000_12_00.6.analog-stereo:capture_FR alsa_output.usb-BEHRINGER_UMC1820_A71E9E3E-00.multichannel-output:playback_AUX1",
],
inactive_command=[
"pw-link -d alsa_input.pci-0000_12_00.6.analog-stereo:capture_FL alsa_output.usb-BEHRINGER_UMC1820_A71E9E3E-00.multichannel-output:playback_AUX0",
"pw-link -d alsa_input.pci-0000_12_00.6.analog-stereo:capture_FR alsa_output.usb-BEHRINGER_UMC1820_A71E9E3E-00.multichannel-output:playback_AUX1 ",
],
**kwargs,
):
# Initialize properties
self._active = False
self._active_command = active_command
self._inactive_command = inactive_command
# Set up the icon using GTK icon
self.icon = Image(
icon_name="folder-music-symbolic",
icon_size=16,
name="vinyl-icon",
)
# Initialize the Button with the icon as child
super().__init__(
name="vinyl-button",
child=self.icon,
on_clicked=self._on_clicked,
**kwargs,
)
# Initialize appearance
self._update_appearance()
def _update_appearance(self):
"""Update CSS class based on active state"""
if self._active:
self.add_style_class("active")
else:
self.remove_style_class("active")
def _on_clicked(self, button=None):
"""Handle button click event"""
# Toggle active state
self.active = not self.active
def _execute_active_command(self):
"""Execute shell command when button is activated"""
try:
for cmd in self._active_command:
subprocess.Popen(cmd, shell=True)
except Exception as e:
print(f"Error executing active command: {e}")
def _execute_inactive_command(self):
"""Execute shell command when button is deactivated"""
try:
for cmd in self._inactive_command:
subprocess.Popen(cmd, shell=True)
except Exception as e:
print(f"Error executing inactive command: {e}")

48
sims/modules/volume.py Normal file
View File

@@ -0,0 +1,48 @@
from fabric.widgets.circularprogressbar import CircularProgressBar
from fabric.audio.service import Audio
from fabric.widgets.eventbox import EventBox
from fabric.widgets.box import Box
from fabric.widgets.overlay import Overlay
from fabric.widgets.label import Label
class VolumeWidget(Box):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.audio = Audio()
self.progress_bar = CircularProgressBar(
name="volume-progress-bar", pie=True, size=24
)
self.event_box = EventBox(
events="scroll",
child=Overlay(
child=self.progress_bar,
overlays=Label(
label="",
style="margin: 0px 6px 0px 0px; font-size: 12px", # to center the icon glyph
),
),
)
self.audio.connect("notify::speaker", self.on_speaker_changed)
self.event_box.connect("scroll-event", self.on_scroll)
self.add(self.event_box)
def on_scroll(self, _, event):
match event.direction:
case 0:
self.audio.speaker.volume += 8
case 1:
self.audio.speaker.volume -= 8
return
def on_speaker_changed(self, *_):
if not self.audio.speaker:
return
self.progress_bar.value = self.audio.speaker.volume / 100
self.audio.speaker.bind(
"volume", "value", self.progress_bar, lambda _, v: v / 100
)
return

View File

@@ -0,0 +1,9 @@
from sims.modules.launcher import FuzzyMenu, WindowProvider
def FuzzyWindowFinder(monitor: int = 0) -> FuzzyMenu:
return FuzzyMenu(
provider=WindowProvider(),
monitor=monitor,
placeholder="Search Windows...",
)

72
sims/services/battery.py Normal file
View File

@@ -0,0 +1,72 @@
import psutil
from fabric.core.service import Service, Signal
from fabric.utils import invoke_repeater
class BatteryService(Service):
@Signal
def battery_changed(self, percent: float, charging: bool) -> None:
"""Signal emitted when battery status changes"""
pass
def __init__(self, update_interval=10000, **kwargs): # Check every 10 seconds
super().__init__(**kwargs)
self._percent = 0.0
self._charging = False
self._update_interval = update_interval
self._timer_id = None
# Start periodic updates
self.start_monitoring()
def start_monitoring(self):
"""Start monitoring battery status"""
if self._timer_id is None:
# Get initial values
self._update_battery()
# Set up periodic updates
self._timer_id = invoke_repeater(self._update_interval, self._update_battery)
def stop_monitoring(self):
"""Stop monitoring battery status"""
if self._timer_id is not None:
from gi.repository import GLib
GLib.source_remove(self._timer_id)
self._timer_id = None
def _update_battery(self):
"""Update battery status and emit signal if changed"""
try:
# Use the same pattern as the example
bat_sen = psutil.sensors_battery()
if not bat_sen:
# No battery sensor available (desktop systems)
new_percent = 100.0 # Assume plugged in
new_charging = True
else:
new_percent = bat_sen.percent
new_charging = bat_sen.power_plugged
# Only emit signal if values changed
percent_changed = abs(new_percent - self._percent) > 0.5
charging_changed = new_charging != self._charging
if percent_changed or charging_changed:
self._percent = new_percent
self._charging = new_charging
self.battery_changed(new_percent, new_charging)
except Exception as e:
print(f"Error updating battery status: {e}")
return True # Keep the timer running
@property
def percent(self):
"""Get current battery percentage"""
return self._percent
@property
def charging(self):
"""Get current charging status"""
return self._charging

55
sims/services/fenster.py Normal file
View File

@@ -0,0 +1,55 @@
"""
Fenster/Sway IPC connection helper.
Provides a singleton I3 connection configured for Fenster's SWAYSOCK.
"""
import os
from sims.services.i3 import I3, I3MessageType
_connection: I3 | None = None
def get_i3_connection() -> I3:
"""Get the singleton I3 connection, configured for Fenster."""
global _connection
if _connection is None:
swaysock = os.environ.get("SWAYSOCK")
if swaysock:
I3.SOCKET_PATH = swaysock
elif not I3.SOCKET_PATH:
runtime_dir = os.environ.get(
"XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"
)
fallback = os.path.join(runtime_dir, "fenster.sock")
if os.path.exists(fallback):
I3.SOCKET_PATH = fallback
_connection = I3()
return _connection
def focused_output_index() -> int:
"""Index of the currently focused output in active GET_OUTPUTS order.
Matches the indexing main.spawn_bars uses for `monitor=` so layer-shell
windows opened with the same index land on the focused output. Returns 0
on any IPC failure or if the focused output cannot be located.
"""
ws_reply = I3.send_command("", I3MessageType.GET_WORKSPACES)
if not (ws_reply.is_ok and isinstance(ws_reply.reply, list)):
return 0
focused_output = next(
(ws.get("output") for ws in ws_reply.reply if ws.get("focused")),
None,
)
if not focused_output:
return 0
out_reply = I3.send_command("", I3MessageType.GET_OUTPUTS)
if not (out_reply.is_ok and isinstance(out_reply.reply, list)):
return 0
active = [o for o in out_reply.reply if o.get("active")]
for i, o in enumerate(active):
if o.get("name") == focused_output:
return i
return 0

245
sims/services/i3.py Normal file
View File

@@ -0,0 +1,245 @@
"""Vendored i3/sway IPC client (originally from fabric.i3).
Maintained in-tree so we can extend `I3MessageType` with fenster-specific
event types without monkey-patching upstream fabric. To add a new event:
1. Add a new `*_EVENT` member to `I3MessageType` with the wire type number
(`0x80000000 | <event_id>`).
2. Make sure fenster broadcasts it under the matching atom and accepts the
subscription string (the auto-derived name = enum-name lowercased without
`_event`).
3. Subscribers connect to `event::<name>` (or `event::<name>::<change>` for
sub-events).
"""
import os
import json
import socket
import struct
from enum import IntEnum
from loguru import logger
from typing import ParamSpec
from dataclasses import dataclass
from fabric.core.service import Service, Signal, Property
from fabric.utils.helpers import exec_shell_command, idle_add
from gi.repository import GLib
P = ParamSpec("P")
SOCKET_MAGIC = b"i3-ipc"
# exceptions
class I3Error(Exception): ...
class I3SocketError(I3Error): ...
class I3SocketNotFoundError(I3SocketError): ...
class I3MessageType(IntEnum):
# commands
COMMAND = 0
GET_WORKSPACES = 1
SUBSCRIBE = 2
GET_OUTPUTS = 3
GET_TREE = 4
GET_MARKS = 5
GET_BAR_CONFIG = 6
GET_VERSION = 7
GET_BINDING_MODES = 8
GET_CONFIG = 9
SEND_TICK = 10
SYNC = 11
GET_BINDING_STATE = 12
# sway only
GET_INPUTS = 100
GET_SEATS = 101
# events
WORKSPACE_EVENT = 0x80000000
OUTPUT_EVENT = 0x80000001
MODE_EVENT = 0x80000002
WINDOW_EVENT = 0x80000003
BARCONFIG_UPDATE_EVENT = 0x80000004
BINDING_EVENT = 0x80000005
SHUTDOWN_EVENT = 0x80000006
TICK_EVENT = 0x80000007
# sway only
BAR_STATE_UPDATE_EVENT = 0x80000014
INPUT_EVENT = 0x80000015
# fenster extensions (event id 100+)
SMART_CORNERS_EVENT = 0x80000064
@dataclass(frozen=True)
class I3Event:
name: str
"the name of the received event"
data: dict
"the json data gotten from event's body"
raw_data: bytes
"the raw json data"
@dataclass(frozen=True)
class I3Reply:
command: str
"the passed in command"
reply: dict | list
"the raw reply from i3/sway as a dict or list"
is_ok: bool
"this indicates if the ran command has returned a success message"
class I3(Service):
"""
A connection to the i3/Sway's IPC socket.
This can be used for sending commands and receiving events.
"""
SOCKET_PATH: str | None = None
@Property(bool, "readable", "is-ready", default_value=False)
def ready(self) -> bool:
return self._ready
@Signal("event", flags="detailed")
def event(self, event: object): ...
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._ready = False
self.lookup_socket()
self.event_socket_thread = GLib.Thread.new(
"i3-socket-service",
self.event_socket_task, # type: ignore
self.SOCKET_PATH,
)
self._ready = True
self.notify("ready")
@staticmethod
def lookup_socket() -> str:
if I3.SOCKET_PATH:
return I3.SOCKET_PATH
for cmd in ("sway", "i3"):
path = exec_shell_command(f"{cmd} --get-socketpath")
if not path or not (path := path.strip()) or not os.path.exists(path):
continue
I3.SOCKET_PATH = path
return I3.SOCKET_PATH
raise I3SocketNotFoundError(
"Couldn't find i3 or Sway socket, is either of them running?"
)
@staticmethod
def pack(message_type: I3MessageType, payload: str = "") -> bytes:
payload_bytes = payload.encode()
header = struct.pack("<II", len(payload_bytes), message_type.value)
return SOCKET_MAGIC + header + payload_bytes
@staticmethod
def unpack(connection: socket.socket) -> tuple[int, str]:
header = connection.recv(14)
if len(header) != 14:
raise I3SocketError("Failed to read IPC header")
magic, length, message_type = struct.unpack("<6sII", header)
if magic != SOCKET_MAGIC:
raise I3SocketError(f"Invalid IPC magic string ({magic}). Report this!")
return message_type, connection.recv(length).decode()
@staticmethod
def send_command(
command: str, message_type: I3MessageType = I3MessageType.COMMAND
) -> I3Reply:
"""
Sends a command to the i3/sway socket.
example usage:
```python
# next workspace...
I3.send_command("workspace next")
```
:param command: The command to send.
:type command: str
:param message_type: The type of message to send.
:type message_type: I3MessageType, optional
:return: A reply object containing the data from i3/sway.
:rtype: I3Reply
"""
reply_data = {}
is_ok = False
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.connect(I3.lookup_socket())
sock.sendall(I3.pack(message_type, command))
_, payload = I3.unpack(sock)
reply_data = json.loads(payload)
# results for any GET_* command is considered ok
# other commands a success reply is a list of dicts with {"success": True}
if (message_type != I3MessageType.COMMAND) or (
isinstance(reply_data, list)
and reply_data
and reply_data[0].get("success")
):
is_ok = True
except Exception as e:
logger.error(
f"[I3Service] got error while sending command via socket ({e})"
)
return I3Reply(command=command, reply=reply_data, is_ok=is_ok)
def event_socket_task(self, socket_addr: str) -> bool:
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.connect(socket_addr)
# subscribe to all events
sock.sendall(
self.pack(
I3MessageType.SUBSCRIBE,
json.dumps(
[
evnt_name.replace("_event", "")
for mt in I3MessageType
if (evnt_name := mt.name.lower()).endswith("_event")
]
),
)
)
self.unpack(sock) # success reply
while True:
idle_add(self.handle_raw_event, *self.unpack(sock))
except Exception as e:
logger.warning(f"[I3Service] events socket thread ended with an error: {e}")
return False
def handle_raw_event(self, message_type: int, payload: str):
event_data = json.loads(payload)
event_name = I3MessageType(message_type).name.lower().replace("_event", "")
if "change" in event_data: # subevents
event_name = f"{event_name}::{event_data['change']}"
return self.emit(
f"event::{event_name}",
I3Event(event_name, event_data, payload.encode()),
)

289
sims/services/mpris.py Normal file
View File

@@ -0,0 +1,289 @@
# Standard library imports
import contextlib
# Third-party imports
import gi
from gi.repository import GLib # type: ignore
from loguru import logger
# Fabric imports
from fabric.core.service import Property, Service, Signal
from fabric.utils import bulk_connect
class PlayerctlImportError(ImportError):
"""An error to raise when playerctl is not installed."""
def __init__(self, *args):
super().__init__(
"Playerctl is not installed, please install it first",
*args,
)
# Try to import Playerctl, raise custom error if not available
try:
gi.require_version("Playerctl", "2.0")
from gi.repository import Playerctl
except ValueError:
raise PlayerctlImportError
class MprisPlayer(Service):
"""A service to manage a mpris player."""
@Signal
def exit(self, value: bool) -> bool: ...
@Signal
def changed(self) -> None: ...
def __init__(
self,
player: Playerctl.Player,
**kwargs,
):
self._signal_connectors: dict = {}
self._player: Playerctl.Player = player
super().__init__(**kwargs)
for sn in ["playback-status", "loop-status", "shuffle", "volume", "seeked"]:
self._signal_connectors[sn] = self._player.connect(
sn,
lambda *args, sn=sn: self.notifier(sn, args),
)
self._signal_connectors["exit"] = self._player.connect(
"exit",
self.on_player_exit,
)
self._signal_connectors["metadata"] = self._player.connect(
"metadata",
lambda *args: self.update_status(),
)
GLib.idle_add(lambda *args: self.update_status_once())
def update_status(self):
# schedule each notifier asynchronously.
def notify_property(prop):
if self.get_property(prop) is not None:
self.notifier(prop)
for prop in [
"metadata",
"title",
"artist",
"arturl",
"length",
]:
GLib.idle_add(lambda p=prop: (notify_property(p), False))
for prop in [
"can-seek",
"can-pause",
"can-shuffle",
"can-go-next",
"can-go-previous",
]:
GLib.idle_add(lambda p=prop: (self.notifier(p), False))
def update_status_once(self):
# schedule notifier calls for each property
def notify_all():
for prop in self.list_properties(): # type: ignore
self.notifier(prop.name)
return False
GLib.idle_add(notify_all, priority=GLib.PRIORITY_DEFAULT_IDLE)
def notifier(self, name: str, args=None):
def notify_and_emit():
self.notify(name)
self.emit("changed")
return False
GLib.idle_add(notify_and_emit, priority=GLib.PRIORITY_DEFAULT_IDLE)
def on_player_exit(self, player):
for id in list(self._signal_connectors.values()):
with contextlib.suppress(Exception):
self._player.disconnect(id)
del self._signal_connectors
GLib.idle_add(lambda: (self.emit("exit", True), False))
del self._player
def toggle_shuffle(self):
if self.can_shuffle:
# schedule the shuffle toggle in the GLib idle loop
GLib.idle_add(lambda: (setattr(self, "shuffle", not self.shuffle), False))
# else do nothing
def play_pause(self):
if self.can_pause:
GLib.idle_add(lambda: (self._player.play_pause(), False))
def next(self):
if self.can_go_next:
GLib.idle_add(lambda: (self._player.next(), False))
def previous(self):
if self.can_go_previous:
GLib.idle_add(lambda: (self._player.previous(), False))
# Properties
@Property(str, "readable")
def player_name(self) -> int:
return self._player.get_property("player-name") # type: ignore
@Property(int, "read-write", default_value=0)
def position(self) -> int:
return self._player.get_property("position") # type: ignore
@position.setter
def position(self, new_pos: int):
self._player.set_position(new_pos)
@Property(object, "readable")
def metadata(self) -> dict:
return self._player.get_property("metadata") # type: ignore
@Property(str or None, "readable")
def arturl(self) -> str | None:
if "mpris:artUrl" in self.metadata.keys(): # type: ignore # noqa: SIM118
return self.metadata["mpris:artUrl"] # type: ignore
return None
@Property(str or None, "readable")
def length(self) -> str | None:
if "mpris:length" in self.metadata.keys(): # type: ignore # noqa: SIM118
return self.metadata["mpris:length"] # type: ignore
return None
@Property(str, "readable")
def artist(self) -> str:
artist = self._player.get_artist() # type: ignore
if isinstance(artist, (list, tuple)):
return ", ".join(artist)
return artist
@Property(str, "readable")
def album(self) -> str:
return self._player.get_album() # type: ignore
@Property(str, "readable")
def title(self):
return self._player.get_title()
@Property(bool, "read-write", default_value=False)
def shuffle(self) -> bool:
return self._player.get_property("shuffle") # type: ignore
@shuffle.setter
def shuffle(self, do_shuffle: bool):
self.notifier("shuffle")
return self._player.set_shuffle(do_shuffle)
@Property(str, "readable")
def playback_status(self) -> str:
return {
Playerctl.PlaybackStatus.PAUSED: "paused",
Playerctl.PlaybackStatus.PLAYING: "playing",
Playerctl.PlaybackStatus.STOPPED: "stopped",
}.get(self._player.get_property("playback_status"), "unknown") # type: ignore
@Property(str, "read-write")
def loop_status(self) -> str:
return {
Playerctl.LoopStatus.NONE: "none",
Playerctl.LoopStatus.TRACK: "track",
Playerctl.LoopStatus.PLAYLIST: "playlist",
}.get(self._player.get_property("loop_status"), "unknown") # type: ignore
@loop_status.setter
def loop_status(self, status: str):
loop_status = {
"none": Playerctl.LoopStatus.NONE,
"track": Playerctl.LoopStatus.TRACK,
"playlist": Playerctl.LoopStatus.PLAYLIST,
}.get(status)
self._player.set_loop_status(loop_status) if loop_status else None
@Property(bool, "readable", default_value=False)
def can_go_next(self) -> bool:
return self._player.get_property("can_go_next") # type: ignore
@Property(bool, "readable", default_value=False)
def can_go_previous(self) -> bool:
return self._player.get_property("can_go_previous") # type: ignore
@Property(bool, "readable", default_value=False)
def can_seek(self) -> bool:
return self._player.get_property("can_seek") # type: ignore
@Property(bool, "readable", default_value=False)
def can_pause(self) -> bool:
return self._player.get_property("can_pause") # type: ignore
@Property(bool, "readable", default_value=False)
def can_shuffle(self) -> bool:
try:
self._player.set_shuffle(self._player.get_property("shuffle"))
return True
except Exception:
return False
@Property(bool, "readable", default_value=False)
def can_loop(self) -> bool:
try:
self._player.set_shuffle(self._player.get_property("shuffle"))
return True
except Exception:
return False
class MprisPlayerManager(Service):
"""A service to manage mpris players."""
@Signal
def player_appeared(self, player: Playerctl.Player) -> Playerctl.Player: ...
@Signal
def player_vanished(self, player_name: str) -> str: ...
def __init__(
self,
**kwargs,
):
self._manager = Playerctl.PlayerManager.new()
bulk_connect(
self._manager,
{
"name-appeared": self.on_name_appeard,
"name-vanished": self.on_name_vanished,
},
)
self.add_players()
super().__init__(**kwargs)
def on_name_appeard(self, manager, player_name: Playerctl.PlayerName):
logger.info(f"[MprisPlayer] {player_name.name} appeared")
try:
new_player = Playerctl.Player.new_from_name(player_name)
except GLib.Error as e:
logger.warning(f"[MprisPlayer] could not attach to {player_name.name}: {e}")
return
manager.manage_player(new_player)
self.emit("player-appeared", new_player) # type: ignore
def on_name_vanished(self, manager, player_name: Playerctl.PlayerName):
logger.info(f"[MprisPlayer] {player_name.name} vanished")
self.emit("player-vanished", player_name.name) # type: ignore
def add_players(self):
for player in self._manager.get_property("player-names"): # type: ignore
try:
self._manager.manage_player(Playerctl.Player.new_from_name(player)) # type: ignore
except GLib.Error as e:
logger.warning(f"[MprisPlayer] could not attach to {getattr(player, 'name', player)}: {e}")
@Property(object, "readable")
def players(self):
return self._manager.get_property("players") # type: ignore

View File

@@ -0,0 +1,106 @@
"""In-memory notification history.
Subscribes to a fabric Notifications service and snapshots each incoming
notification before fabric drops it on close. Snapshots scale image pixbufs
down to a bounded edge so a flood of high-res previews can't balloon memory.
"""
import time
from collections import deque
from dataclasses import dataclass
from fabric.core.service import Service, Signal
from fabric.notifications import Notification, Notifications
from gi.repository import GdkPixbuf
@dataclass
class HistoryEntry:
id: int
summary: str
body: str
urgency: int
timestamp: float
pixbuf: GdkPixbuf.Pixbuf | None
def _scale_pixbuf(
pixbuf: GdkPixbuf.Pixbuf | None, max_edge: int
) -> GdkPixbuf.Pixbuf | None:
if pixbuf is None:
return None
w, h = pixbuf.get_width(), pixbuf.get_height()
if w <= max_edge and h <= max_edge:
return pixbuf
scale = max_edge / max(w, h)
return pixbuf.scale_simple(
max(1, int(w * scale)),
max(1, int(h * scale)),
GdkPixbuf.InterpType.BILINEAR,
)
class NotificationHistoryService(Service):
@Signal
def changed(self) -> None: ...
def __init__(
self,
notifications: Notifications,
history_size: int = 50,
image_max_px: int = 128,
):
super().__init__()
self._entries: deque[HistoryEntry] = deque(maxlen=history_size)
self._image_max_px = image_max_px
self._unseen_count = 0
notifications.connect("notification-added", self._on_added)
def _on_added(self, service: Notifications, nid: int) -> None:
notification: Notification | None = service.get_notification_from_id(nid)
if notification is None:
return
self._entries.appendleft(
HistoryEntry(
id=nid,
summary=notification.summary or "",
body=notification.body or "",
urgency=notification.urgency,
timestamp=time.time(),
pixbuf=_scale_pixbuf(
notification.image_pixbuf, self._image_max_px
),
)
)
self._unseen_count += 1
self.changed()
@property
def entries(self) -> list[HistoryEntry]:
return list(self._entries)
@property
def unseen_count(self) -> int:
return self._unseen_count
def mark_all_seen(self) -> None:
if self._unseen_count == 0:
return
self._unseen_count = 0
self.changed()
def remove(self, entry_id: int) -> None:
before = len(self._entries)
self._entries = deque(
(e for e in self._entries if e.id != entry_id),
maxlen=self._entries.maxlen,
)
if len(self._entries) != before:
self.changed()
def clear(self) -> None:
if not self._entries:
return
self._entries.clear()
self._unseen_count = 0
self.changed()

230
sims/services/screenrec.py Normal file
View File

@@ -0,0 +1,230 @@
"""wl-screenrec process manager.
Owns the wl-screenrec subprocess so the bar reflects real recording state
without polling. Survives bar restarts via orphan adoption.
"""
import os
import signal
import subprocess
import time
from datetime import datetime
from typing import Literal
from fabric.core.service import Service, Signal
from sims.services.i3 import I3, I3MessageType
from gi.repository import GLib
from loguru import logger
Destination = Literal["videos", "clipboard"]
class ScreenrecService(Service):
@Signal
def recording_changed(self, recording: bool) -> None: ...
def __init__(self, output_dir: str = "~/Videos/wl-screenrec"):
super().__init__()
self._output_dir = os.path.expanduser(output_dir)
self._proc: subprocess.Popen | None = None
self._adopted_pid: int | None = None
self._started_at: float | None = None
self._output_path: str | None = None
self._destination: Destination | None = None
self._watch_id: int | None = None
self._adopt_orphan_if_running()
@property
def recording(self) -> bool:
return self._proc is not None or self._adopted_pid is not None
@property
def started_at(self) -> float | None:
return self._started_at
def start_monitor(self, dest: Destination = "videos", output: str | None = None) -> None:
if self.recording:
logger.warning("[Screenrec] start_monitor: already recording")
return
path = self._make_output_path(dest)
# Prefer an explicit output name when the caller passes one, but fenster's
# IPC reports synthetic names ("Unknown-XXXX") that wl-screenrec can't
# resolve. Fall back to the focused output's geometry, which works
# across i3/sway/fenster.
if output and not output.startswith("Unknown-"):
self._spawn(["wl-screenrec", "-o", output, "-f", path], path, dest)
return
geom = self._focused_output_geometry()
if not geom:
logger.error("[Screenrec] no focused output found")
return
self._spawn(["wl-screenrec", "-g", geom, "-f", path], path, dest)
def start_region(self, dest: Destination = "videos") -> None:
if self.recording:
logger.warning("[Screenrec] start_region: already recording")
return
geom = self._slurp_region()
if not geom:
logger.info("[Screenrec] region selection cancelled")
return
path = self._make_output_path(dest)
self._spawn(["wl-screenrec", "-g", geom, "-f", path], path, dest)
def stop(self) -> None:
if self._proc is not None:
logger.info("[Screenrec] sending SIGINT to wl-screenrec")
try:
self._proc.send_signal(signal.SIGINT)
except ProcessLookupError:
self._on_exit(self._proc.pid, 0)
return
if self._adopted_pid is not None:
logger.info(f"[Screenrec] sending SIGINT to adopted pid {self._adopted_pid}")
try:
os.kill(self._adopted_pid, signal.SIGINT)
except ProcessLookupError:
pass
self._poll_adopted_until_gone()
def _spawn(self, argv: list[str], path: str, dest: Destination) -> None:
os.makedirs(os.path.dirname(path), exist_ok=True)
logger.info(f"[Screenrec] spawning: {' '.join(argv)}")
try:
self._proc = subprocess.Popen(
argv,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
except FileNotFoundError:
logger.error("[Screenrec] wl-screenrec not found on PATH")
return
self._output_path = path
self._destination = dest
self._started_at = time.monotonic()
self._watch_id = GLib.child_watch_add(
GLib.PRIORITY_DEFAULT, self._proc.pid, self._on_exit
)
self.recording_changed(True)
def _on_exit(self, pid: int, status: int) -> None:
logger.info(f"[Screenrec] wl-screenrec exited (pid={pid} status={status})")
path = self._output_path
dest = self._destination
self._reset_state()
if dest == "clipboard" and path and os.path.exists(path):
self._copy_to_clipboard(path)
self.recording_changed(False)
def _reset_state(self) -> None:
self._proc = None
self._adopted_pid = None
self._started_at = None
self._output_path = None
self._destination = None
if self._watch_id is not None:
try:
GLib.source_remove(self._watch_id)
except Exception:
pass
self._watch_id = None
def _copy_to_clipboard(self, path: str) -> None:
try:
with open(path, "rb") as f:
subprocess.Popen(
["wl-copy", "-t", "video/mp4"],
stdin=f,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
logger.info(f"[Screenrec] copied {path} to clipboard as video/mp4")
except FileNotFoundError:
logger.error("[Screenrec] wl-copy not found on PATH")
def _slurp_region(self) -> str | None:
try:
result = subprocess.run(
["slurp"], capture_output=True, text=True, check=False
)
except FileNotFoundError:
logger.error("[Screenrec] slurp not found on PATH")
return None
geom = result.stdout.strip()
return geom or None
def _focused_output(self) -> str | None:
reply = I3.send_command("", I3MessageType.GET_WORKSPACES)
if not (reply.is_ok and isinstance(reply.reply, list)):
return None
for ws in reply.reply:
if ws.get("focused"):
return ws.get("output")
return None
def _focused_output_geometry(self) -> str | None:
"""Return the focused output's geometry as 'X,Y WxH' (slurp format).
Used as a portable fallback when the IPC's output names aren't real
wl_output names (e.g. fenster reports 'Unknown-XXXX').
"""
reply = I3.send_command("", I3MessageType.GET_WORKSPACES)
if not (reply.is_ok and isinstance(reply.reply, list)):
return None
for ws in reply.reply:
if ws.get("focused"):
rect = ws.get("rect") or {}
x = rect.get("x")
y = rect.get("y")
w = rect.get("width")
h = rect.get("height")
if None in (x, y, w, h) or w <= 0 or h <= 0:
return None
return f"{x},{y} {w}x{h}"
return None
def _make_output_path(self, dest: Destination) -> str:
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
if dest == "clipboard":
tmp = os.path.join(GLib.get_tmp_dir(), f"sims-screenrec-{stamp}.mp4")
return tmp
return os.path.join(self._output_dir, f"{stamp}.mp4")
def _adopt_orphan_if_running(self) -> None:
try:
result = subprocess.run(
["pgrep", "-x", "wl-screenrec"], capture_output=True, text=True
)
except FileNotFoundError:
return
pid_str = result.stdout.strip().split("\n")[0] if result.stdout.strip() else ""
if not pid_str:
return
try:
self._adopted_pid = int(pid_str)
except ValueError:
return
logger.info(f"[Screenrec] adopted orphan wl-screenrec pid={self._adopted_pid}")
self._started_at = time.monotonic()
self.recording_changed(True)
def _poll_adopted_until_gone(self) -> None:
def check() -> bool:
if self._adopted_pid is None:
return False
try:
os.kill(self._adopted_pid, 0)
except ProcessLookupError:
logger.info("[Screenrec] adopted wl-screenrec finished")
self._reset_state()
self.recording_changed(False)
return False
return True
GLib.timeout_add(250, check)

View File

@@ -0,0 +1,49 @@
"""Smart-corners IPC subscriber.
Listens to fenster's `:smart_corners` event and emits a per-output signal
when the WM's smart-corners state flips. Caches the latest state per output
so widgets created after the event can ask for the current value.
"""
from fabric.core.service import Service, Signal
from loguru import logger
from sims.services.fenster import get_i3_connection
_service: "SmartCornersService | None" = None
class SmartCornersService(Service):
@Signal
def state_changed(self, output: str, active: bool) -> None:
"""Emitted when a fenster output flips smart-corners state."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._state: dict[str, bool] = {}
i3 = get_i3_connection()
i3.connect("event::smart_corners::active", self._on_event)
i3.connect("event::smart_corners::inactive", self._on_event)
def get(self, output: str) -> bool:
"""Latest known state for an output, or False if unseen."""
return self._state.get(output, False)
def _on_event(self, _i3, event):
change = event.data.get("change")
output = event.data.get("output")
if not isinstance(output, str) or change not in ("active", "inactive"):
logger.warning(f"[SmartCorners] unexpected event payload: {event.data!r}")
return
active = change == "active"
if self._state.get(output) == active:
return
self._state[output] = active
self.state_changed(output, active)
def get_smart_corners_service() -> SmartCornersService:
global _service
if _service is None:
_service = SmartCornersService()
return _service

View File

@@ -0,0 +1,66 @@
import psutil
from fabric.core.service import Service, Signal
from fabric.utils import invoke_repeater
class SystemStatsService(Service):
@Signal
def stats_changed(self, cpu_percent: float, memory_percent: float) -> None:
"""Signal emitted when system stats change"""
pass
def __init__(self, update_interval=3000, **kwargs):
super().__init__(**kwargs)
self._cpu_percent = 0.0
self._memory_percent = 0.0
self._update_interval = update_interval
self._timer_id = None
# Start periodic updates
self.start_monitoring()
def start_monitoring(self):
"""Start monitoring system stats"""
if self._timer_id is None:
# Get initial values
self._update_stats()
# Set up periodic updates
self._timer_id = invoke_repeater(self._update_interval, self._update_stats)
def stop_monitoring(self):
"""Stop monitoring system stats"""
if self._timer_id is not None:
from gi.repository import GLib
GLib.source_remove(self._timer_id)
self._timer_id = None
def _update_stats(self):
"""Update system stats and emit signal if changed"""
try:
new_cpu = psutil.cpu_percent()
new_memory = psutil.virtual_memory().percent
# Only emit signal if values changed significantly (reduce noise)
cpu_changed = abs(new_cpu - self._cpu_percent) > 1.0
memory_changed = abs(new_memory - self._memory_percent) > 1.0
if cpu_changed or memory_changed:
self._cpu_percent = new_cpu
self._memory_percent = new_memory
self.stats_changed(new_cpu / 100, new_memory / 100)
except Exception as e:
print(f"Error updating system stats: {e}")
return True # Keep the timer running
@property
def cpu_percent(self):
"""Get current CPU percentage"""
return self._cpu_percent / 100
@property
def memory_percent(self):
"""Get current memory percentage"""
return self._memory_percent / 100

130
sims/styles/bar.css Normal file
View File

@@ -0,0 +1,130 @@
#sims-inner {
padding: 4px;
border-bottom: solid 2px;
border-color: var(--border-color);
background-color: var(--window-bg);
border-radius: 0;
transition: border-radius 200ms ease;
}
#sims-inner.rounded-bottom {
border-radius: 0 0 28px 28px;
}
#center-container {
color: var(--foreground);
}
.active-window {
color: var(--foreground);
font-weight: bold;
}
#battery-widget {
background-color: var(--module-bg);
padding: 4px 8px;
border-radius: 4px;
}
#bat-icon {
color: var(--blue);
margin-right: 2px;
}
#bat-label {
color: var(--foreground);
font-size: 14px;
}
#bat-label.battery-low {
color: var(--red);
font-weight: bold;
}
#cpu-progress-bar,
#ram-progress-bar,
#volume-progress-bar {
color: transparent;
background-color: transparent
}
#cpu-progress-bar {
border: solid 0px alpha(var(--violet), 0.8);
}
#ram-progress-bar,
#volume-progress-bar {
border: solid 0px var(--blue);
}
#widgets-container {
background-color: var(--module-bg);
padding: 2px;
}
#player-small {
background-color: var(--module-bg);
padding: 6px;
border-radius: 100px;
}
#compact-mpris-icon,
#compact-mpris-button {
background: transparent;
border: none;
padding: 0 4px;
margin: 0;
box-shadow: none;
min-height: 0;
min-width: 0;
}
#compact-mpris-button-icon {
color: var(--foreground);
}
#compact-mpris-button:hover #compact-mpris-button-icon {
color: var(--blue);
}
#compact-mpris-fallback {
color: var(--foreground);
opacity: 0.7;
}
#compact-mpris-label {
color: var(--foreground);
font-size: 13px;
}
#nixos-label {
color: var(--blue);
}
#screenrec-widget {
background: transparent;
border: none;
padding: 0 6px;
margin: 0;
box-shadow: none;
}
#screenrec-dot {
color: #ff4444;
font-size: 14px;
}
#screenrec-elapsed {
font-size: 12px;
font-family: monospace;
}
tooltip {
border: solid 2px;
border-color: var(--border-color);
background-color: var(--window-bg);
}
tooltip>* {
padding: 2px 4px
}

60
sims/styles/calendar.css Normal file
View File

@@ -0,0 +1,60 @@
/* Calendar widget styling */
/* Date time button */
#date-time-button {
background: transparent;
border: none;
padding: 0;
margin: 0;
box-shadow: none;
}
#date-time {
color: var(--foreground);
background-color: var(--module-bg);
padding: 4px 8px;
border-radius: 12px;
}
/* Calendar event items */
.event-item {
border-radius: 8px;
padding: 8px 10px;
margin: 2px 0px;
background-color: var(--light-bg);
border: none;
transition: background-color 0.15s ease;
}
#event-content {
margin-left: 8px;
}
.event-title {
font-weight: bold;
color: var(--foreground);
}
.event-time {
color: var(--dark-fg);
}
.event-location {
color: var(--light-grey);
}
/* Current time indicator */
.current-time-indicator {
margin: 8px 0px;
padding: 4px 0px;
}
#current-time-label {
color: var(--blue);
font-weight: bold;
}
#current-time-line {
color: var(--blue);
font-weight: bold;
}

29
sims/styles/colors.css Normal file
View File

@@ -0,0 +1,29 @@
:vars {
--background: #17181C;
--mid-bg: #1E1F24;
--light-bg: #26272B;
--dark-grey: #333438;
--light-grey: #8F9093;
--dark-fg: #B0B1B4;
--mid-fg: #CBCCCE;
--foreground: #E4E5E7;
--pink: #FA3867;
--orange: #F3872F;
--gold: #FEBD16;
--lime: #3FD43B;
--turquoise: #47E7CE;
--blue: #53ADE1;
--violet: #AD60FF;
--red: #FC3F2C;
--window-bg: alpha(var(--background), 0.9);
--module-bg: alpha(var(--mid-bg), 0.8);
--border-color: var(--light-bg);
--ws-active: var(--blue);
--ws-visible: var(--violet);
--ws-inactive: var(--light-grey);
--ws-empty: var(--dark-grey);
--ws-hover: var(--turquoise);
--ws-urgent: var(--red);
}

92
sims/styles/launcher.css Normal file
View File

@@ -0,0 +1,92 @@
/* Shared styles for the fuzzy-menu launcher (window finder, app launcher,
screenrec menu, and any future provider built on FuzzyMenu).
Element IDs come from sims/modules/launcher/base.py. */
#picker-box {
padding: 12px;
background-color: rgba(40, 40, 40, 0.95);
border-radius: 8px;
font-family: sans-serif;
font-size: 14px;
color: white;
min-width: 720px;
}
#viewport {
padding: 8px;
background-color: rgba(30, 30, 30, 0.9);
border-radius: 6px;
font-family: sans-serif;
font-size: 14px;
color: white;
}
#viewport > * {
padding: 8px 12px;
margin-bottom: 4px;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.04);
border-left: 3px solid transparent;
transition: background-color 80ms ease, border-color 80ms ease;
}
#viewport > *.selected {
background-color: rgba(137, 180, 250, 0.28);
border-left-color: #89b4fa;
color: #ffffff;
font-weight: 600;
}
#viewport > *.selected label {
color: #ffffff;
}
/* Provider-specific tweaks (apps launcher) */
#app-icon {
margin-right: 4px;
}
#app-name {
font-weight: 500;
}
#app-generic {
font-size: 11px;
opacity: 0.6;
}
/* Provider-specific tweaks (notmuch search) */
#notmuch-text {
/* Let the date column hug the right edge */
margin-right: 8px;
}
#notmuch-subject {
font-weight: 500;
}
#notmuch-authors {
font-size: 11px;
opacity: 0.7;
}
#notmuch-date {
font-size: 11px;
opacity: 0.6;
}
#notmuch-saved-name {
font-weight: 500;
}
#notmuch-saved-query {
font-size: 11px;
opacity: 0.6;
font-family: monospace;
}
#notmuch-bare {
font-style: italic;
opacity: 0.7;
}

23
sims/styles/main.css Normal file
View File

@@ -0,0 +1,23 @@
@import url("./colors.css");
@import url("./workspaces.css");
@import url("./menu.css");
@import url("./vinyl.css");
@import url("./bar.css");
@import url("./launcher.css");
@import url("./calendar.css");
@import url("./notmuch.css");
@import url("./notifications.css");
/* unset so we can style everything from the ground up. */
* {
all: unset;
color: var(--foreground);
font-size: 16px;
font-family: "Jost*", sans-serif;
}
button {
background-size: 400% 400%;
}

38
sims/styles/menu.css Normal file
View File

@@ -0,0 +1,38 @@
#date-time,
menu>menuitem>label,
#date-time>label,
/* system tray */
#system-tray {
padding: 2px 4px;
background-color: var(--module-bg);
}
/* menu and menu items (written for the system tray) */
menu {
border: solid 2px;
border-radius: 10px;
border-color: var(--border-color);
background-color: var(--window-bg);
}
menu>menuitem {
border-radius: 0px;
background-color: var(--module-bg);
padding: 6px;
margin-left: 2px;
margin-right: 2px;
}
menu>menuitem:first-child {
margin-top: 1px;
border-radius: 8px 8px 0px 0px;
}
menu>menuitem:last-child {
margin-bottom: 1px;
border-radius: 0px 0px 8px 8px;
}
menu>menuitem:hover {
background-color: var(--pink);
}

View File

@@ -0,0 +1,179 @@
#notification {
padding: 0.8rem;
border: solid 1px var(--border-color);
border-radius: 1rem;
background-color: var(--mid-bg);
}
#notification .summary {
font-size: 18px;
font-weight: bold;
}
#notification .body {
color: var(--mid-fg);
font-weight: normal;
}
#notification button {
padding: 0.4rem 0.8rem;
font-weight: 600;
border-radius: 0.6rem;
background-color: var(--light-bg);
}
#notification button:hover {
background-color: var(--dark-grey);
}
#notification.urgency-low {
border-color: var(--dark-grey);
}
#notification.urgency-low .summary {
color: var(--mid-fg);
}
#notification.urgency-critical {
border-color: var(--red);
border-width: 2px;
}
#notification.urgency-critical .summary {
color: var(--red);
}
/* Control center side rail */
#control-center {
background-color: transparent;
}
#control-center-body {
background-color: var(--background);
border-left: solid 2px var(--border-color);
border-bottom: solid 2px var(--border-color);
border-bottom-left-radius: 28px;
padding: 50px 12px 12px 12px;
}
#control-center-header {
padding: 4px 8px 12px 8px;
border-bottom: solid 1px var(--border-color);
}
#control-center-title {
font-size: 18px;
font-weight: bold;
color: var(--foreground);
}
#control-center-close {
padding: 4px 8px;
border-radius: 12px;
background-color: var(--module-bg);
}
#control-center-close:hover {
background-color: var(--light-bg);
}
#control-center-sections {
padding: 8px 0;
}
#control-center-settings,
#control-center-calendar,
#control-center-notifications {
padding: 8px;
background-color: var(--module-bg);
border-radius: 12px;
}
#control-center-section-title {
font-size: 12px;
font-weight: bold;
color: var(--light-grey);
padding: 4px 4px 8px 4px;
}
#control-center-settings-row {
padding: 4px 4px;
}
#control-center-settings-label {
font-size: 14px;
color: var(--foreground);
}
#control-center-events {
padding: 0 4px;
}
#control-center-no-events {
color: var(--light-grey);
padding: 6px 4px;
}
#control-center-notifications-header {
padding: 0 4px 6px 4px;
}
#control-center-notifications-clear {
padding: 2px 10px;
border-radius: 8px;
background-color: var(--light-bg);
font-size: 12px;
}
#control-center-notifications-clear:hover {
background-color: var(--dark-grey);
}
#control-center-notifications-list {
padding: 0 4px;
}
#control-center-notifications-empty {
color: var(--light-grey);
padding: 8px 4px;
}
#notification-history-entry {
padding: 10px;
border: solid 1px var(--border-color);
border-radius: 0.75rem;
background-color: var(--light-bg);
}
#notification-history-entry .summary {
font-weight: bold;
}
#notification-history-entry .body {
color: var(--mid-fg);
}
#notification-history-entry .timestamp {
color: var(--light-grey);
font-size: 12px;
padding-left: 8px;
}
#notification-history-entry.urgency-critical {
border-color: var(--red);
}
#notification-history-entry.urgency-critical .summary {
color: var(--red);
}
#notification-history-dismiss {
padding: 2px;
border-radius: 0.5rem;
}
#notification-history-dismiss:hover {
background-color: var(--dark-grey);
}

53
sims/styles/notmuch.css Normal file
View File

@@ -0,0 +1,53 @@
/* Notmuch email widget styling */
#notmuch-widget {
background-color: var(--module-bg);
padding: 4px 8px;
border-radius: 12px;
transition: background-color 0.2s ease;
}
#notmuch-widget:hover {
background-color: var(--light-bg);
}
#notmuch-widget.has-unread {
background-color: var(--blue);
}
#notmuch-widget.has-unread:hover {
background-color: var(--turquoise);
}
#notmuch-widget.no-unread {
background-color: var(--module-bg);
}
#notmuch-widget.debt-warn {
background-color: var(--orange);
}
#notmuch-widget.debt-warn:hover {
background-color: var(--gold);
}
#notmuch-widget.debt-alarm {
background-color: var(--red);
}
#notmuch-widget.debt-alarm:hover {
background-color: var(--pink);
}
#unread-count {
color: var(--foreground);
font-size: 14px;
font-weight: bold;
min-width: 16px;
}
#notmuch-widget.has-unread #unread-count,
#notmuch-widget.debt-warn #unread-count,
#notmuch-widget.debt-alarm #unread-count {
color: var(--background);
}

29
sims/styles/vinyl.css Normal file
View File

@@ -0,0 +1,29 @@
/* Vinyl button styling */
#vinyl-button {
background-color: var(--module-bg);
padding: 4px 8px;
border-radius: 12px;
transition: background-color 0.2s ease;
}
#vinyl-button:hover {
background-color: var(--light-bg);
}
/* Active state styling */
#vinyl-button.active {
background-color: var(--pink);
}
#vinyl-button.active:hover {
background-color: var(--turquoise);
}
/* Icon styling */
#vinyl-icon {
color: var(--foreground);
}
#vinyl-button.active #vinyl-icon {
color: var(--background);
}

View File

@@ -0,0 +1,50 @@
#workspaces {
padding: 6px;
min-width: 0px;
background-color: var(--module-bg);
}
#workspaces>button {
padding: 8px;
transition: padding 0.05s steps(8), background-color 0.15s ease;
background-color: var(--ws-inactive);
border-radius: 100px;
}
#workspaces>button>label {
font-size: 0px;
}
#workspaces>button:hover {
background-color: var(--ws-hover);
}
#workspaces>button.empty {
background-color: var(--ws-empty);
}
#workspaces>button.visible {
background-color: var(--ws-visible);
}
#workspaces>button.active {
padding: 8px 32px;
background-color: var(--ws-active);
}
#workspaces>button.urgent {
background-color: var(--ws-urgent);
color: var(--foreground);
font-weight: bold;
animation: urgent-blink 1s infinite;
}
#workspaces>button.foreign {
opacity: 0.45;
}
@keyframes urgent-blink {
0% { opacity: 1.0; }
50% { opacity: 0.5; }
100% { opacity: 1.0; }
}

550
sims/utils/icons.py Normal file
View File

@@ -0,0 +1,550 @@
common_text_icons = {
"playing": "",
"paused": "",
"power": "",
"cpu": "",
"memory": "",
"storage": "󰋊",
"updates": "󱧘",
"thermometer": "",
}
distro_text_icons = {
"deepin": "",
"fedora": "",
"arch": "",
"nixos": "",
"debian": "",
"opensuse-tumbleweed": "",
"ubuntu": "",
"endeavouros": "",
"manjaro": "",
"popos": "",
"garuda": "",
"zorin": "",
"mxlinux": "",
"arcolinux": "",
"gentoo": "",
"artix": "",
"centos": "",
"hyperbola": "",
"kubuntu": "",
"mandriva": "",
"xerolinux": "",
"parabola": "",
"void": "",
"linuxmint": "",
"archlabs": "",
"devuan": "",
"freebsd": "",
"openbsd": "",
"slackware": "",
}
# sourced from wttr.in
weather_text_icons = {
"113": {"description": "Sunny", "icon": "󰖙"},
"116": {"description": "PartlyCloudy", "icon": "󰖕"},
"119": {"description": "Cloudy", "icon": "󰖐"},
"122": {"description": "VeryCloudy", "icon": "󰖕"},
"143": {"description": "Fog", "icon": "󰖑"},
"176": {"description": "LightShowers", "icon": "󰼳"},
"179": {"description": "LightSleetShowers", "icon": "󰼵"},
"182": {"description": "LightSleet", "icon": "󰙿"},
"185": {"description": "LightSleet", "icon": "󰙿"},
"200": {"description": "ThunderyShowers", "icon": "󰙾"},
"227": {"description": "LightSnow", "icon": "󰼴"},
"230": {"description": "HeavySnow", "icon": "󰼶"},
"248": {"description": "Fog", "icon": "󰖑"},
"260": {"description": "Fog", "icon": "󰖑"},
"263": {"description": "LightShowers", "icon": "󰼳"},
"266": {"description": "LightRain", "icon": "󰼳"},
"281": {"description": "LightSleet", "icon": "󰙿"},
"284": {"description": "LightSleet", "icon": "󰙿"},
"293": {"description": "LightRain", "icon": "󰼳"},
"296": {"description": "LightRain", "icon": "󰼳"},
"299": {"description": "HeavyShowers", "icon": "󰖖"},
"302": {"description": "HeavyRain", "icon": "󰖖"},
"305": {"description": "HeavyShowers", "icon": "󰖖"},
"308": {"description": "HeavyRain", "icon": "󰖖"},
"311": {"description": "LightSleet", "icon": "󰙿"},
"314": {"description": "LightSleet", "icon": "󰙿"},
"317": {"description": "LightSleet", "icon": "󰙿"},
"320": {"description": "LightSnow", "icon": "󰼴"},
"323": {"description": "LightSnowShowers", "icon": "󰼵"},
"326": {"description": "LightSnowShowers", "icon": "󰼵"},
"329": {"description": "HeavySnow", "icon": "󰼶"},
"332": {"description": "HeavySnow", "icon": "󰼶"},
"335": {"description": "HeavySnowShowers", "icon": "󰼵"},
"338": {"description": "HeavySnow", "icon": "󰼶"},
"350": {"description": "LightSleet", "icon": "󰙿"},
"353": {"description": "LightShowers", "icon": "󰼳"},
"356": {"description": "HeavyShowers", "icon": "󰖖"},
"359": {"description": "HeavyRain", "icon": "󰖖"},
"362": {"description": "LightSleetShowers", "icon": "󰼵"},
"365": {"description": "LightSleetShowers", "icon": "󰼵"},
"368": {"description": "LightSnowShowers", "icon": "󰼵"},
"371": {"description": "HeavySnowShowers", "icon": "󰼵"},
"374": {"description": "LightSleetShowers", "icon": "󰼵"},
"377": {"description": "LightSleet", "icon": "󰙿"},
"386": {"description": "ThunderyShowers", "icon": "󰙾"},
"389": {"description": "ThunderyHeavyRain", "icon": "󰙾"},
"392": {"description": "ThunderySnowShowers", "icon": "󰼶"},
"395": {"description": "HeavySnowShowers", "icon": "󰼵"},
}
weather_text_icons_v2 = {
"113": {
"description": "Sunny",
"icon": "󰖙",
"image": "clear-day",
"icon-night": "󰖙",
"image-night": "clear-night",
},
"116": {
"description": "PartlyCloudy",
"icon": "󰖕",
"image": "cloudy",
"icon-night": "󰖕",
"image-night": "cloudy",
},
"119": {
"description": "Cloudy",
"icon": "󰖐",
"image": "cloudy",
"icon-night": "󰖐",
"image-night": "cloudy",
},
"122": {
"description": "VeryCloudy",
"icon": "󰖕",
"image": "cloudy",
"icon-night": "󰖕",
"image-night": "cloudy",
},
"143": {
"description": "Fog",
"icon": "󰖑",
"image": "fog",
"icon-night": "󰖑",
"image-night": "fog",
},
"176": {
"description": "LightShowers",
"icon": "󰼳",
"image": "rain",
"icon-night": "󰼳",
"image-night": "rain",
},
"179": {
"description": "LightSleetShowers",
"icon": "󰼵",
"image": "sleet",
"icon-night": "󰼵",
"image-night": "sleet",
},
"182": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"185": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"200": {
"description": "ThunderyShowers",
"icon": "󰙾",
"image": "thunderstorms",
"icon-night": "󰙾",
"image-night": "thunderstorms",
},
"227": {
"description": "LightSnow",
"icon": "󰼴",
"image": "snow",
"icon-night": "󰼴",
"image-night": "snow",
},
"230": {
"description": "HeavySnow",
"icon": "󰼶",
"image": "snow",
"icon-night": "󰼶",
"image-night": "snow",
},
"248": {
"description": "Fog",
"icon": "󰖑",
"image": "fog",
"icon-night": "󰖑",
"image-night": "fog",
},
"260": {
"description": "Fog",
"icon": "󰖑",
"image": "fog",
"icon-night": "󰖑",
"image-night": "fog",
},
"263": {
"description": "LightShowers",
"icon": "󰼳",
"image": "rain",
"icon-night": "󰼳",
"image-night": "rain",
},
"266": {
"description": "LightRain",
"icon": "󰼳",
"image": "rain",
"icon-night": "󰼳",
"image-night": "rain",
},
"281": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"284": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"293": {
"description": "LightRain",
"icon": "󰼳",
"image": "rain",
"icon-night": "󰼳",
"image-night": "rain",
},
"296": {
"description": "LightRain",
"icon": "󰼳",
"image": "rain",
"icon-night": "󰼳",
"image-night": "rain",
},
"299": {
"description": "HeavyShowers",
"icon": "󰖖",
"image": "rain",
"icon-night": "󰖖",
"image-night": "rain",
},
"302": {
"description": "HeavyRain",
"icon": "󰖖",
"image": "rain",
"icon-night": "󰖖",
"image-night": "rain",
},
"305": {
"description": "HeavyShowers",
"icon": "󰖖",
"image": "rain",
"icon-night": "󰖖",
"image-night": "rain",
},
"308": {
"description": "HeavyRain",
"icon": "󰖖",
"image": "rain",
"icon-night": "󰖖",
"image-night": "rain",
},
"311": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"314": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"317": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"320": {
"description": "LightSnow",
"icon": "󰼴",
"image": "snow",
"icon-night": "󰼴",
"image-night": "snow",
},
"323": {
"description": "LightSnowShowers",
"icon": "󰼵",
"image": "snow",
"icon-night": "󰼵",
"image-night": "snow",
},
"326": {
"description": "LightSnowShowers",
"icon": "󰼵",
"image": "snow",
"icon-night": "󰼵",
"image-night": "snow",
},
"329": {
"description": "HeavySnow",
"icon": "󰼶",
"image": "snow",
"icon-night": "󰼶",
"image-night": "snow",
},
"332": {
"description": "HeavySnow",
"icon": "󰼶",
"image": "snow",
"icon-night": "󰼶",
"image-night": "snow",
},
"335": {
"description": "HeavySnowShowers",
"icon": "󰼵",
"image": "snow",
"icon-night": "󰼵",
"image-night": "snow",
},
"338": {
"description": "HeavySnow",
"icon": "󰼶",
"image": "snow",
"icon-night": "󰼶",
"image-night": "snow",
},
"350": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"353": {
"description": "LightShowers",
"icon": "󰼳",
"image": "rain",
"icon-night": "󰼳",
"image-night": "rain",
},
"356": {
"description": "HeavyShowers",
"icon": "󰖖",
"image": "rain",
"icon-night": "󰖖",
"image-night": "rain",
},
"359": {
"description": "HeavyRain",
"icon": "󰖖",
"image": "rain",
"icon-night": "󰖖",
"image-night": "rain",
},
"362": {
"description": "LightSleetShowers",
"icon": "󰼵",
"image": "sleet",
"icon-night": "󰼵",
"image-night": "sleet",
},
"365": {
"description": "HeavySleetShowers",
"icon": "󰼵",
"image": "sleet",
"icon-night": "󰼵",
"image-night": "sleet",
},
"368": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"371": {
"description": "HeavySleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
"374": {
"description": "HeavySnowShowers",
"icon": "󰼶",
"image": "snow",
"icon-night": "󰼶",
"image-night": "snow",
},
"377": {
"description": "LightSleet",
"icon": "󰙿",
"image": "sleet",
"icon-night": "󰙿",
"image-night": "sleet",
},
}
volume_text_icons = {
"overamplified": "󰕾",
"high": "󰕾",
"medium": "󰖀",
"low": "󰕿",
"muted": "󰝟",
}
volume_text_icons = {
"overamplified": "󰕾",
"high": "󰕾",
"medium": "󰖀",
"low": "󰕿",
"muted": "󰝟",
}
brightness_text_icons = {
"off": "", # lowest brightness
"low": "",
"medium": "",
"high": "", # highest brightness
}
icons = {
"missing": "image-missing-symbolic",
"nix": {
"nix": "nix-snowflake-symbolic",
},
"app": {
"terminal": "terminal-symbolic",
},
"fallback": {
"executable": "application-x-executable",
"notification": "dialog-information-symbolic",
"video": "video-x-generic-symbolic",
"audio": "audio-x-generic-symbolic",
},
"ui": {
"close": "window-close-symbolic",
"colorpicker": "color-select-symbolic",
"info": "info-symbolic",
"link": "external-link-symbolic",
"lock": "system-lock-screen-symbolic",
"menu": "open-menu-symbolic",
"refresh": "view-refresh-symbolic",
"search": "system-search-symbolic",
"settings": "emblem-system-symbolic",
"themes": "preferences-desktop-theme-symbolic",
"tick": "object-select-symbolic",
"time": "hourglass-symbolic",
"toolbars": "toolbars-symbolic",
"warning": "dialog-warning-symbolic",
"avatar": "avatar-default-symbolic",
"arrow": {
"right": "pan-end-symbolic",
"left": "pan-start-symbolic",
"down": "pan-down-symbolic",
"up": "pan-up-symbolic",
},
},
"audio": {
"mic": {
"muted": "microphone-disabled-symbolic",
"low": "microphone-sensitivity-low-symbolic",
"medium": "microphone-sensitivity-medium-symbolic",
"high": "microphone-sensitivity-high-symbolic",
},
"volume": {
"muted": "audio-volume-muted-symbolic",
"low": "audio-volume-low-symbolic",
"medium": "audio-volume-medium-symbolic",
"high": "audio-volume-high-symbolic",
"overamplified": "audio-volume-overamplified-symbolic",
},
"type": {
"headset": "audio-headphones-symbolic",
"speaker": "audio-speakers-symbolic",
"card": "audio-card-symbolic",
},
"mixer": "mixer-symbolic",
},
"powerprofile": {
"balanced": "power-profile-balanced-symbolic",
"power-saver": "power-profile-power-saver-symbolic",
"performance": "power-profile-performance-symbolic",
},
"battery": {
"charging": "battery-flash-symbolic",
"warning": "battery-empty-symbolic",
},
"bluetooth": {
"enabled": "bluetooth-active-symbolic",
"disabled": "bluetooth-disabled-symbolic",
},
"brightness": {
"indicator": "display-brightness-symbolic",
"keyboard": "keyboard-brightness-symbolic",
"screen": "display-brightness-symbolic",
},
"powermenu": {
"sleep": "weather-clear-night-symbolic",
"reboot": "system-reboot-symbolic",
"logout": "system-log-out-symbolic",
"shutdown": "system-shutdown-symbolic",
},
"recorder": {
"recording": "media-record-symbolic",
"stopped": "media-record-symbolic",
},
"notifications": {
"noisy": "org.gnome.Settings-notifications-symbolic",
"silent": "notifications-disabled-symbolic",
"message": "chat-bubbles-symbolic",
},
"trash": {
"full": "user-trash-full-symbolic",
"empty": "user-trash-symbolic",
},
"mpris": {
"shuffle": {
"enabled": "media-playlist-shuffle-symbolic",
"disabled": "media-playlist-consecutive-symbolic",
},
"loop": {
"none": "media-playlist-repeat-symbolic",
"track": "media-playlist-repeat-song-symbolic",
"playlist": "media-playlist-repeat-symbolic",
},
"playing": "media-playback-pause-symbolic",
"paused": "media-playback-start-symbolic",
"stopped": "media-playback-start-symbolic",
"prev": "media-skip-backward-symbolic",
"next": "media-skip-forward-symbolic",
},
"system": {
"cpu": "org.gnome.SystemMonitor-symbolic",
"ram": "drive-harddisk-solidstate-symbolic",
"temp": "temperature-symbolic",
},
"color": {
"dark": "dark-mode-symbolic",
"light": "light-mode-symbolic",
},
}

28
sims/utils/markup.py Normal file
View File

@@ -0,0 +1,28 @@
import re
from html import escape as html_escape
import gi
gi.require_version("Pango", "1.0")
from gi.repository import GLib, Pango
# Pango cannot render <img ...> from the freedesktop notification spec; strip it.
_IMG_RE = re.compile(r"<img\b[^>]*/?>", re.IGNORECASE)
def render_body_markup(body: str) -> tuple[str, bool]:
"""Return ``(text, is_markup)`` for a notification body.
If the body parses as Pango markup, ``text`` is the cleaned-up markup
string and ``is_markup`` is True. Otherwise ``text`` is the XML-escaped
plain text and ``is_markup`` is False.
"""
if not body:
return "", False
candidate = _IMG_RE.sub("", body)
try:
Pango.parse_markup(candidate, -1, "\0")
except GLib.Error:
return html_escape(body, quote=False), False
return candidate, True

0
sims/widgets/battery.py Normal file
View File

View File

@@ -0,0 +1,126 @@
import math
from typing import Literal
import cairo
import gi
from fabric.core.service import Property
from fabric.widgets.widget import Widget
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk, GdkPixbuf, Gtk # noqa: E402
class CircleImage(Gtk.DrawingArea, Widget):
"""A widget that displays an image in a circular shape with a 1:1 aspect ratio."""
@Property(int, "read-write")
def angle(self) -> int:
return self._angle
@angle.setter
def angle(self, value: int):
self._angle = value % 360
self.queue_draw()
def __init__(
self,
image_file: str | None = None,
pixbuf: GdkPixbuf.Pixbuf | None = None,
name: str | None = None,
visible: bool = True,
all_visible: bool = False,
style: str | None = None,
tooltip_text: str | None = None,
tooltip_markup: str | None = None,
h_align: Literal["fill", "start", "end", "center", "baseline"]
| Gtk.Align
| None = None,
v_align: Literal["fill", "start", "end", "center", "baseline"]
| Gtk.Align
| None = None,
h_expand: bool = False,
v_expand: bool = False,
size: int | None = None,
**kwargs,
):
Gtk.DrawingArea.__init__(self)
Widget.__init__(
self,
name=name,
visible=visible,
all_visible=all_visible,
style=style,
tooltip_text=tooltip_text,
tooltip_markup=tooltip_markup,
h_align=h_align,
v_align=v_align,
h_expand=h_expand,
v_expand=v_expand,
size=size,
**kwargs,
)
self.size = size if size is not None else 100 # Default size if not provided
self._angle = 0
self._orig_image: GdkPixbuf.Pixbuf | None = (
None # Original image for reprocessing
)
self._image: GdkPixbuf.Pixbuf | None = None
if image_file:
pix = GdkPixbuf.Pixbuf.new_from_file(image_file)
self._orig_image = pix
self._image = self._process_image(pix)
elif pixbuf:
self._orig_image = pixbuf
self._image = self._process_image(pixbuf)
self.connect("draw", self.on_draw)
def _process_image(self, pixbuf: GdkPixbuf.Pixbuf) -> GdkPixbuf.Pixbuf:
"""Crop the image to a centered square and scale it to the widgets size."""
width, height = pixbuf.get_width(), pixbuf.get_height()
if width != height:
square_size = min(width, height)
x_offset = (width - square_size) // 2
y_offset = (height - square_size) // 2
pixbuf = pixbuf.new_subpixbuf(x_offset, y_offset, square_size, square_size)
else:
square_size = width
if square_size != self.size:
pixbuf = pixbuf.scale_simple(
self.size, self.size, GdkPixbuf.InterpType.BILINEAR
)
return pixbuf
def on_draw(self, widget: "CircleImage", ctx: cairo.Context):
if self._image:
ctx.save()
# Create a circular clipping path
ctx.arc(self.size / 2, self.size / 2, self.size / 2, 0, 2 * math.pi)
ctx.clip()
# Rotate around the center of the square image
ctx.translate(self.size / 2, self.size / 2)
ctx.rotate(self._angle * math.pi / 180.0)
ctx.translate(-self.size / 2, -self.size / 2)
Gdk.cairo_set_source_pixbuf(ctx, self._image, 0, 0)
ctx.paint()
ctx.restore()
def set_image_from_file(self, new_image_file: str):
if not new_image_file:
return
pixbuf = GdkPixbuf.Pixbuf.new_from_file(new_image_file)
self._orig_image = pixbuf
self._image = self._process_image(pixbuf)
self.queue_draw()
def set_image_from_pixbuf(self, pixbuf: GdkPixbuf.Pixbuf):
if not pixbuf:
return
self._orig_image = pixbuf
self._image = self._process_image(pixbuf)
self.queue_draw()
def set_image_size(self, size: int):
self.size = size
if self._orig_image:
self._image = self._process_image(self._orig_image)
self.queue_draw()

240
sims/widgets/fenster.py Normal file
View File

@@ -0,0 +1,240 @@
"""
Fenster widgets for workspace and window management via sway IPC.
"""
from gi.repository import GLib
from sims.services.i3 import I3, I3Event, I3MessageType
from fabric.utils.helpers import bulk_connect
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from sims.services.fenster import get_i3_connection
class FensterWorkspaceButton(Button):
"""Button representing a single workspace"""
def __init__(
self,
workspace_num: int,
i3: I3 | None = None,
label: str | None = None,
**kwargs,
):
self._workspace_num = workspace_num
self._i3 = i3 or get_i3_connection()
display_label = label if label is not None else str(workspace_num)
super().__init__(
name=f"workspace-button-{workspace_num}",
child=Label(label=display_label),
on_clicked=self._on_clicked,
**kwargs,
)
self.add_style_class("workspace-button")
@property
def workspace_num(self) -> int:
return self._workspace_num
def _on_clicked(self, *args):
self._i3.send_command(f"workspace {self._workspace_num}")
def _toggle_class(self, name: str, on: bool):
if on:
self.add_style_class(name)
else:
self.remove_style_class(name)
def set_active(self, active: bool):
self._toggle_class("active", active)
def set_visible_other(self, visible: bool):
self._toggle_class("visible", visible)
def set_empty(self, empty: bool):
self._toggle_class("empty", empty)
def set_urgent(self, urgent: bool):
self._toggle_class("urgent", urgent)
def set_foreign(self, foreign: bool):
self._toggle_class("foreign", foreign)
class FensterWorkspaces(Box):
"""Container widget showing a fixed set of workspace bubbles (1..N)."""
def __init__(
self,
output: str | None = None,
i3: I3 | None = None,
buttons_factory=None,
workspace_count: int = 9,
**kwargs,
):
super().__init__(
name=kwargs.pop("name", "workspaces"),
spacing=kwargs.pop("spacing", 4),
orientation="h",
**kwargs,
)
self._output = output
self._workspace_count = workspace_count
self._i3 = i3 or get_i3_connection()
self._buttons_factory = buttons_factory or self._default_button_factory
self._buttons: dict[int, FensterWorkspaceButton] = {}
self._refresh_pending = False
# Pre-create one button per workspace slot so position N always means workspace N.
for n in range(1, workspace_count + 1):
button = self._buttons_factory(n)
self._buttons[n] = button
self.add(button)
bulk_connect(
self._i3,
{
"event::workspace::focus": self._on_event,
"event::workspace::init": self._on_event,
"event::workspace::empty": self._on_event,
"event::workspace::urgent": self._on_event,
"event::workspace::move": self._on_event,
"event::window::focus": self._on_event,
"event::window::new": self._on_event,
"event::window::close": self._on_event,
},
)
if self._i3.ready:
# Initial state is already current — no need to defer.
self._refresh_workspaces()
else:
self._i3.connect("notify::ready", lambda *_: self._schedule_refresh())
def _default_button_factory(self, workspace_num: int) -> FensterWorkspaceButton:
return FensterWorkspaceButton(workspace_num=workspace_num, i3=self._i3)
def _on_event(self, _, event: I3Event):
self._schedule_refresh()
def _schedule_refresh(self):
# Defer to the next idle tick — fenster's internal state is not always
# updated synchronously when an event fires, so querying GET_WORKSPACES
# immediately can return the pre-event view.
if self._refresh_pending:
return
self._refresh_pending = True
GLib.idle_add(self._refresh_idle)
def _refresh_idle(self):
self._refresh_pending = False
self._refresh_workspaces()
return False
def _refresh_workspaces(self):
reply = I3.send_command("", I3MessageType.GET_WORKSPACES)
if reply.is_ok and isinstance(reply.reply, list):
self._update_workspaces(reply.reply)
def _update_workspaces(self, workspaces: list):
ws_by_num = {
ws["num"]: ws for ws in workspaces if ws.get("num") is not None
}
for n, button in self._buttons.items():
ws = ws_by_num.get(n)
if ws is None:
button.set_active(False)
button.set_visible_other(False)
button.set_urgent(False)
button.set_empty(True)
button.set_foreign(False)
continue
focused = bool(ws.get("focused"))
visible = bool(ws.get("visible"))
urgent = bool(ws.get("urgent"))
ws_output = ws.get("output")
window_count = ws.get("window_count", 0)
button.set_active(focused)
# Visible on its output but not the focused one → shown on another monitor.
button.set_visible_other(visible and not focused)
button.set_urgent(urgent)
button.set_empty(window_count == 0)
# Workspace currently shown on a different output than this bar's.
button.set_foreign(
self._output is not None
and ws_output is not None
and ws_output != self._output
)
self.show_all()
class FensterActiveWindow(Label):
"""Label showing the title of the focused window"""
def __init__(
self,
i3: I3 | None = None,
max_length: int = 50,
**kwargs,
):
super().__init__(
name=kwargs.pop("name", "active-window"),
label="",
**kwargs,
)
self._i3 = i3 or get_i3_connection()
self._max_length = max_length
bulk_connect(
self._i3,
{
"event::window::focus": self._on_window_event,
"event::window::title": self._on_window_event,
"event::window::close": self._on_window_close,
},
)
if self._i3.ready:
self._initialize()
else:
self._i3.connect("notify::ready", lambda *_: self._initialize())
def _initialize(self):
tree_reply = I3.send_command("", I3MessageType.GET_TREE)
if tree_reply.is_ok and isinstance(tree_reply.reply, dict):
focused = self._find_focused(tree_reply.reply)
if focused:
self._set_title(focused.get("name") or "")
return
self.set_label("")
def _find_focused(self, node: dict) -> dict | None:
if node.get("focused") and node.get("type") == "con":
return node
for child in node.get("nodes", []) + node.get("floating_nodes", []):
result = self._find_focused(child)
if result:
return result
return None
def _on_window_event(self, _, event: I3Event):
container = event.data.get("container", {})
self._set_title(container.get("name") or "")
def _on_window_close(self, _, event: I3Event):
self._initialize()
def _set_title(self, title: str):
if len(title) > self._max_length:
title = title[: self._max_length - 3] + "..."
self.set_label(title)

View File

@@ -0,0 +1,136 @@
from fabric.notifications import Notification
from fabric.utils import invoke_repeater
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from gi.repository import GdkPixbuf
from sims.utils.markup import render_body_markup
NOTIFICATION_IMAGE_SIZE = 64
class NotificationWidget(Box):
def __init__(
self,
notification: Notification,
width: int = 360,
timeout_ms: int = 10_000,
**kwargs,
):
super().__init__(
size=(width, -1),
name="notification",
spacing=8,
orientation="v",
**kwargs,
)
self._notification = notification
urgency_class = {0: "urgency-low", 1: "urgency-normal", 2: "urgency-critical"}.get(
notification.urgency, "urgency-normal"
)
self.get_style_context().add_class(urgency_class)
body_container = Box(spacing=4, orientation="h")
if image_pixbuf := self._notification.image_pixbuf:
body_container.add(
Image(
pixbuf=image_pixbuf.scale_simple(
NOTIFICATION_IMAGE_SIZE,
NOTIFICATION_IMAGE_SIZE,
GdkPixbuf.InterpType.BILINEAR,
)
)
)
text_children = []
summary = self._notification.summary or ""
body = self._notification.body or ""
text_children.append(
Box(
orientation="h",
children=[
Label(label=summary, ellipsization="middle")
.build()
.add_style_class("summary")
.unwrap(),
],
h_expand=True,
v_expand=True,
).build(
lambda box, _: box.pack_end(
Button(
image=Image(icon_name="window-close-symbolic", icon_size=18),
v_align="center",
h_align="end",
on_clicked=lambda *_: self._notification.close(),
),
False,
False,
0,
)
)
)
if body:
body_text, body_is_markup = render_body_markup(body)
body_kwargs = {"markup": body_text} if body_is_markup else {"label": body_text}
text_children.append(
Label(
**body_kwargs,
line_wrap="word-char",
v_align="start",
h_align="start",
)
.build()
.add_style_class("body")
.unwrap()
)
body_container.add(
Box(
spacing=4,
orientation="v",
children=text_children,
h_expand=True,
v_expand=True,
)
)
self.add(body_container)
if actions := self._notification.actions:
self.add(
Box(
spacing=4,
orientation="h",
children=[
Button(
h_expand=True,
v_expand=True,
label=action.label,
on_clicked=lambda *_, action=action: action.invoke(),
)
for action in actions
],
)
)
self._notification.connect(
"closed",
lambda *_: (
parent.remove(self) if (parent := self.get_parent()) else None, # type: ignore
self.destroy(),
),
)
invoke_repeater(
timeout_ms,
lambda: self._notification.close("expired"),
initial_call=False,
)

View File

@@ -0,0 +1,103 @@
import time
from typing import Callable
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from sims.services.notification_history import HistoryEntry
from sims.utils.markup import render_body_markup
def _time_ago(ts: float, now: float | None = None) -> str:
delta = int((now if now is not None else time.time()) - ts)
if delta < 60:
return "just now"
if delta < 3600:
return f"{delta // 60}m ago"
if delta < 86400:
return f"{delta // 3600}h ago"
return f"{delta // 86400}d ago"
class NotificationHistoryEntryWidget(Box):
THUMB_SIZE = 40
def __init__(
self,
entry: HistoryEntry,
on_dismiss: Callable[[int], None],
**kwargs,
):
super().__init__(
name="notification-history-entry",
spacing=8,
orientation="h",
**kwargs,
)
urgency_class = {0: "urgency-low", 1: "urgency-normal", 2: "urgency-critical"}.get(
entry.urgency, "urgency-normal"
)
self.get_style_context().add_class(urgency_class)
if entry.pixbuf is not None:
self.add(Image(pixbuf=entry.pixbuf, h_align="start", v_align="start"))
text_children: list = []
header = Box(orientation="h", h_expand=True)
header.pack_start(
Label(
label=entry.summary,
ellipsization="end",
h_align="start",
)
.build()
.add_style_class("summary")
.unwrap(),
True,
True,
0,
)
header.pack_end(
Label(label=_time_ago(entry.timestamp), h_align="end")
.build()
.add_style_class("timestamp")
.unwrap(),
False,
False,
0,
)
text_children.append(header)
if entry.body:
body_text, body_is_markup = render_body_markup(entry.body)
body_kwargs = {"markup": body_text} if body_is_markup else {"label": body_text}
text_children.append(
Label(
**body_kwargs,
line_wrap="word-char",
h_align="start",
v_align="start",
)
.build()
.add_style_class("body")
.unwrap()
)
text_box = Box(orientation="v", spacing=2, children=text_children, h_expand=True)
self.add(text_box)
self.pack_end(
Button(
name="notification-history-dismiss",
image=Image(icon_name="window-close-symbolic", icon_size=14),
v_align="start",
h_align="end",
on_clicked=lambda *_: on_dismiss(entry.id),
),
False,
False,
0,
)