Compare commits

80 Commits
Author SHA1 Message Date
Makussu 377889db8c feat: unified bar styling
- semantic tokens (accent/surface/hairline/text-muted) derived from the
  palette so they follow stylix in light and dark mode
- every bar module is a uniform 28px rounded chip; one accent for active
  state, tints for attention, solid fill only for mail-debt alarm
- workspaces as dots with a stretching accent pill
- mic/cpu-ram/tray/battery grouped into one chip; cpu/ram as concentric
  rings with tooltip; clock split into bold time + muted date
- stylix provider only sets palette + font; scope its font-size so the
  bar's own CSS sizes are no longer flattened
- drop inline widget styles, 16px tray icons, fix broken menu.css selector
2026-11-09 23:29:01 +01:00
Makussu a890604001 feat: media hover card with playback controls 2026-11-09 22:20:34 +01:00
Makussu a56d4d1c20 fix: light mode theming 2026-10-05 12:30:43 +02:00
Makussu 4274971337 feat: manual darkman switching 2026-10-05 12:09:28 +02:00
Makussu fc4fa21a0f feat: support theme switching 2026-10-05 12:01:17 +02:00
Makussu 42a4ffdee6 feat: dmenu-compatible picker 2026-10-04 21:25:28 +02:00
Makussu 4721976c71 feat: screen-share indicator
Replace the wl-screenrec bar widget with a generic capture indicator
driven by fenster's "capture" IPC event (riverfx capture_sessions). It
shows a red dot while any output/window is captured, reveals a summary
on hover with details in the tooltip, and stops a running sims
recording on click.
2026-10-04 19:43:02 +02:00
Makussu 7cf69a8c75 fix: only start systems once 2026-09-17 13:30:59 +02:00
Makussu 2fc0854a11 feat: launcher recommendation 2026-09-15 19:53:43 +02:00
Makussu ff200e3580 feat: microphone muting 2026-07-22 20:18:17 +02:00
Makussu d69107c624 fix: use khal 0.11.3 command 2026-06-30 20:27:29 +02:00
Makussu 9c1c612a04 fix: start sims after graphical so it gets correct env 2026-06-16 18:17:15 +02:00
Makussu 07919fc687 feat: org todos in bar 2026-05-10 01:55:21 +02:00
Makussu a8d96b7481 feat: buddy 2026-05-09 22:42:27 +02:00
Makussu 6da7e97f19 feat: mail finder 2026-05-06 23:12:57 +02:00
Makussu cfdcf0c039 feat: email debt timer 2026-05-06 21:22:27 +02:00
Makussu 4adace6c4c feat: subscribe to all players 2026-05-05 23:58:15 +02:00
Makussu cc3bac5ce7 feat: player animations 2026-05-05 23:47:47 +02:00
Makussu 81e1a1fc1f feat: mpris player widget 2026-05-05 23:15:09 +02:00
Makussu d14a0c9678 fix: start apps not in this service cgroup 2026-05-05 20:50:18 +02:00
Makussu 47e104465e feat: control center 2026-05-05 00:19:10 +02:00
Makussu 4a271ac4d8 feat: notification markup support 2026-05-04 23:05:23 +02:00
Makussu 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
Makussu 047a85925a feat: sims notifications 2026-05-04 21:31:09 +02:00
Makussu 4c8b9020b0 fix: start apps in subprocess 2026-05-04 20:06:52 +02:00
Makussu e7a1a2c0ee feat: spawn layer shells on correct output 2026-05-04 19:50:06 +02:00
Makussu cb3b7bf392 fix: correct smart corner events 2026-05-04 19:40:39 +02:00
Makussu f83b7ce874 fix: launchers should have exclusive focus 2026-05-04 19:29:56 +02:00
Makussu ec7e2cd6fd fix: render more of launchers 2026-05-04 19:15:26 +02:00
Makussu 6f4e397f6c feat: clipboard menu 2026-05-04 17:01:08 +02:00
Makussu aad8121fa4 fix: only show screenrec when recording 2026-05-04 12:09:39 +02:00
Makussu 709695fd22 fix: dont ship weird default styles 2026-05-04 12:03:48 +02:00
Makussu 1d98a541de fix: click on workspace 2026-05-04 11:35:14 +02:00
Makussu 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
Makussu 6343c91fca fix: instantly spawn bar 2026-05-04 00:00:11 +02:00
Makussu 0cd58f4a1f feat: sims cli as python package 2026-05-03 22:19:52 +02:00
Makussu afcf8d51fe feat: power and screenshot launchers 2026-05-03 21:53:10 +02:00
Makussu 7bdf23001f feat: add app launcher 2026-05-03 21:42:30 +02:00
Makussu 60757ee336 feat: sims launcher 2026-05-03 20:40:21 +02:00
Makussu c10709df26 feat: rename to sims 2026-05-03 20:15:43 +02:00
Makussu fb206667c4 feat: dim other monitors workspaces 2026-05-03 19:05:46 +02:00
Makussu aee5be7f39 fix: stylix needs to generate visible colours 2026-05-03 18:53:37 +02:00
Makussu d1b6d3a560 feat: always show 9 bubbles 2026-05-03 14:58:52 +02:00
Makussu 0d4c4caf10 feat: show visible and active workspaces 2026-05-03 14:47:20 +02:00
Makussu f1c45a7f8c feat: use fenster ipc (sway/i3 compatible) 2026-03-10 22:58:40 +01:00
Makussu 7962947f80 feat: refresh mail widget 2025-10-18 20:38:03 +02:00
Makussu c256931b1d feat: log level in nix 2025-10-17 17:44:49 +02:00
Makussu 5137379ac9 shadow preparation
the shadow needs to be done on the compositor
2025-09-30 20:54:57 +02:00
Makussu 159eafbc73 quick menu 2025-09-30 20:52:03 +02:00
Makussu 7b0a4a56db better vinyl styling 2025-09-30 12:56:05 +02:00
Makussu 9666a2f7ae fix: nix paths 2025-09-30 00:48:41 +02:00
Makussu 0be71cfddf prod logging 2025-09-30 00:35:27 +02:00
Makussu 2d3f97cae1 fix: khal and notmuch in path 2025-09-30 00:29:02 +02:00
Makussu 15077fe6fa feat: mail 2025-09-29 23:24:33 +02:00
Makussu 34e837562f better calendar styling 2025-09-29 18:45:36 +02:00
Makussu a22f16a84f fix: run 2025-09-29 18:32:05 +02:00
Makussu 17d11591ac dev mode 2025-09-29 18:29:57 +02:00
Makussu 05f20d65b9 notch docs 2025-09-29 18:29:24 +02:00
Makussu 0b3ee96ccf better calendar styling 2025-09-29 17:00:53 +02:00
Makussu dd6feb4170 stylix font size 2025-09-29 16:42:44 +02:00
Makussu 5cea889af3 feat: calendar in bar 2025-09-29 16:36:43 +02:00
Makussu f781603907 example dev stylix yaml 2025-09-29 12:54:58 +02:00
Makussu 5afada0fb3 better workspace styling 2025-09-29 12:52:03 +02:00
Makussu 055f4ebb96 better snowflake symbol 2025-09-29 12:44:48 +02:00
Makussu da2a7d94d8 new workspace styling 2025-09-29 12:27:24 +02:00
Makussu c814eb01de smaller stylix workspace buttons 2025-09-29 11:40:51 +02:00
Makussu 03598694fc fix: stylix workspace buttons 2025-09-29 11:39:16 +02:00
Makussu c4e522f17a fix battery usage 2025-09-29 11:36:33 +02:00
Makussu fe87de7580 fix stylix stylesheet 2025-09-29 11:19:13 +02:00
Makussu 5c2ee58f4d fix: stylix enable option 2025-09-29 11:13:34 +02:00
Makussu 4fda2670ac feat: stylix support 2025-09-29 11:10:25 +02:00
Makussu d9a176d4ec window title option 2025-09-29 11:02:48 +02:00
Makussu 1a24c4eb99 add makefile 2025-09-29 10:56:37 +02:00
Makussu 0ce3d286e2 bar height 2025-09-29 10:51:21 +02:00
Makussu 7a6eca395d fix: correct battery icons 2025-09-29 10:34:24 +02:00
Makussu 40ab13ab26 fix: really run battery updates 2025-09-29 10:12:12 +02:00
Makussu 56c35ec7ec fix: battery run 2025-09-29 09:19:09 +02:00
Makussu e3396be9af battery icons 2025-09-29 09:13:40 +02:00
Makussu fc264dda44 feat: battery 2025-09-29 09:01:23 +02:00
Makussu df2bef7685 fix: vinyl 2025-05-19 10:44:26 +02:00
98 changed files with 9534 additions and 1348 deletions
+15
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))
+11
View File
@@ -1,3 +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
-52
View File
@@ -1,52 +0,0 @@
import yaml
import os
from platformdirs import user_config_dir
import argparse
APP_NAME = "makku_bar"
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="makku_bar")
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})
-57
View File
@@ -1,57 +0,0 @@
from loguru import logger
from fabric import Application
from fabric.system_tray.widgets import SystemTray
from fabric.widgets.wayland import WaylandWindow as Window
from fabric.river.widgets import (
get_river_connection,
)
from fabric.utils import (
get_relative_path,
)
from .modules.bar import StatusBar
from .modules.window_fuzzy import FuzzyWindowFinder
from .modules.app_launcher import AppLauncher
tray = SystemTray(name="system-tray", spacing=4)
river = get_river_connection()
dummy = Window(visible=False)
finder = FuzzyWindowFinder()
launcher = AppLauncher()
bar_windows = []
app = Application("bar", dummy, finder, launcher)
app.set_stylesheet_from_file(get_relative_path("styles/main.css"))
def spawn_bars():
logger.info("[Bar] Spawning bars after river ready")
outputs = river.outputs
if not outputs:
logger.warning("[Bar] No outputs found — skipping bar spawn")
return
output_ids = sorted(outputs.keys())
for i, output_id in enumerate(output_ids):
bar = StatusBar(display=output_id, tray=tray if i == 0 else None, monitor=i)
bar_windows.append(bar)
return False
def main():
if river.ready:
spawn_bars()
else:
river.connect("notify::ready", lambda sender, pspec: spawn_bars())
app.run()
if __name__ == "__main__":
main()
-192
View File
@@ -1,192 +0,0 @@
"""
example configuration shows how to make a simple
desktop applications launcher, this example doesn't involve
any styling (except a couple of basic style properties)
the purpose of this configuration is to show to to use
the given utils and mainly how using lazy executors might
make the configuration way more faster than it's supposed to be
"""
import operator
from collections.abc import Iterator
from dataclasses import dataclass
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 fabric.widgets.entry import Entry
from fabric.widgets.scrolledwindow import ScrolledWindow
from fabric.widgets.wayland import WaylandWindow as Window
from fabric.utils import DesktopApp, get_desktop_applications, idle_add, remove_handler
import subprocess
from time import sleep
import threading
@dataclass()
class CustomApp:
name: str
generic_name: str | None
display_name: str | None
description: str | None
executable: str | None
command_line: str | None
hidden: bool
def __init__(
self,
name,
display_name=None,
executable=None,
generic_name=None,
description=None,
command_line=None,
hidden=False,
):
self.name = name
self.generic_name = generic_name
self.display_name = display_name
self.description = description
self.executable = executable
self.command_line = command_line
self.hidden = hidden
def launch(self):
def background():
subprocess.run([self.command_line])
threading.Thread(target=background, daemon=True).start()
def get_icon_pixbuf(
self,
size: int = 48,
default_icon: str | None = "image-missing",
) -> None:
return None
class AppLauncher(Window):
def __init__(self, **kwargs):
super().__init__(
layer="top",
anchor="center",
exclusivity="none",
keyboard_mode="on-demand",
visible=False,
all_visible=False,
**kwargs,
)
self._arranger_handler: int = 0
self._all_apps = get_desktop_applications()
self._custom_apps = [
CustomApp("Screenshot Clipboard", command_line="grim2clip")
]
self.viewport = Box(spacing=2, orientation="v")
self.search_entry = Entry(
placeholder="Search Applications...",
h_expand=True,
notify_text=lambda entry, *_: self.arrange_viewport(entry.get_text()),
)
self.scrolled_window = ScrolledWindow(
min_content_size=(280, 320),
max_content_size=(280 * 2, 320),
child=self.viewport,
)
self.add(
Box(
spacing=2,
orientation="v",
style="margin: 2px",
children=[
# the header with the search entry
Box(
spacing=2,
orientation="h",
children=[
self.search_entry,
Button(
image=Image(icon_name="window-close"),
tooltip_text="Exit",
on_clicked=lambda *_: self.application.quit(),
),
],
),
# the actual slots holder
self.scrolled_window,
],
)
)
self.show_all()
def arrange_viewport(self, query: str = ""):
# reset everything so we can filter current viewport's slots...
# remove the old handler so we can avoid race conditions
remove_handler(self._arranger_handler) if self._arranger_handler else None
# remove all children from the viewport
self.viewport.children = []
combined_apps = self._all_apps + self._custom_apps
# make a new iterator containing the filtered apps
filtered_apps_iter = iter(
[
app
for app in combined_apps
if query.casefold()
in (
(app.display_name or "")
+ (" " + app.name + " ")
+ (app.generic_name or "")
).casefold()
]
)
should_resize = operator.length_hint(filtered_apps_iter) == len(self._all_apps)
# all aboard...
# start the process of adding slots with a lazy executor
# using this method makes the process of adding slots way more less
# resource expensive without blocking the main thread and resulting in a lock
self._arranger_handler = idle_add(
lambda *args: self.add_next_application(*args)
or (self.resize_viewport() if should_resize else False),
filtered_apps_iter,
pin=True,
)
return False
def add_next_application(self, apps_iter: Iterator[DesktopApp]):
if not (app := next(apps_iter, None)):
return False
self.viewport.add(self.bake_application_slot(app))
return True
def resize_viewport(self):
self.scrolled_window.set_min_content_width(
self.viewport.get_allocation().width # type: ignore
)
return False
def bake_application_slot(self, app: DesktopApp, **kwargs) -> Button:
return Button(
child=Box(
orientation="h",
spacing=12,
children=[
Image(pixbuf=app.get_icon_pixbuf(), h_align="start", size=32),
Label(
label=app.display_name or "Unknown",
v_align="center",
h_align="center",
),
],
),
tooltip_text=app.description,
on_clicked=lambda *_: (self.hide(), app.launch()),
**kwargs,
)
-133
View File
@@ -1,133 +0,0 @@
import psutil
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.overlay import Overlay
from fabric.widgets.datetime import DateTime
from fabric.widgets.centerbox import CenterBox
from bar.modules.player import Player
from bar.modules.vinyl import VinylButton
from fabric.widgets.wayland import WaylandWindow as Window
from fabric.system_tray.widgets import SystemTray
from fabric.river.widgets import (
RiverWorkspaces,
RiverWorkspaceButton,
RiverActiveWindow,
get_river_connection,
)
from fabric.utils import (
invoke_repeater,
)
from fabric.widgets.circularprogressbar import CircularProgressBar
from bar.config import VINYL
class StatusBar(Window):
def __init__(
self,
display: int,
tray: SystemTray | None = None,
monitor: int = 1,
river_service=None,
):
super().__init__(
name="bar",
layer="top",
anchor="left top right",
margin="0px 0px -2px 0px",
exclusivity="auto",
visible=False,
all_visible=False,
monitor=monitor,
)
if river_service:
self.river = river_service
else:
self.river = get_river_connection()
self.workspaces = RiverWorkspaces(
display,
name="workspaces",
spacing=4,
buttons_factory=lambda ws_id: RiverWorkspaceButton(id=ws_id, label=None),
river_service=self.river,
)
self.date_time = DateTime(name="date-time", formatters="%d %b - %H:%M")
self.system_tray = tray
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_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.vinyl = None
if VINYL["enable"]:
self.vinyl = VinylButton()
self.status_container = Box(
name="widgets-container",
spacing=4,
orientation="h",
children=self.progress_bars_overlay,
)
end_container_children = []
if self.vinyl:
end_container_children.append(self.vinyl)
end_container_children.append(self.status_container)
if self.system_tray:
end_container_children.append(self.system_tray)
end_container_children.append(self.date_time)
self.children = CenterBox(
name="bar-inner",
start_children=Box(
name="start-container",
spacing=6,
orientation="h",
children=[
Label(name="nixos-label", markup=""),
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
-274
View File
@@ -1,274 +0,0 @@
import os
import struct
import subprocess
import re
import ctypes
import signal
from gi.repository import GLib, Gtk, Gdk
from loguru import logger
from math import pi
from fabric.widgets.overlay import Overlay
from fabric.utils.helpers import get_relative_path
import configparser
def get_bars(file_path):
config = configparser.ConfigParser()
config.read(file_path)
return int(config["general"]["bars"])
CAVA_CONFIG = get_relative_path("../config/cavalcade/cava.ini")
bars = get_bars(CAVA_CONFIG)
def set_death_signal():
"""
Set the death signal of the child process to SIGTERM so that if the parent
process is killed, the child (cava) is automatically terminated.
"""
libc = ctypes.CDLL("libc.so.6")
PR_SET_PDEATHSIG = 1
libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM)
class Cava:
"""
CAVA wrapper.
Launch cava process with certain settings and read output.
"""
NONE = 0
RUNNING = 1
RESTARTING = 2
CLOSING = 3
def __init__(self, mainapp):
self.bars = bars
self.path = "/tmp/cava.fifo"
self.cava_config_file = CAVA_CONFIG
self.data_handler = mainapp.draw.update
self.command = ["cava", "-p", self.cava_config_file]
self.state = self.NONE
self.env = dict(os.environ)
self.env["LC_ALL"] = "en_US.UTF-8" # not sure if it's necessary
is_16bit = True
self.byte_type, self.byte_size, self.byte_norm = (
("H", 2, 65535) if is_16bit else ("B", 1, 255)
)
if not os.path.exists(self.path):
os.mkfifo(self.path)
self.fifo_fd = None
self.fifo_dummy_fd = None
self.io_watch_id = None
def _run_process(self):
logger.debug("Launching cava process...")
try:
self.process = subprocess.Popen(
self.command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env=self.env,
preexec_fn=set_death_signal, # Ensure cava gets killed when the parent dies.
)
logger.debug("cava successfully launched!")
self.state = self.RUNNING
except Exception:
logger.exception("Fail to launch cava")
def _start_io_reader(self):
logger.debug("Activating GLib IO watch for cava stream handler")
# Open FIFO in non-blocking mode for reading
self.fifo_fd = os.open(self.path, os.O_RDONLY | os.O_NONBLOCK)
# Open dummy write end to prevent getting an EOF on our FIFO
self.fifo_dummy_fd = os.open(self.path, os.O_WRONLY | os.O_NONBLOCK)
self.io_watch_id = GLib.io_add_watch(
self.fifo_fd, GLib.IO_IN, self._io_callback
)
def _io_callback(self, source, condition):
chunk = self.byte_size * self.bars # number of bytes for given format
try:
data = os.read(self.fifo_fd, chunk)
except OSError as e:
# logger.error("Error reading FIFO: {}".format(e))
return False
# When no data is read, do not remove the IO watch immediately.
if len(data) < chunk:
# Instead of closing the FIFO, we log a warning and continue.
# logger.warning("Incomplete data packet received (expected {} bytes, got {}). Waiting for more data...".format(chunk, len(data)))
# Returning True keeps the IO watch active. A real EOF will only occur when the writer closes.
return True
fmt = self.byte_type * self.bars # format string for struct.unpack
sample = [i / self.byte_norm for i in struct.unpack(fmt, data)]
GLib.idle_add(self.data_handler, sample)
return True
def _on_stop(self):
logger.debug("Cava stream handler deactivated")
if self.state == self.RESTARTING:
self.start()
elif self.state == self.RUNNING:
self.state = self.NONE
logger.error("Cava process was unexpectedly terminated.")
# self.restart() # May cause infinity loop, need more check
def start(self):
"""Launch cava"""
self._start_io_reader()
self._run_process()
def restart(self):
"""Restart cava process"""
if self.state == self.RUNNING:
logger.debug("Restarting cava process (normal mode) ...")
self.state = self.RESTARTING
if self.process.poll() is None:
self.process.kill()
elif self.state == self.NONE:
logger.warning("Restarting cava process (after crash) ...")
self.start()
def close(self):
"""Stop cava process"""
self.state = self.CLOSING
if self.process.poll() is None:
self.process.kill()
if self.io_watch_id:
GLib.source_remove(self.io_watch_id)
if self.fifo_fd:
os.close(self.fifo_fd)
if self.fifo_dummy_fd:
os.close(self.fifo_dummy_fd)
if os.path.exists(self.path):
os.remove(self.path)
class AttributeDict(dict):
"""Dictionary with keys as attributes. Does nothing but easy reading"""
def __getattr__(self, attr):
return self.get(attr, 3)
def __setattr__(self, attr, value):
self[attr] = value
class Spectrum:
"""Spectrum drawing"""
def __init__(self):
self.silence_value = 0
self.audio_sample = []
self.color = None
self.area = Gtk.DrawingArea()
self.area.connect("draw", self.redraw)
self.area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.sizes = AttributeDict()
self.sizes.area = AttributeDict()
self.sizes.bar = AttributeDict()
self.silence = 10
self.max_height = 12
self.area.connect("configure-event", self.size_update)
self.color_update()
def is_silence(self, value):
"""Check if volume level critically low during last iterations"""
self.silence_value = 0 if value > 0 else self.silence_value + 1
return self.silence_value > self.silence
def update(self, data):
"""Audio data processing"""
self.color_update()
self.audio_sample = data
if not self.is_silence(self.audio_sample[0]):
self.area.queue_draw()
elif self.silence_value == (self.silence + 1):
self.audio_sample = [0] * self.sizes.number
self.area.queue_draw()
def redraw(self, widget, cr):
"""Draw spectrum graph"""
cr.set_source_rgba(*self.color)
dx = 3
center_y = self.sizes.area.height / 2 # center vertical of the drawing area
for i, value in enumerate(self.audio_sample):
width = self.sizes.area.width / self.sizes.number - self.sizes.padding
radius = width / 2
height = max(self.sizes.bar.height * min(value, 1), self.sizes.zero) / 2
if height == self.sizes.zero / 2 + 1:
height *= 0.5
height = min(height, self.max_height)
# Draw rectangle and arcs for rounded ends
cr.rectangle(dx, center_y - height, width, height * 2)
cr.arc(dx + radius, center_y - height, radius, 0, 2 * pi)
cr.arc(dx + radius, center_y + height, radius, 0, 2 * pi)
cr.close_path()
dx += width + self.sizes.padding
cr.fill()
def size_update(self, *args):
"""Update drawing geometry"""
self.sizes.number = bars
self.sizes.padding = 100 / bars
self.sizes.zero = 0
self.sizes.area.width = self.area.get_allocated_width()
self.sizes.area.height = self.area.get_allocated_height() - 2
tw = self.sizes.area.width - self.sizes.padding * (self.sizes.number - 1)
self.sizes.bar.width = max(int(tw / self.sizes.number), 1)
self.sizes.bar.height = self.sizes.area.height
def color_update(self):
"""Set drawing color according to current settings by reading primary color from CSS"""
color = "#a5c8ff" # default value
try:
with open(get_relative_path("../styles/colors.css"), "r") as f:
content = f.read()
m = re.search(r"--primary:\s*(#[0-9a-fA-F]{6})", content)
if m:
color = m.group(1)
except Exception as e:
logger.error("Failed to read primary color: {}".format(e))
red = int(color[1:3], 16) / 255
green = int(color[3:5], 16) / 255
blue = int(color[5:7], 16) / 255
self.color = Gdk.RGBA(red=red, green=green, blue=blue, alpha=1.0)
class SpectrumRender:
def __init__(self, mode=None, **kwargs):
super().__init__(**kwargs)
self.mode = mode
self.draw = Spectrum()
self.cava = Cava(self)
self.cava.start()
def get_spectrum_box(self):
# Get the spectrum box
box = Overlay(name="cavalcade", h_align="center", v_align="center")
box.set_size_request(180, 40)
box.add_overlay(self.draw.area)
return box
-92
View File
@@ -1,92 +0,0 @@
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.eventbox import EventBox
from fabric.widgets.overlay import Overlay
from fabric.core.service import Property
import subprocess
class VinylButton(Box):
@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,
):
super().__init__(**kwargs)
# Initialize properties
self._active = False
self._active_command = active_command
self._inactive_command = inactive_command
# Set up the icon
self.icon = Label(
label="", # CD icon
name="vinyl-icon",
style="",
)
# Set up event box to handle clicks
self.event_box = EventBox(
events="button-press",
child=Overlay(
child=self.icon,
),
name="vinyl-button",
)
# Connect click event
self.event_box.connect("button-press-event", self._on_clicked)
# Add to parent box
self.add(self.event_box)
# 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, _, event):
"""Handle button click event"""
if event.button == 1: # Left click
# Toggle active state
self.active = not self.active
return True
def _execute_active_command(self):
"""Execute shell command when button is activated"""
try:
subprocess.Popen(self._active_command, 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:
subprocess.Popen(self._inactive_command, shell=True)
except Exception as e:
print(f"Error executing inactive command: {e}")
-75
View File
@@ -1,75 +0,0 @@
import operator
from fabric.widgets.wayland import WaylandWindow as Window
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.entry import Entry
from fabric.utils import idle_add
from gi.repository import Gdk
class FuzzyWindowFinder(Window):
def __init__(
self,
monitor: int = 0,
):
super().__init__(
name="finder",
anchor="center",
monitor=monitor,
keyboard_mode="on-demand",
type="popup",
visible=False,
)
self._all_windows = ["Test", "Uwu", "Tidal"]
self.viewport = Box(name="viewport", spacing=4, orientation="v")
self.search_entry = Entry(
name="search-entry",
placeholder="Search Windows...",
h_expand=True,
editable=True,
notify_text=self.notify_text,
on_activate=lambda entry, *_: self.on_search_entry_activate(
entry.get_text()
),
on_key_press_event=self.on_search_entry_key_press,
)
self.picker_box = Box(
name="picker-box",
spacing=4,
orientation="v",
children=[self.search_entry, self.viewport],
)
self.add(self.picker_box)
self.arrange_viewport("")
def notify_text(self, entry, *_):
text = entry.get_text()
self.arrange_viewport(text) # Update list on typing
print(text)
def on_search_entry_key_press(self, widget, event):
# if event.keyval in (Gdk.KEY_Up, Gdk.KEY_Down, Gdk.KEY_Left, Gdk.KEY_Right):
# self.move_selection_2d(event.keyval)
# return True
print(event.keyval)
if event.keyval in [Gdk.KEY_Escape, 103]:
self.hide()
return True
return False
def on_search_entry_activate(self, text):
print(f"activate {text}")
def arrange_viewport(self, query: str = ""):
self.viewport.children = [] # Clear previous entries
filtered = [w for w in self._all_windows if query.lower() in w.lower()]
for window in filtered:
self.viewport.add(
Box(name="slot-box", orientation="h", children=[Label(label=window)])
)
-51
View File
@@ -1,51 +0,0 @@
#bar-inner {
padding: 4px;
border-bottom: solid 2px;
border-color: var(--border-color);
background-color: var(--window-bg);
min-height: 28px;
}
#center-container {
color: var(--foreground);
}
.active-window {
color: var(--foreground);
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;
}
#nixos-label {
color: var(--blue);
}
tooltip {
border: solid 2px;
border-color: var(--border-color);
background-color: var(--window-bg);
}
tooltip>* {
padding: 2px 4px
}
-28
View File
@@ -1,28 +0,0 @@
: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(--pink);
--ws-inactive: var(--blue);
--ws-empty: var(--dark-grey);
--ws-hover: var(--turquoise);
--ws-urgent: var(--red);
}
-29
View File
@@ -1,29 +0,0 @@
#picker-box {
padding: 12px;
background-color: rgba(40, 40, 40, 0.95); /* darker for contrast */
border-radius: 8px;
font-family: sans-serif;
font-size: 14px;
color: white;
}
#viewport {
padding: 8px;
background-color: rgba(30, 30, 30, 0.9); /* dark background for contrast */
border-radius: 6px;
font-family: sans-serif;
font-size: 14px;
color: white; /* ensure contrast */
}
#viewport > * {
padding: 6px 10px;
margin-bottom: 4px;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.05);
}
#viewport:hover {
background-color: rgba(255, 255, 255, 0.15); /* hover feedback */
}
-20
View File
@@ -1,20 +0,0 @@
@import url("./colors.css");
@import url("./workspaces.css");
@import url("./menu.css");
@import url("./vinyl.css");
@import url("./bar.css");
@import url("./finder.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
View File
@@ -1,38 +0,0 @@
#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);
}
-41
View File
@@ -1,41 +0,0 @@
/* Vinyl button styling */
#vinyl-button {
padding: 0px 8px;
transition: padding 0.05s steps(8);
background-color: rgba(180, 180, 180, 0.2);
border-radius: 4px;
transition: all 0.2s ease;
}
/* Active state styling */
.active #vinyl-button {
background-color: rgba(108, 158, 175, 0.7);
padding: 0px 32px;
}
/* Icon styling */
#vinyl-icon {
color: #555555;
min-width: 36px;
}
/* Label styling */
#vinyl-label {
color: #333333;
}
/* Active state changes for icon and label */
.active #vinyl-icon,
.active #vinyl-label {
color: var(--pink);
padding: 0px 32px;
}
/* Hover effect */
#vinyl-button:hover {
background-color: rgba(180, 180, 180, 0.4);
}
.active #vinyl-button:hover {
background-color: rgba(108, 158, 175, 0.9);
}
-42
View File
@@ -1,42 +0,0 @@
#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(--foreground);
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);
color: var(--foreground);
font-weight: bold;
animation: urgent-blink 1s infinite;
}
@keyframes urgent-blink {
0% { opacity: 1.0; }
50% { opacity: 0.5; }
100% { opacity: 1.0; }
}
#workspaces>button.empty {
background-color: var(--ws-empty);
}
#workspaces>button.active {
padding: 0px 32px;
background-color: var(--ws-active);
}
+68
View File
@@ -0,0 +1,68 @@
height: 42
dev: true
buddy:
enable: 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"
org:
enable: true
paths:
- "~/Documents/notes"
todo_keywords: ["TODO", "NEXT", "IN-PROGRESS"]
done_keywords: ["DONE", "CANCELLED"]
counted_states: ["TODO", "NEXT", "IN-PROGRESS"]
update_interval: 60000
emacsclient_command: "emacsclient"
dropdown_width: 420
dropdown_height: 480
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
+6 -1
View File
@@ -1,2 +1,7 @@
bar_height: 42
window_title:
enable: false
vinyl:
enabled: true
enable: true
battery:
enable: true
Generated
+5 -5
View File
@@ -6,15 +6,15 @@
"utils": "utils"
},
"locked": {
"lastModified": 1747045720,
"narHash": "sha256-2Z0F4hnluJZunwRfx80EQXpjGLhunV2wrseT42nzh7M=",
"owner": "Makesesama",
"lastModified": 1770146720,
"narHash": "sha256-YVlwsUz4SLj8qYAb21ernT3lDB/piU1V6hTW/UjikWA=",
"owner": "Fabric-Development",
"repo": "fabric",
"rev": "dae50c763e8bf2b4e5807b49b9e62425e0725cfa",
"rev": "fd2aabbd7e1859aa7c11c626a6c36a937aca736a",
"type": "github"
},
"original": {
"owner": "Makesesama",
"owner": "Fabric-Development",
"repo": "fabric",
"type": "github"
}
+379 -59
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.11";
unstable.url = "github:NixOS/nixpkgs/nixos-unstable";
utils.url = "github:numtide/flake-utils";
fabric.url = "github:Makesesama/fabric";
fabric.url = "github:Fabric-Development/fabric";
home-manager.url = "github:nix-community/home-manager";
home-manager.inputs.nixpkgs.follows = "nixpkgs";
};
@@ -32,79 +32,399 @@
{
formatter = pkgs.nixfmt-rfc-style;
devShells.default = pkgs.callPackage ./nix/shell.nix { inherit pkgs; };
packages = {
packages = rec {
default = pkgs.callPackage ./nix/derivation.nix { inherit (pkgs) lib python3Packages; };
makku = pkgs.writeShellScriptBin "makku" ''
dbus-send --session --print-reply --dest=org.Fabric.fabric.bar /org/Fabric/fabric org.Fabric.fabric.Evaluate string:"finder.show()" > /dev/null 2>&1
'';
sims = default;
};
apps.default = {
type = "app";
program = "${self.packages.${system}.default}/bin/bar";
program = "${self.packages.${system}.default}/bin/sims";
};
}
)
// {
homeManagerModules.makku-bar =
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.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";
settingsFormat = pkgs.formats.yaml { };
in
{
options.services.sims = {
enable = lib.mkEnableOption "sims status bar";
package = lib.mkOption {
type = lib.types.package;
default = self.packages.${pkgs.system}.default;
description = "The makku-bar package to use.";
};
package = lib.mkOption {
type = lib.types.package;
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;
settings = lib.mkOption {
type = lib.types.submodule {
options = {
vinyl = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
};
};
darkman = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Add a light/dark mode toggle to the control center and the
`theme-toggle` / `theme-set-light` / `theme-set-dark` actions
(`sims-cli theme toggle|light|dark`). Switches darkman via its
control socket.
'';
};
socket_path = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "darkman control socket; null means \${XDG_RUNTIME_DIR}/darkman/control.sock";
};
};
battery = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
};
};
buddy = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to enable the bar buddy (animated pixel-art slime that reacts to system state)";
};
};
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.
Optionally set `variants.light.colors` / `variants.dark.colors`
(base16 slots base00..base0F, hex without `#`). When present,
sims follows the XDG desktop portal's color-scheme setting
(org.freedesktop.appearance, e.g. served by darkman) and
swaps palettes live; slots missing from a variant fall back
to `colors`.
'';
};
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";
};
};
org = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to enable the org-mode agenda widget";
};
paths = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Org files / directories / globs to scan (~ is expanded)";
};
todo_keywords = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"TODO"
"NEXT"
"IN-PROGRESS"
];
description = "Active TODO keywords used by orgparse when no #+TODO: header is present";
};
done_keywords = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"DONE"
"CANCELLED"
];
description = "Done keywords (filtered out of the count)";
};
counted_states = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"TODO"
"NEXT"
"IN-PROGRESS"
];
description = "States summed for the bar badge count";
};
update_interval = lib.mkOption {
type = lib.types.int;
default = 60000;
description = "Polling interval in milliseconds (mtime-checked, only re-parses on change)";
};
emacsclient_command = lib.mkOption {
type = lib.types.str;
default = "emacsclient";
description = "Command used to open headlines (split on whitespace)";
};
dropdown_width = lib.mkOption {
type = lib.types.int;
default = 420;
description = "Dropdown width in pixels";
};
dropdown_height = lib.mkOption {
type = lib.types.int;
default = 480;
description = "Dropdown height in pixels";
};
};
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;
default = {
vinyl.enable = false;
darkman.enable = false;
battery.enable = false;
buddy.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" ];
};
org = {
enable = false;
paths = [ ];
todo_keywords = [
"TODO"
"NEXT"
"IN-PROGRESS"
];
done_keywords = [
"DONE"
"CANCELLED"
];
counted_states = [
"TODO"
"NEXT"
"IN-PROGRESS"
];
update_interval = 60000;
emacsclient_command = "emacsclient";
dropdown_width = 420;
dropdown_height = 480;
};
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.sims.enable {
systemd.user.services.sims =
let
configFile = settingsFormat.generate "config.yaml" cfg.settings;
in
{
Unit = {
Description = "sims status bar";
# Start as part of the graphical session rather than at
# user-manager boot. The compositor populates the systemd
# user environment (WAYLAND_DISPLAY, NIXOS_OZONE_WL, ...)
# via `import-environment` before it activates
# graphical-session.target, so binding here guarantees sims
# — and every app it launches via `systemd-run --scope` —
# inherits the correct Wayland environment.
PartOf = [ "graphical-session.target" ];
After = [ "graphical-session.target" ];
};
Service = {
ExecStart = "${config.services.sims.package}/bin/sims --config ${configFile}";
Restart = "on-failure";
};
Install = {
WantedBy = [ "graphical-session.target" ];
};
};
};
};
config = lib.mkIf config.services.makku-bar.enable {
systemd.user.services.makku-bar =
let
configFile = settingsFormat.generate "config.yaml" cfg.settings;
in
{
Unit = {
Description = "Makku Status Bar";
After = [ "graphical-session.target" ];
};
Service = {
ExecStart = "${config.services.makku-bar.package}/bin/bar --config ${configFile}";
Restart = "on-failure";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
};
stylix-sims = import ./nix/stylix/hm.nix;
};
};
}
+25 -5
View File
@@ -12,11 +12,14 @@
wrapGAppsHook3,
playerctl,
webp-pixbuf-loader,
notmuch,
khal,
dbus,
...
}:
python3Packages.buildPythonApplication {
pname = "fabric-nix-example";
pname = "sims";
version = "0.0.1";
pyproject = true;
@@ -38,6 +41,8 @@ python3Packages.buildPythonApplication {
gdk-pixbuf
playerctl
webp-pixbuf-loader
notmuch
khal
];
dependencies = with python3Packages; [
@@ -45,6 +50,7 @@ python3Packages.buildPythonApplication {
pywayland
pyyaml
platformdirs
orgparse
];
doCheck = false;
dontWrapGApps = true;
@@ -53,24 +59,38 @@ python3Packages.buildPythonApplication {
runHook preInstall
mkdir -p $out/${python3Packages.python.sitePackages}
cp -r bar $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/bar
chmod +x $out/bin/bar
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 = ''
Fabrix Bar Example
sims status bar (companion to fenster WM).
'';
homepage = "https://github.com/wholikeel/fabric";
license = lib.licenses.agpl3Only;
+6
View File
@@ -22,6 +22,7 @@ pkgs.mkShell {
gobject-introspection
libdbusmenu-gtk3
gdk-pixbuf
librsvg
gnome-bluetooth
cinnamon-desktop
wayland-scanner
@@ -43,7 +44,12 @@ pkgs.mkShell {
python-lsp-ruff
pyyaml
platformdirs
orgparse
]
))
];
shellHook = ''
export GDK_PIXBUF_MODULE_FILE=${pkgs.librsvg}/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache
'';
}
+44
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
View File
@@ -0,0 +1,6 @@
{ lib }:
{
name = "Makku Bar";
homepage = "https://github.com/Makesesama/makku-bar";
maintainers = [ ];
}
+2 -2
View File
@@ -3,14 +3,14 @@ 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"}
+20
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())
Regular → Executable
+1 -1
View File
@@ -15,7 +15,7 @@ if site_packages_dir not in sys.path:
sys.path.insert(0, site_packages_dir)
from bar.main import *
from sims.main import *
sys.argv[0] = os.path.join(script_dir, os.path.basename(__file__))
sys.exit(main())
+261
View File
@@ -0,0 +1,261 @@
"""sims-cli — talk to the running sims status bar over DBus."""
from __future__ import annotations
import argparse
import json
import os
import re
import socket
import subprocess
import sys
import tempfile
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_theme(ns: argparse.Namespace) -> None:
mapping = {
"toggle": "theme-toggle",
"light": "theme-set-light",
"dark": "theme-set-dark",
}
invoke_action(mapping[ns.theme_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 _cmd_dmenu(ns: argparse.Namespace) -> None:
"""dmenu-compatible picker: lines on stdin, chosen line on stdout.
Exits 1 when cancelled or when nothing was offered. Items travel via
a private request file instead of DBus arguments because dbus-send
splits array arguments on commas.
"""
lines = [line.rstrip("\r\n") for line in sys.stdin]
lines = [line for line in lines if line]
if not lines:
sys.exit(1)
base = os.environ.get("XDG_RUNTIME_DIR") or None
with tempfile.TemporaryDirectory(prefix="sims-dmenu-", dir=base) as request_dir:
with open(os.path.join(request_dir, "request.json"), "w", encoding="utf-8") as f:
json.dump({"prompt": ns.prompt, "lines": lines}, f)
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as server:
server.bind(os.path.join(request_dir, "reply.sock"))
server.listen(1)
server.settimeout(ns.timeout)
out = _dbus_send(
f"{IFACE}.InvokeAction",
"string:open-dmenu",
f"array:string:{request_dir}",
)
# InvokeAction replies (error: bool, message: str) with exit 0
# even when the action does not exist (e.g. an older sims).
if re.search(r"^\s*boolean true\s*$", out, re.MULTILINE):
sys.stderr.write(f"sims-cli: open-dmenu failed:\n{out}")
sys.exit(1)
try:
conn, _ = server.accept()
except socket.timeout:
sys.stderr.write("sims-cli: dmenu timed out\n")
sys.exit(1)
with conn:
conn.settimeout(5)
chunks = []
try:
while chunk := conn.recv(4096):
chunks.append(chunk)
except OSError as e:
sys.stderr.write(f"sims-cli: dmenu reply failed: {e}\n")
sys.exit(1)
choice = b"".join(chunks).decode("utf-8").rstrip("\n")
if not choice:
sys.exit(1)
sys.stdout.write(choice + "\n")
sys.stdout.flush()
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)
theme = sub.add_parser("theme", help="light/dark mode (via darkman)")
theme_sub = theme.add_subparsers(dest="theme_cmd", required=True, metavar="MODE")
for sub_name, sub_help in [
("toggle", "flip between light and dark mode"),
("light", "switch to light mode"),
("dark", "switch to dark mode"),
]:
theme_sub.add_parser(sub_name, help=sub_help)
theme.set_defaults(func=_cmd_theme)
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)
dm = sub.add_parser(
"dmenu",
help="dmenu-compatible picker (stdin lines -> chosen line on stdout)",
)
dm.add_argument("-p", "--prompt", default="Select...", help="placeholder text")
dm.add_argument(
"--timeout",
type=float,
default=300.0,
help="seconds to wait for a choice before giving up (default: 300)",
)
dm.set_defaults(func=_cmd_dmenu)
return parser
def main() -> None:
parser = build_parser()
ns = parser.parse_args()
ns.func(ns)
if __name__ == "__main__":
main()
+89
View File
@@ -0,0 +1,89 @@
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})
DARKMAN = app_config.get("darkman", {"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)
BUDDY = app_config.get("buddy", {"enable": False})
ORG = app_config.get("org", {"enable": False})
ORG.setdefault("paths", [])
ORG.setdefault("todo_keywords", ["TODO", "NEXT", "IN-PROGRESS"])
ORG.setdefault("done_keywords", ["DONE", "CANCELLED"])
ORG.setdefault("counted_states", ["TODO", "NEXT", "IN-PROGRESS"])
ORG.setdefault("update_interval", 60_000)
ORG.setdefault("emacsclient_command", "emacsclient")
ORG.setdefault("dropdown_width", 420)
ORG.setdefault("dropdown_height", 480)
+308
View File
@@ -0,0 +1,308 @@
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.dmenu import DmenuMenu
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.org import OrgDropdown
from .modules.stylix import generate_stylix_css
from .modules.theme_toggle import ThemeToggleButton
from .modules.vinyl import VinylButton
from .services.org import OrgService
from .config import CALENDAR, DARKMAN, NOTIFICATIONS, ORG, POWER, SCREENREC, STYLIX, VINYL
from .services.darkman import get_darkman_service
from .services.fenster import get_i3_connection
from .services.capture import get_capture_service
from .services.notification_history import NotificationHistoryService
from .services.screenrec import ScreenrecService
from .services.theme import get_theme_service
from gi.repository import GLib, Gtk
from fabric.notifications import Notifications
tray = SystemTray(name="system-tray", spacing=2, icon_size=16)
get_i3_connection()
# Subscribe before the main loop runs so fenster's replayed capture state
# (sent right after SUBSCRIBE) is not missed.
get_capture_service()
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()
dmenu_menu = DmenuMenu()
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
theme_button: ThemeToggleButton | None = (
ThemeToggleButton(get_darkman_service()) if DARKMAN.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,
theme_button=theme_button,
monitor=0,
width=NOTIFICATIONS.get("center_width", 380),
)
org_service: OrgService | None = None
org_dropdown: OrgDropdown | None = None
if ORG.get("enable", False):
org_service = OrgService(
update_interval=int(ORG.get("update_interval", 60_000)),
)
org_dropdown = OrgDropdown(service=org_service, monitor=0)
bar_windows = []
notmuch_widget = None
_app_windows = [dummy, finder, app_launcher, clipboard_menu, power_menu, screenshot_menu, notmuch_search_menu, dmenu_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)
if org_dropdown is not None:
_app_windows.append(org_dropdown)
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 open_dmenu(request_dir: str):
"""Driven by `sims-cli dmenu`; see sims/modules/launcher/dmenu.py."""
dmenu_menu.open_request(request_dir)
@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()
@Application.action()
def theme_toggle():
if DARKMAN.get("enable", False):
get_darkman_service().toggle()
@Application.action()
def theme_set_light():
if DARKMAN.get("enable", False):
get_darkman_service().set_mode("light")
@Application.action()
def theme_set_dark():
if DARKMAN.get("enable", False):
get_darkman_service().set_mode("dark")
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
app.set_stylesheet_from_file(get_relative_path("styles/main.css"))
if STYLIX.get("enable", False):
# Own the stylix provider so a light/dark switch can reload its data in
# place; GTK restyles every widget when a provider changes.
stylix_provider = Gtk.CssProvider()
theme_service = get_theme_service()
def _load_stylix_css(mode=None):
css = generate_stylix_css(mode)
if css is None:
return
try:
stylix_provider.load_from_data(css.encode())
except GLib.Error as e:
logger.error(f"[Bar] Failed to load Stylix CSS: {e.message}")
_load_stylix_css(theme_service.mode)
app.add_style_provider(stylix_provider)
theme_service.connect("changed", lambda _svc, mode: _load_stylix_css(mode))
logger.info("[Bar] Using Stylix CSS")
else:
logger.info("[Bar] Using default 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,
control_center=control_center if i == 0 else None,
org_service=org_service,
org_dropdown=org_dropdown 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()
+249
View File
@@ -0,0 +1,249 @@
import time
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from fabric.widgets.overlay import Overlay
from fabric.widgets.centerbox import CenterBox
from fabric.utils import invoke_repeater
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.buddy import Buddy
from sims.modules.org import OrgDropdown, OrgWidget
from sims.modules.capture import CaptureWidget
from sims.modules.microphone import MicrophoneWidget
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.org import OrgService
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 get_system_stats_service
from sims.config import BATTERY, BAR_HEIGHT, WINDOW_TITLE, NOTMUCH, BUDDY, ORG
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,
org_service: OrgService | None = None,
org_dropdown: OrgDropdown | 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,
)
self.date_time = Button(
name="date-time-button",
child=Clock(),
on_clicked=self._on_date_time_clicked,
)
self.control_center = control_center
self.system_tray = tray
self.active_window = FensterActiveWindow(
name="active-window",
max_length=50,
)
# CPU/RAM as concentric "activity rings": outer = RAM, inner = CPU.
ring = dict(line_width=3, start_angle=-90, end_angle=270,
h_align="center", v_align="center")
self.ram_progress_bar = CircularProgressBar(
name="ram-progress-bar", size=18, **ring
)
self.cpu_progress_bar = CircularProgressBar(
name="cpu-progress-bar", size=8, **ring
)
self.progress_bars_overlay = Overlay(
name="system-stats",
child=self.ram_progress_bar,
overlays=[self.cpu_progress_bar],
)
self.player = Player()
self.player_small = PlayerSmall(monitor=monitor)
self.battery = None
if BATTERY["enable"]:
self.battery = Battery()
self.notmuch = None
if NOTMUCH["enable"]:
self.notmuch = NotmuchWidget()
self.buddy = None
if BUDDY.get("enable", False):
notmuch_service = self.notmuch.service if self.notmuch is not None else None
self.buddy = Buddy(notmuch_service=notmuch_service)
self.capture = CaptureWidget(screenrec_service=screenrec_service)
self.org = None
if org_service is not None:
self.org = OrgWidget(service=org_service, dropdown=org_dropdown)
self.microphone = MicrophoneWidget()
# One chip for the ambient system state; attention items (org,
# mail, screen share) stay separate so they can light up.
status_children = [self.microphone, self.progress_bars_overlay]
if self.system_tray:
status_children.append(self.system_tray)
if self.battery:
status_children.append(self.battery)
self.status_container = Box(
name="widgets-container",
spacing=6,
orientation="h",
children=status_children,
)
end_container_children = []
if self.org is not None:
end_container_children.append(self.org)
if self.notmuch:
end_container_children.append(self.notmuch)
end_container_children.append(self.capture)
end_container_children.append(self.status_container)
end_container_children.append(self.date_time)
center_children = []
if WINDOW_TITLE["enable"]:
center_children.append(self.active_window)
start_container_children = [
# Nerd Font glyph (nf-linux-nixos) rather than the nix-snowflake-white
# icon: that SVG is hard-coded white and vanishes on light themes,
# while a glyph follows the CSS `color`.
Label(name="nixos-label", label="\uf313"),
self.workspaces,
self.player_small,
]
if self.buddy is not None:
start_container_children.append(self.buddy)
self.inner = CenterBox(
name="sims-inner",
start_children=Box(
name="start-container",
spacing=8,
orientation="h",
children=start_container_children,
),
center_children=Box(
name="center-container",
spacing=4,
orientation="h",
children=center_children,
),
end_children=Box(
name="end-container",
spacing=6,
orientation="h",
children=end_container_children,
),
)
self.children = self.inner
self.system_stats_service = get_system_stats_service()
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
self.progress_bars_overlay.set_tooltip_text(
f"CPU {cpu_percent * 100:.0f}% · RAM {memory_percent * 100:.0f}%"
)
def _on_date_time_clicked(self, _button=None):
if self.control_center is not None:
self.control_center.toggle()
class Clock(Box):
"""Bold time + muted date, e.g. `20:26 Mon 22 Jul`."""
def __init__(self, **kwargs):
self._time = Label(name="clock-time")
self._date = Label(name="clock-date")
super().__init__(
name="date-time",
orientation="h",
spacing=8,
children=[self._time, self._date],
**kwargs,
)
invoke_repeater(1000, self._update)
def _update(self) -> bool:
now = time.localtime()
self._time.set_label(time.strftime("%H:%M", now))
self._date.set_label(time.strftime("%a %d %b", now))
return True
+54
View File
@@ -0,0 +1,54 @@
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 get_battery_service
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%")
# Shared battery service with signal-based updates (one poller for the
# whole process, including the buddy's battery checks)
self.battery_service = get_battery_service()
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")
+23
View File
@@ -0,0 +1,23 @@
from fabric.widgets.box import Box
from sims.widgets.buddy import BuddyWidget
from sims.services.buddy import get_buddy_service
class Buddy(Box):
def __init__(self, notmuch_service=None, **kwargs):
super().__init__(name="buddy-container", v_align="center", **kwargs)
self.service = get_buddy_service(notmuch_service=notmuch_service)
self.sprite = BuddyWidget(on_pet=self._on_pet)
self.service.connect("mood-changed", self._on_mood_changed)
self.children = [self.sprite]
# The shared service only emits on *changes* and may already sit in a
# non-idle mood when this output's sprite is built: adopt it now.
self.sprite.update_mood(self.service.mood)
def _on_mood_changed(self, _service, mood: str):
self.sprite.update_mood(mood)
def _on_pet(self, **kwargs):
if kwargs.get("petted"):
self.service.pet()
+210
View File
@@ -0,0 +1,210 @@
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:
# khal 0.11.3 does not support the newer `--json` output flags.
# Use the documented `list --format ... --day-format ... START DELTA`
# form instead and parse one event per line. `{bell}` is an uncommon
# control-code delimiter supported by khal's formatter.
cmd = [
khal_path,
"list",
"--format",
"{start-date}{bell}{start-time}{bell}{end-date}{bell}{end-time}{bell}{title}{bell}{location}",
"--day-format",
"",
"today",
"eod",
]
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():
all_events = []
for line in result.stdout.splitlines():
if not line.strip():
continue
parts = line.split("\a", 5)
if len(parts) != 6:
logger.warning(f"[Calendar] Could not parse khal output line: {line}")
continue
start_date, start_time, end_date, end_time, title, location = parts
all_events.append(
{
"title": title.strip() or "No title",
"start": f"{start_date} {start_time}".strip() if start_time else "",
"end": f"{end_date} {end_time}".strip() if end_time else "",
"location": location.strip(),
}
)
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()
+92
View File
@@ -0,0 +1,92 @@
"""Screen-share indicator.
Minimal by default: a single red dot, visible only while fenster reports an
active screen capture (portal screen shares, wl-screenrec, ...). Hovering
slides out a short summary of what is being captured; the tooltip lists every
captured output/window. Clicking stops a running sims screen recording.
"""
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from fabric.widgets.revealer import Revealer
from sims.services.capture import CaptureService, get_capture_service
from sims.services.screenrec import ScreenrecService
SUMMARY_MAX_CHARS = 40
def _window_label(window: dict) -> str:
return window.get("app_id") or window.get("title") or f"window {window.get('id')}"
def _sessions_suffix(entry: dict) -> str:
sessions = entry.get("sessions", 1)
return f" ({sessions}×)" if isinstance(sessions, int) and sessions > 1 else ""
class CaptureWidget(Button):
def __init__(
self,
service: CaptureService | None = None,
screenrec_service: ScreenrecService | None = None,
**kwargs,
):
self._service = service or get_capture_service()
self._screenrec = screenrec_service
self._dot = Label(name="capture-dot", label="●")
self._summary = Label(name="capture-summary", label="")
self._revealer = Revealer(
child=self._summary,
transition_type="slide-left",
transition_duration=200,
)
super().__init__(
name="capture-widget",
child=Box(orientation="h", children=[self._revealer, self._dot]),
on_clicked=self._on_clicked,
visible=False,
**kwargs,
)
self.set_no_show_all(True)
self.connect("enter-notify-event", lambda *_: self._revealer.reveal())
self.connect("leave-notify-event", lambda *_: self._revealer.unreveal())
self._service.connect("capture-changed", self._update)
if self._screenrec is not None:
self._screenrec.connect("recording-changed", self._update)
self._update()
def _on_clicked(self, *_):
if self._screenrec is not None and self._screenrec.recording:
self._screenrec.stop()
def _update(self, *_):
outputs = self._service.outputs
windows = self._service.windows
if not (outputs or windows):
self._revealer.unreveal()
self.set_visible(False)
return
names = [o.get("name", "?") for o in outputs] + [_window_label(w) for w in windows]
summary = "Sharing " + ", ".join(names)
if len(summary) > SUMMARY_MAX_CHARS:
summary = summary[: SUMMARY_MAX_CHARS - 1] + "…"
self._summary.set_label(summary)
lines = [f"Monitor {o.get('name', '?')}{_sessions_suffix(o)}" for o in outputs]
for w in windows:
title = w.get("title")
label = _window_label(w)
detail = f"{label} — {title}" if title and title != label else label
lines.append(f"Window {detail}{_sessions_suffix(w)}")
if self._screenrec is not None and self._screenrec.recording:
lines.append("Click to stop recording")
self.set_tooltip_text("\n".join(lines))
self.set_visible(True)
+363
View File
@@ -0,0 +1,363 @@
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.theme_toggle import ThemeToggleButton
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,
theme_button: ThemeToggleButton | 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._theme_button = theme_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 = []
settings_rows = [
(label, widget)
for label, widget in (
("Dark Mode", theme_button),
("Vinyl Passthrough", vinyl_button),
)
if widget is not None
]
if settings_rows:
sections.append(self._build_settings_section(settings_rows))
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, rows: list) -> Box:
section = self._build_section("control-center-settings", "Settings")
for label, widget in rows:
row = Box(
name="control-center-settings-row",
orientation="h",
spacing=8,
)
row.pack_start(
Label(
name="control-center-settings-label",
label=label,
h_align="start",
),
True,
True,
0,
)
row.pack_end(widget, 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
+12
View File
@@ -0,0 +1,12 @@
from .base import FuzzyMenu, LauncherProvider, StaticAction, StaticActionProvider
from .dmenu import DmenuMenu
from .windows import WindowProvider
__all__ = [
"DmenuMenu",
"FuzzyMenu",
"LauncherProvider",
"StaticAction",
"StaticActionProvider",
"WindowProvider",
]
+129
View File
@@ -0,0 +1,129 @@
import re
import shlex
import subprocess
import time
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
from .history import LaunchHistory
from .ranking import rank_items
ICON_SIZE = 32
_FIELD_CODE_RE = re.compile(r"^%[fFuUickdDnNvm]$")
class AppProvider:
def __init__(self, history: LaunchHistory | None = None):
self._history = history if history is not None else LaunchHistory()
def items(self) -> list[DesktopApp]:
return get_desktop_applications()
def filter(self, items: list[DesktopApp], query: str) -> list[DesktopApp]:
"""Rank apps against *query*, best match first.
With an empty query everything matches equally, so the order is
purely "what gets launched most" - the launcher opens on your
most useful apps instead of an arbitrary alphabetical slice.
"""
now = time.time()
return rank_items(
items,
query,
_fields,
bonus_of=lambda app: self._history.bonus(_app_key(app), now=now),
tie_break_of=_sort_name,
)
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:
self._history.record(_app_key(item))
# 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 _fields(app: DesktopApp) -> dict[str, str | None]:
return {
"name": app.name,
"display_name": app.display_name,
"generic_name": app.generic_name,
"executable": app.executable,
}
def _sort_name(app: DesktopApp) -> str:
return (app.display_name or app.name or "").casefold()
def _app_key(app: DesktopApp) -> str:
"""Stable identity for the launch history.
DesktopApp does not expose the desktop file id, but it wraps the
GioUnix.DesktopAppInfo which does. Fall back to the command line
(unique per Steam game) and finally the name.
"""
info = getattr(app, "_app", None)
get_id = getattr(info, "get_id", None) if info is not None else None
if callable(get_id):
try:
app_id = get_id()
except Exception: # pragma: no cover - defensive
app_id = None
if isinstance(app_id, str) and app_id:
return app_id
return app.command_line or app.executable or app.name or ""
def AppLauncher(monitor: int = 0) -> FuzzyMenu:
return FuzzyMenu(
provider=AppProvider(),
monitor=monitor,
placeholder="Search Apps...",
window_name="app-launcher",
max_results=8,
)
+212
View File
@@ -0,0 +1,212 @@
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
from .ranking import rank_items
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]:
# Fixed menus (screenshot, power, screenrec) have no history: an
# empty query keeps the declaration order, a real query is ranked
# like everything else in the launcher.
return rank_items(
items,
query,
lambda action: {"label": action.label},
weights={"label": 1.0},
)
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()
+80
View File
@@ -0,0 +1,80 @@
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
from .ranking import rank_items
@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]:
# Empty query keeps cliphist's newest-first order; a query is
# ranked like every other launcher menu.
return rank_items(
items,
query,
lambda entry: {"preview": entry.preview},
weights={"preview": 1.0},
)
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,
)
+199
View File
@@ -0,0 +1,199 @@
"""dmenu-compatible picker driven by ``sims-cli dmenu``.
The CLI writes ``request.json`` (prompt + lines) into a private directory,
listens on ``reply.sock`` in that same directory and invokes the
``open-dmenu`` action with the directory path. The menu answers by
connecting to the socket and sending the chosen line verbatim (or nothing
when cancelled), so the CLI can print it on stdout like dmenu would.
Lines produced by xdg-desktop-portal-wlr's screencast chooser
(``Monitor: <name> <description>`` / ``Window: <title> (<identifier>)``) get
a nicer rendering; everything else is shown as plain text.
"""
from __future__ import annotations
import json
import os
import re
import socket
from dataclasses import dataclass
from fabric.widgets.box import Box
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from gi.repository import Gtk
from loguru import logger
from sims.services.i3 import I3, I3MessageType
from .base import FuzzyMenu
from .ranking import rank_items
ICON_SIZE = 32
_MONITOR_RE = re.compile(r"^Monitor: (?P<name>\S+)(?: (?P<desc>.*))?$")
_WINDOW_RE = re.compile(r"^Window: (?P<title>.*) \((?P<ident>[^()]*)\)$")
_WEIGHTS = {"title": 1.0, "detail": 0.6}
@dataclass
class DmenuItem:
line: str
kind: str # "monitor" | "window" | "plain"
title: str
detail: str = ""
icon_name: str | None = None
def _window_app_ids() -> dict[str, str]:
"""Map window title -> app_id from fenster's tree (best effort)."""
reply = I3.send_command("", I3MessageType.GET_TREE)
if not (reply.is_ok and isinstance(reply.reply, dict)):
return {}
out: dict[str, str] = {}
stack = [reply.reply]
while stack:
node = stack.pop()
if node.get("type") == "con" and node.get("name") and node.get("app_id"):
out.setdefault(node["name"], node["app_id"])
stack.extend(node.get("nodes", []))
stack.extend(node.get("floating_nodes", []))
return out
def _icon_for_app_id(app_id: str | None) -> str:
theme = Gtk.IconTheme.get_default()
if app_id and theme is not None:
for candidate in (app_id, app_id.lower(), app_id.rsplit(".", 1)[-1].lower()):
if theme.has_icon(candidate):
return candidate
return "application-x-executable"
def parse_lines(lines: list[str]) -> list[DmenuItem]:
app_ids: dict[str, str] | None = None
items: list[DmenuItem] = []
for line in lines:
if m := _MONITOR_RE.match(line):
items.append(
DmenuItem(
line=line,
kind="monitor",
title=m["name"],
detail=m["desc"] or "",
icon_name="video-display",
)
)
elif m := _WINDOW_RE.match(line):
if app_ids is None:
try:
app_ids = _window_app_ids()
except Exception as e: # pragma: no cover - defensive
logger.warning(f"[dmenu] could not query window tree: {e}")
app_ids = {}
app_id = app_ids.get(m["title"])
items.append(
DmenuItem(
line=line,
kind="window",
title=m["title"] or "(untitled)",
detail=app_id or "",
icon_name=_icon_for_app_id(app_id),
)
)
else:
items.append(DmenuItem(line=line, kind="plain", title=line))
return items
class DmenuProvider:
def __init__(self):
self._items: list[DmenuItem] = []
self.on_select = lambda _line: None
def set_lines(self, lines: list[str]) -> None:
self._items = parse_lines(lines)
def items(self) -> list[DmenuItem]:
return list(self._items)
def filter(self, items: list[DmenuItem], query: str) -> list[DmenuItem]:
return rank_items(
items,
query,
lambda item: {"title": item.title, "detail": item.detail},
weights=_WEIGHTS,
)
def render(self, item: DmenuItem) -> Gtk.Widget:
if item.kind == "plain":
return Box(
name="slot-box",
orientation="h",
children=[Label(label=item.title, h_align="start")],
)
children: list[Gtk.Widget] = []
if item.icon_name:
children.append(
Image(name="app-icon", icon_name=item.icon_name, icon_size=ICON_SIZE)
)
text_box = Box(name="app-text", orientation="v", spacing=0)
text_box.add(
Label(label=item.title, name="app-name", h_align="start", ellipsization="end")
)
kind = "Monitor" if item.kind == "monitor" else "Window"
detail = f"{kind} · {item.detail}" if item.detail else kind
text_box.add(
Label(label=detail, name="app-generic", h_align="start", ellipsization="end")
)
children.append(text_box)
return Box(name="slot-box", orientation="h", spacing=10, children=children)
def activate(self, item: DmenuItem) -> None:
self.on_select(item.line)
class DmenuMenu(FuzzyMenu):
def __init__(self, monitor: int = 0):
# Set before FuzzyMenu/Window init, which may call hide().
self._reply_path: str | None = None
self._dmenu = DmenuProvider()
self._dmenu.on_select = self._finish
super().__init__(
provider=self._dmenu,
monitor=monitor,
placeholder="Select...",
window_name="dmenu",
max_results=10,
)
def open_request(self, request_dir: str) -> None:
with open(os.path.join(request_dir, "request.json"), encoding="utf-8") as f:
request = json.load(f)
# A new request supersedes any pending one.
self._finish(None)
self._reply_path = os.path.join(request_dir, "reply.sock")
self._dmenu.set_lines([str(line) for line in request.get("lines", [])])
self.search_entry.set_placeholder_text(request.get("prompt") or "Select...")
self.show()
def hide(self):
super().hide()
# Escape / Ctrl-G / activation all end up here; activation already
# replied, so this only fires for a real cancel.
self._finish(None)
def _finish(self, line: str | None) -> None:
path, self._reply_path = self._reply_path, None
if path is None:
return
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(1.0)
sock.connect(path)
if line is not None:
sock.sendall(line.encode("utf-8") + b"\n")
except OSError as e:
logger.warning(f"[dmenu] could not reply to {path}: {e}")
+167
View File
@@ -0,0 +1,167 @@
"""Persistent launch history for the app launcher.
Remembers how often and how recently each application was launched so
``AppProvider`` can rank frequently used apps first (frecency, the
same frequency + recency idea as zoxide). The file lives in the system
cache directory - losing it only resets the ranking, never breaks the
launcher.
Layout (JSON, written atomically)::
{"version": 1, "entries": {"steam.desktop": {"count": 12, "last_used": 1712345678.0}}}
"""
from __future__ import annotations
import json
import os
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
from loguru import logger
from platformdirs import user_cache_dir
from .ranking import frecency, popularity_bonus
CACHE_VERSION = 1
MAX_ENTRIES = 500
MAX_AGE_DAYS = 365.0
DEFAULT_HALF_LIFE_DAYS = 30.0
def default_cache_path() -> Path:
return Path(user_cache_dir("sims")) / "launcher-history.json"
@dataclass
class _Entry:
count: int = 0
last_used: float = 0.0
class LaunchHistory:
"""Launch counts/recency, keyed by launcher-specific item id."""
def __init__(
self,
path: Path | str | None = None,
*,
half_life_days: float = DEFAULT_HALF_LIFE_DAYS,
):
self.path = Path(path) if path is not None else default_cache_path()
self._half_life_days = half_life_days
self._entries: dict[str, _Entry] = self._load()
def record(self, key: str, *, now: float | None = None) -> None:
"""Count one launch of *key* and persist the history."""
if not key:
return
now = time.time() if now is None else now
entry = self._entries.get(key)
if entry is None:
entry = self._entries[key] = _Entry()
entry.count += 1
entry.last_used = now
self._save()
def bonus(
self,
key: str,
*,
now: float | None = None,
max_bonus: float = 150.0,
) -> float:
"""Bounded popularity bonus for *key*, 0.0 when unknown."""
entry = self._entries.get(key)
if entry is None or entry.count <= 0:
return 0.0
now = time.time() if now is None else now
score = frecency(
entry.count,
entry.last_used,
now,
half_life_days=self._half_life_days,
)
return popularity_bonus(score, max_bonus=max_bonus)
# -- persistence ------------------------------------------------------
def _load(self) -> dict[str, _Entry]:
try:
with open(self.path, "r", encoding="utf-8") as handle:
data = json.load(handle)
except FileNotFoundError:
return {}
except (OSError, ValueError) as exc:
logger.warning("launcher history {} unreadable: {}", self.path, exc)
return {}
raw_entries = data.get("entries") if isinstance(data, dict) else None
if not isinstance(raw_entries, dict):
logger.warning("launcher history {}: unexpected format", self.path)
return {}
entries: dict[str, _Entry] = {}
for key, raw in raw_entries.items():
if not isinstance(raw, dict):
continue
try:
count = int(raw.get("count", 0))
last_used = float(raw.get("last_used", 0.0))
except (TypeError, ValueError):
continue
if count > 0:
entries[key] = _Entry(count=count, last_used=last_used)
return self._prune(entries, time.time())
def _prune(self, entries: dict[str, _Entry], now: float) -> dict[str, _Entry]:
cutoff = now - MAX_AGE_DAYS * 86_400.0
kept = {
key: entry
for key, entry in entries.items()
if entry.count > 0 and entry.last_used >= cutoff
}
if len(kept) > MAX_ENTRIES:
top = sorted(
kept.items(),
key=lambda item: frecency(
item[1].count,
item[1].last_used,
now,
half_life_days=self._half_life_days,
),
reverse=True,
)[:MAX_ENTRIES]
kept = dict(top)
return kept
def _save(self) -> None:
self._entries = self._prune(self._entries, time.time())
payload = {
"version": CACHE_VERSION,
"entries": {
key: {"count": entry.count, "last_used": entry.last_used}
for key, entry in sorted(self._entries.items())
},
}
temp_path: str | None = None
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_path = tempfile.mkstemp(
dir=self.path.parent, prefix=self.path.name, suffix=".tmp"
)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(payload, handle)
os.replace(temp_path, self.path)
temp_path = None
except OSError as exc:
logger.warning("could not write launcher history {}: {}", self.path, exc)
finally:
if temp_path is not None:
try:
os.unlink(temp_path)
except OSError:
pass
+284
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
+25
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",
)
+263
View File
@@ -0,0 +1,263 @@
"""Search ranking for launcher items.
The launcher used to keep items in provider order (alphabetical for
desktop apps) and filter by plain substring. That breaks as soon as a
query matches several apps through different fields: typing ``steam``
listed every installed Steam game (each of their desktop files has
``Exec=steam steam://rungameid/...``) in the middle of the list, with
Steam itself somewhere in between.
This module scores a query against a set of named fields:
* every whitespace-separated token must match somewhere (AND semantics);
* match *kind* dominates the score:
exact > prefix > word start > substring > subsequence;
* fields are weighted so a match on the user-visible name outranks the
same kind of match on the generic name or the executable;
* a bounded bonus can be added on top (launch frecency, see
``history.py``). The bonus is small enough that it can never beat a
better match kind on the same field.
The score is only used for ordering, so the absolute numbers do not
matter - only the gaps between them.
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
from typing import Any, Callable, Mapping, Sequence, TypeVar
# Fuzzy (subsequence) matching on tiny queries matches almost anything,
# so only use it once the query is long enough to be meaningful.
MIN_SUBSEQUENCE_LEN = 3
Item = TypeVar("Item")
class MatchKind(IntEnum):
NONE = 0
SUBSEQUENCE = 1
SUBSTRING = 2
WORD_PREFIX = 3
PREFIX = 4
EXACT = 5
# Base score per match kind. The gaps are much larger than any quality
# or popularity bonus, so a better kind of match on the same field always
# wins over a bonus-carrying worse one.
_KIND_SCORE: Mapping[MatchKind, float] = {
MatchKind.EXACT: 1000.0,
MatchKind.PREFIX: 650.0,
MatchKind.WORD_PREFIX: 450.0,
MatchKind.SUBSTRING: 250.0,
MatchKind.SUBSEQUENCE: 90.0,
}
# Weight of the match *quality* (max 75 points total):
_POSITION_WEIGHT = 25.0 # earlier in the field is better
_COVERAGE_WEIGHT = 25.0 # token covers more of the field is better
_CONTIGUITY_WEIGHT = 25.0 # subsequence: fewer skipped chars is better
# How much each desktop-entry field counts. The name must always beat
# generic-name/executable matches, otherwise every Steam game (Exec=
# "steam steam://rungameid/<id>") drowns out Steam itself.
DEFAULT_FIELD_WEIGHTS: Mapping[str, float] = {
"name": 1.0,
"display_name": 0.95,
"generic_name": 0.45,
"executable": 0.55,
}
@dataclass(frozen=True)
class FieldMatch:
"""Where and how a token matched a single field."""
kind: MatchKind
position: int
span: int
def quality(self, value_len: int, token_len: int) -> float:
value_len = max(value_len, 1)
position = 1.0 - self.position / value_len
coverage = token_len / value_len
contiguity = token_len / max(self.span, 1)
return (
_POSITION_WEIGHT * position
+ _COVERAGE_WEIGHT * coverage
+ _CONTIGUITY_WEIGHT * contiguity
)
def _is_word_start(value: str, position: int) -> bool:
return position == 0 or not value[position - 1].isalnum()
def _subsequence_span(value: str, token: str) -> tuple[int, int] | None:
"""Greedy subsequence match; returns (start, span) or None."""
first = -1
last = -1
index = 0
for position, char in enumerate(value):
if char == token[index]:
if first == -1:
first = position
last = position
index += 1
if index == len(token):
return first, last - first + 1
return None
def find_match(value: str, token: str) -> FieldMatch | None:
"""Best match of *token* inside *value* (both lowercased here).
Returns None when the token does not occur in the field at all.
"""
if not value or not token:
return None
value = value.lower()
token = token.lower()
if value == token:
return FieldMatch(MatchKind.EXACT, 0, len(token))
if value.startswith(token):
return FieldMatch(MatchKind.PREFIX, 0, len(token))
position = value.find(token)
if position != -1:
kind = (
MatchKind.WORD_PREFIX
if _is_word_start(value, position)
else MatchKind.SUBSTRING
)
return FieldMatch(kind, position, len(token))
if len(token) >= MIN_SUBSEQUENCE_LEN:
span = _subsequence_span(value, token)
if span is not None:
return FieldMatch(MatchKind.SUBSEQUENCE, span[0], span[1])
return None
def score_token(
token: str,
fields: Mapping[str, str | None],
weights: Mapping[str, float] = DEFAULT_FIELD_WEIGHTS,
) -> float | None:
"""Best weighted score of *token* across *fields*, or None."""
best: float | None = None
for field, weight in weights.items():
value = fields.get(field)
if not value:
continue
match = find_match(value, token)
if match is None:
continue
score = weight * (
_KIND_SCORE[match.kind] + match.quality(len(value), len(token))
)
if best is None or score > best:
best = score
return best
def score_query(
query: str,
fields: Mapping[str, str | None],
weights: Mapping[str, float] = DEFAULT_FIELD_WEIGHTS,
) -> float | None:
"""Score an item for *query*: None unless every token matches.
An empty query matches everything with score 0.0, which lets callers
fall back to time/frequency based ordering.
"""
tokens = query.split()
if not tokens:
return 0.0
total = 0.0
for token in tokens:
token_score = score_token(token, fields, weights)
if token_score is None:
return None
total += token_score
return total / len(tokens)
def rank_items(
items: Sequence[Item],
query: str,
fields_of: Callable[[Item], Mapping[str, str | None]],
*,
weights: Mapping[str, float] = DEFAULT_FIELD_WEIGHTS,
bonus_of: Callable[[Item], float] | None = None,
tie_break_of: Callable[[Item], Any] | None = None,
) -> list[Item]:
"""Rank *items* by how well they match *query*, best first.
This is the shared filter for every launcher provider: apps, windows,
clipboard entries and static action menus all describe their searchable
text as weighted fields via *fields_of*.
With an empty query the provider order is kept, unless *bonus_of* is
given - then items are ordered by bonus instead (used by the app
launcher to show launch frecency). *bonus_of* is added to the match
score and must stay small enough not to outrank a better match kind.
Ties keep provider order, or fall back to *tie_break_of* when given.
"""
if not query.split():
if bonus_of is None:
return list(items)
scored = [(bonus_of(item), item) for item in items]
else:
scored = []
for item in items:
score = score_query(query, fields_of(item), weights)
if score is None:
continue
if bonus_of is not None:
score += bonus_of(item)
scored.append((score, item))
if tie_break_of is None:
scored.sort(key=lambda pair: -pair[0])
else:
scored.sort(key=lambda pair: (-pair[0], tie_break_of(pair[1])))
return [item for _, item in scored]
def frecency(
count: int,
last_used: float | None,
now: float,
*,
half_life_days: float = 30.0,
) -> float:
"""Launch count decayed by age with the given half-life."""
if count <= 0:
return 0.0
if last_used is None:
return float(count)
age_days = max(0.0, (now - last_used) / 86_400.0)
return count * 0.5 ** (age_days / max(half_life_days, 1e-6))
def popularity_bonus(
frecency_score: float,
*,
max_bonus: float = 150.0,
half_bonus_at: float = 5.0,
) -> float:
"""Saturating, monotonic map of frecency into ``[0, max_bonus)``.
Keeps the launch-history signal bounded so it can reorder equal
matches but never beat a better match kind.
"""
if frecency_score <= 0.0:
return 0.0
return max_bonus * frecency_score / (frecency_score + half_bonus_at)
+30
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",
)
+23
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",
)
+72
View File
@@ -0,0 +1,72 @@
from sims.services.i3 import I3, I3MessageType
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from gi.repository import Gtk
from .ranking import rank_items
# A window title is what people search for; the app id is a fallback.
# Weighted below 0.65 on purpose: an exact app-id match must not beat a
# window whose *title* starts with the query, so a query like "firefox"
# still orders the Firefox windows by their titles.
_WINDOW_WEIGHTS = {"title": 1.0, "app_id": 0.6}
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]:
# No history for windows - empty query keeps workspace order,
# typed queries are ranked by title/app id match quality.
return rank_items(
items,
query,
lambda window: {
"title": window.get("title", ""),
"app_id": window.get("app_id", ""),
},
weights=_WINDOW_WEIGHTS,
)
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")
+503
View File
@@ -0,0 +1,503 @@
"""Hover card for the bar's compact media player.
A layer-shell popup that drops down below `PlayerSmall` while the pointer
rests on it: large spinning cover, full track metadata, a seekable progress
bar, transport controls (shuffle / previous / play-pause / next / loop) and,
when more than one MPRIS player is around, a row to switch between them.
The card holds no MPRIS state of its own — `PlayerSmall` owns the tracked
players and the active selection and pushes updates in via `set_players`,
`set_active`, `refresh` and `set_cover`.
"""
from collections.abc 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 fabric.widgets.scale import Scale
from fabric.widgets.stack import Stack
from fabric.widgets.wayland import WaylandWindow as Window
from gi.repository import GLib, Gdk
from loguru import logger
from sims.services.mpris import MprisPlayer
from sims.utils.artwork import file_key
from sims.widgets.circle_image import CircleImage
CARD_WIDTH = 360
COVER_SIZE = 96
PROGRESS_INTERVAL_MS = 500
PLAY_ICON = "media-playback-start-symbolic"
PAUSE_ICON = "media-playback-pause-symbolic"
PREV_ICON = "media-skip-backward-symbolic"
NEXT_ICON = "media-skip-forward-symbolic"
SHUFFLE_ICON = "media-playlist-shuffle-symbolic"
LOOP_ICON = "media-playlist-repeat-symbolic"
LOOP_TRACK_ICON = "media-playlist-repeat-song-symbolic"
FALLBACK_ICON = "audio-x-generic-symbolic"
LOOP_CYCLE = {"none": "playlist", "playlist": "track", "track": "none"}
def _safe(fn: Callable, default=None):
"""MPRIS properties raise once the underlying player has exited (the
wrapper drops `_player`) and DBus calls can fail at any time; the card
should degrade to defaults instead of throwing out of a GTK callback."""
try:
return fn()
except Exception:
return default
def _format_time(us: int) -> str:
seconds = max(0, int(us / 1_000_000))
hours, rem = divmod(seconds, 3600)
minutes, seconds = divmod(rem, 60)
if hours:
return f"{hours}:{minutes:02}:{seconds:02}"
return f"{minutes}:{seconds:02}"
def _icon_button(name: str, icon: str, size: int = 16, **kwargs) -> Button:
return Button(
name=name,
child=Image(icon_name=icon, icon_size=size),
**kwargs,
)
class MediaCard(Window):
def __init__(
self,
monitor: int | None = None,
on_select_player: Callable[[MprisPlayer], None] | None = None,
):
super().__init__(
name="media-card",
title="sims-media-card",
layer="top",
anchor="top left",
margin=(6, 0, 0, 0),
exclusivity="none",
keyboard_mode="none",
visible=False,
monitor=monitor,
)
self._on_select_player = on_select_player
self._player: MprisPlayer | None = None
self._players: list[MprisPlayer] = []
self._progress_timer_id: int | None = None
self._spin_timer_id: int | None = None
self._seeking = False
self._cover_key: tuple[str, int] | None = None
# Player names whose shuffle / loop writes were rejected; their
# buttons stay disabled so they don't look like they do something.
self._no_shuffle: set[str] = set()
self._no_loop: set[str] = set()
# --- cover -------------------------------------------------------
self.cover = CircleImage(
name="media-card-cover", size=COVER_SIZE, h_align="center", v_align="center"
)
self.cover_fallback = Image(
name="media-card-cover-fallback", icon_name=FALLBACK_ICON, icon_size=48
)
self.cover_stack = Stack(
name="media-card-cover-stack",
transition_type="crossfade",
transition_duration=200,
children=[self.cover_fallback, self.cover],
v_align="center",
)
self.cover_stack.set_size_request(COVER_SIZE, COVER_SIZE)
self.cover_stack.set_visible_child(self.cover_fallback)
# --- metadata ----------------------------------------------------
def meta_label(name: str) -> Label:
label = Label(
name=name, h_align="fill", ellipsization="end", max_chars_width=1
)
label.set_xalign(0.0)
label.set_hexpand(True)
return label
self.player_label = meta_label("media-card-player")
self.title = meta_label("media-card-title")
self.artist = meta_label("media-card-artist")
self.album = meta_label("media-card-album")
meta = Box(
name="media-card-meta",
orientation="v",
spacing=2,
h_expand=True,
v_align="center",
children=[self.player_label, self.title, self.artist, self.album],
)
header = Box(
name="media-card-header",
orientation="h",
spacing=14,
children=[self.cover_stack, meta],
)
# --- progress ----------------------------------------------------
self.progress = Scale(
name="media-card-progress",
min_value=0.0,
max_value=1.0,
value=0.0,
draw_value=False,
h_expand=True,
increments=(0.01, 0.05),
)
self.progress.connect("button-press-event", self._on_seek_press)
self.progress.connect("button-release-event", self._on_seek_release)
# Scrolling over the card shouldn't silently scrub the track.
self.progress.connect("scroll-event", lambda *_: True)
self.time_current = Label(name="media-card-time", label="0:00", h_align="start")
self.time_total = Label(name="media-card-time", label="0:00", h_align="end")
times = Box(orientation="h", h_expand=True)
times.pack_start(self.time_current, False, False, 0)
times.pack_end(self.time_total, False, False, 0)
progress_box = Box(
name="media-card-progress-box",
orientation="v",
spacing=2,
children=[self.progress, times],
)
# --- controls ----------------------------------------------------
self.shuffle_btn = _icon_button(
"media-card-toggle", SHUFFLE_ICON, on_clicked=self._on_shuffle
)
self.prev_btn = _icon_button(
"media-card-btn", PREV_ICON, size=20, on_clicked=self._on_prev
)
self.play_image = Image(icon_name=PLAY_ICON, icon_size=24)
self.play_btn = Button(
name="media-card-play", child=self.play_image, on_clicked=self._on_play_pause
)
self.next_btn = _icon_button(
"media-card-btn", NEXT_ICON, size=20, on_clicked=self._on_next
)
self.loop_image = Image(icon_name=LOOP_ICON, icon_size=16)
self.loop_btn = Button(
name="media-card-toggle", child=self.loop_image, on_clicked=self._on_loop
)
self.shuffle_btn.set_tooltip_text("Shuffle")
self.prev_btn.set_tooltip_text("Previous")
self.next_btn.set_tooltip_text("Next")
self.loop_btn.set_tooltip_text("Repeat")
controls = Box(
name="media-card-controls",
orientation="h",
spacing=10,
h_align="center",
children=[
self.shuffle_btn,
self.prev_btn,
self.play_btn,
self.next_btn,
self.loop_btn,
],
)
# --- player switcher (only shown with >1 player) -----------------
self.players_box = Box(
name="media-card-players", orientation="h", spacing=6, h_align="center"
)
self.players_box.set_no_show_all(True)
self.body = Box(
name="media-card-body",
orientation="v",
spacing=12,
children=[header, progress_box, controls, self.players_box],
)
self.body.set_size_request(CARD_WIDTH, -1)
self.add(self.body)
self.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK)
self.connect("map", lambda *_: self._on_mapped())
self.connect("unmap", lambda *_: self._on_unmapped())
self.refresh()
# ------------------------------------------------------------------
# public API (driven by PlayerSmall)
# ------------------------------------------------------------------
@property
def player(self) -> MprisPlayer | None:
return self._player
@property
def seeking(self) -> bool:
return self._seeking
def popup(self, x: int) -> None:
"""Show the card with its left edge at `x` (output coordinates)."""
self.margin = (6, 0, 0, max(0, x))
if not self.get_visible():
# Not show_all(): that would resurrect labels/rows refresh() hid.
self.show()
def popdown(self) -> None:
if self.get_visible():
self.hide()
def set_players(self, players: list[MprisPlayer]) -> None:
self._players = list(players)
self._rebuild_player_switcher()
def set_active(self, player: MprisPlayer | None) -> None:
self._player = player
self._seeking = False
self._sync_player_switcher()
self.refresh()
def set_cover(self, path: str | None) -> None:
key = file_key(path)
if key is not None and key == self._cover_key:
return
self._cover_key = None
if key is not None:
try:
self.cover.set_image_from_file(path)
self._cover_key = key
self.cover_stack.set_visible_child(self.cover)
self._update_spin()
return
except Exception as e:
logger.debug(f"[MediaCard] failed to load cover {path}: {e}")
self.cover_stack.set_visible_child(self.cover_fallback)
self._update_spin()
def refresh(self) -> None:
mp = self._player
if mp is None:
self.player_label.set_text("")
self.title.set_text("Nothing playing")
self.artist.set_text("")
self.album.set_text("")
self.artist.set_visible(False)
self.album.set_visible(False)
self.play_image.set_property("icon-name", PLAY_ICON)
for btn in (self.shuffle_btn, self.prev_btn, self.play_btn, self.next_btn, self.loop_btn):
btn.set_sensitive(False)
self.progress.set_sensitive(False)
self.progress.set_value(0.0)
self.time_current.set_text("0:00")
self.time_total.set_text("0:00")
self.cover_stack.set_visible_child(self.cover_fallback)
self._cover_key = None
self._update_spin()
return
name = _safe(lambda: mp.player_name, "") or ""
self.player_label.set_text(name.upper())
title = (_safe(lambda: mp.title, "") or "").strip()
artist = (_safe(lambda: mp.artist, "") or "").strip()
album = (_safe(lambda: mp.album, "") or "").strip()
self.title.set_text(title or "Unknown title")
self.title.set_tooltip_text(title or None)
self.artist.set_text(artist)
self.artist.set_visible(bool(artist))
self.album.set_text(album)
self.album.set_visible(bool(album))
playing = _safe(lambda: mp.playback_status, "") == "playing"
self.play_image.set_property("icon-name", PAUSE_ICON if playing else PLAY_ICON)
self.play_btn.set_tooltip_text("Pause" if playing else "Play")
self.play_btn.set_sensitive(bool(_safe(lambda: mp.can_pause, False)))
self.prev_btn.set_sensitive(bool(_safe(lambda: mp.can_go_previous, False)))
self.next_btn.set_sensitive(bool(_safe(lambda: mp.can_go_next, False)))
self.shuffle_btn.set_sensitive(name not in self._no_shuffle)
self._set_class(self.shuffle_btn, "active", bool(_safe(lambda: mp.shuffle, False)))
loop = _safe(lambda: mp.loop_status, "none")
self.loop_btn.set_sensitive(name not in self._no_loop)
self.loop_image.set_property(
"icon-name", LOOP_TRACK_ICON if loop == "track" else LOOP_ICON
)
self._set_class(self.loop_btn, "active", loop in ("playlist", "track"))
self.loop_btn.set_tooltip_text(
{"playlist": "Repeat: playlist", "track": "Repeat: track"}.get(
loop, "Repeat: off"
)
)
self._update_progress()
self._update_spin()
# ------------------------------------------------------------------
# player switcher
# ------------------------------------------------------------------
def _rebuild_player_switcher(self) -> None:
for child in self.players_box.get_children():
self.players_box.remove(child)
child.destroy()
if len(self._players) < 2:
self.players_box.hide()
return
for mp in self._players:
label = _safe(lambda mp=mp: mp.player_name, "?") or "?"
btn = Button(
name="media-card-player-chip",
child=Label(label=label),
on_clicked=lambda *_, mp=mp: self._select(mp),
)
btn.player = mp
self.players_box.add(btn)
btn.show_all()
self.players_box.show()
self._sync_player_switcher()
def _sync_player_switcher(self) -> None:
for btn in self.players_box.get_children():
self._set_class(btn, "active", getattr(btn, "player", None) is self._player)
def _select(self, mp: MprisPlayer) -> None:
if self._on_select_player is not None:
self._on_select_player(mp)
# ------------------------------------------------------------------
# controls
# ------------------------------------------------------------------
def _on_play_pause(self, *_):
if self._player is not None:
_safe(self._player.play_pause)
def _on_prev(self, *_):
if self._player is not None:
_safe(self._player.previous)
def _on_next(self, *_):
if self._player is not None:
_safe(self._player.next)
def _on_shuffle(self, *_):
mp = self._player
if mp is None:
return
try:
mp.set_shuffle(not mp.shuffle)
except Exception as e:
logger.debug(f"[MediaCard] shuffle unsupported by {mp.player_name}: {e}")
self._no_shuffle.add(mp.player_name)
self.refresh()
def _on_loop(self, *_):
mp = self._player
if mp is None:
return
try:
mp.set_loop(LOOP_CYCLE.get(mp.loop_status, "none"))
except Exception as e:
logger.debug(f"[MediaCard] loop unsupported by {mp.player_name}: {e}")
self._no_loop.add(mp.player_name)
self.refresh()
# ------------------------------------------------------------------
# progress / seeking
# ------------------------------------------------------------------
def _length(self) -> int:
mp = self._player
if mp is None:
return 0
return _safe(lambda: int(mp.length or 0), 0)
def _update_progress(self) -> bool:
mp = self._player
total = self._length()
can_seek = bool(mp is not None and _safe(lambda: mp.can_seek, False))
self.progress.set_sensitive(can_seek and total > 0)
if mp is None or total <= 0:
if not self._seeking:
self.progress.set_value(0.0)
self.time_current.set_text("0:00" if mp is None else "--:--")
self.time_total.set_text("0:00" if mp is None else "--:--")
return True
self.time_total.set_text(_format_time(total))
if self._seeking:
# While dragging, show where the thumb is instead of the player.
self.time_current.set_text(_format_time(self.progress.get_value() * total))
return True
position = _safe(lambda: mp.position, 0) or 0
self.progress.set_value(min(1.0, max(0.0, position / total)))
self.time_current.set_text(_format_time(position))
return True
def _on_seek_press(self, *_):
self._seeking = True
return False
def _on_seek_release(self, *_):
if self._seeking and self._player is not None:
total = self._length()
if total > 0:
target = int(self.progress.get_value() * total)
_safe(lambda: setattr(self._player, "position", target))
self._seeking = False
# Let the scale finish its own release handling before we re-sync.
GLib.timeout_add(150, lambda: (self._update_progress(), False)[1])
return False
# ------------------------------------------------------------------
# timers — only run while the card is on screen
# ------------------------------------------------------------------
def _on_mapped(self):
self._update_progress()
if self._progress_timer_id is None:
self._progress_timer_id = GLib.timeout_add(
PROGRESS_INTERVAL_MS, self._update_progress
)
self._update_spin()
def _on_unmapped(self):
if self._progress_timer_id is not None:
GLib.source_remove(self._progress_timer_id)
self._progress_timer_id = None
self._seeking = False
self._update_spin()
def _update_spin(self):
should_spin = (
self.get_mapped()
and self._player is not None
and self.cover_stack.get_visible_child() is self.cover
and _safe(lambda: self._player.playback_status, "") == "playing"
)
if should_spin and self._spin_timer_id is None:
self._spin_timer_id = GLib.timeout_add(50, self._advance_spin)
elif not should_spin and 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 + 1) % 360
return True
@staticmethod
def _set_class(widget, cls: str, on: bool) -> None:
ctx = widget.get_style_context()
if on and not ctx.has_class(cls):
ctx.add_class(cls)
elif not on and ctx.has_class(cls):
ctx.remove_class(cls)
+67
View File
@@ -0,0 +1,67 @@
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.label import Label
from sims.services.audio import get_audio_service
MIC_ICON = "󰍬"
MIC_MUTED_ICON = "󰍭"
class MicrophoneWidget(Box):
"""Bar widget showing microphone state; click to toggle mute.
Mutes *all* input sources (not just the default one) so virtual
sources like EasyEffects and their underlying hardware mics are
silenced together.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.audio = get_audio_service()
self.icon_label = Label(
name="microphone-icon",
label=MIC_ICON,
)
self.button = Button(
name="microphone-button",
child=self.icon_label,
on_clicked=self.on_clicked,
)
self.add(self.button)
# `changed` fires for any stream change (incl. mute state) and
# `microphone-changed` when the default source switches.
self.audio.connect("changed", self.update_icon)
self.audio.connect("microphone-changed", self.update_icon)
self.update_icon()
def on_clicked(self, *_):
mics = self.audio.microphones or []
if not mics and self.audio.microphone:
mics = [self.audio.microphone]
if not mics:
return
# if anything is live -> mute everything; else unmute everything
mute = self._any_unmuted(mics)
for mic in mics:
mic.muted = mute
self.update_icon()
def _any_unmuted(self, mics) -> bool:
return any(not mic.muted for mic in mics)
def update_icon(self, *_):
mics = self.audio.microphones or []
if not mics and self.audio.microphone:
mics = [self.audio.microphone]
if not mics:
self.set_visible(False)
return
self.set_visible(True)
if self._any_unmuted(mics):
self.icon_label.set_label(MIC_ICON)
self.icon_label.remove_style_class("muted")
else:
self.icon_label.set_label(MIC_MUTED_ICON)
self.icon_label.add_style_class("muted")
+54
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,
)
)
+224
View File
@@ -0,0 +1,224 @@
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(name="notmuch-icon", 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 = get_notmuch_service()
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}"
)
_service: "NotmuchService | None" = None
def get_notmuch_service(update_interval: int = 60000) -> "NotmuchService":
"""Return the process-wide notmuch service, creating it on first use.
Each poll shells out to `notmuch count` twice. Every bar widget used to own
a service, so one `refresh-notmuch` (or one timer tick) opened the database
2 x bars times over; now all widgets share a single poller.
"""
global _service
if _service is None:
_service = NotmuchService(update_interval=update_interval)
return _service
+283
View File
@@ -0,0 +1,283 @@
"""Org-agenda bar widget + dropdown popup.
Bar slot is a small button showing an icon + count of open items. Clicking
toggles a layer-shell dropdown listing items grouped by state. Clicking an
item opens emacsclient at the headline's line.
"""
from __future__ import annotations
import os
import subprocess
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 loguru import logger
from sims.config import BAR_HEIGHT, ORG
from sims.services.org import OrgItem, OrgService, OrgSnapshot
# Order in which states are shown / counted. Anything else discovered at parse
# time is appended after these.
DEFAULT_STATE_ORDER = ["NEXT", "IN-PROGRESS", "TODO"]
def _state_order(states: list[str]) -> list[str]:
seen = set()
ordered: list[str] = []
for s in DEFAULT_STATE_ORDER:
if s in states and s not in seen:
ordered.append(s)
seen.add(s)
for s in states:
if s not in seen:
ordered.append(s)
seen.add(s)
return ordered
def _open_in_emacs(item: OrgItem) -> None:
cmd_template = ORG.get("emacsclient_command", "emacsclient")
parts = cmd_template.split() if isinstance(cmd_template, str) else list(cmd_template)
cmd = [*parts, "-c", f"+{item.line}", item.file]
try:
subprocess.Popen(cmd, start_new_session=True)
logger.info(f"[Org] Opened {item.file}:{item.line} in emacsclient")
except Exception as e:
logger.error(f"[Org] Failed to open emacsclient: {e}")
class OrgDropdown(Window):
def __init__(self, service: OrgService, monitor: int = 0):
width = int(ORG.get("dropdown_width", 420))
super().__init__(
name="org-dropdown",
layer="top",
anchor="top",
margin=f"{BAR_HEIGHT}px 0 0 0",
keyboard_mode="on-demand",
exclusivity="none",
visible=False,
monitor=monitor,
)
self._service = service
self._width = width
self._header = Label(
name="org-dropdown-title",
label="Org Agenda",
h_align="start",
)
close_button = Button(
name="org-dropdown-close",
image=Image(icon_name="window-close-symbolic", icon_size=16),
on_clicked=lambda *_: self.hide(),
)
header_row = Box(name="org-dropdown-header", orientation="h", spacing=8)
header_row.pack_start(self._header, True, True, 0)
header_row.pack_end(close_button, False, False, 0)
self._sections_box = Box(
name="org-dropdown-sections",
orientation="v",
spacing=10,
h_expand=True,
)
scroll = ScrolledWindow(
name="org-dropdown-scroll",
h_scrollbar_policy="never",
v_scrollbar_policy="automatic",
child=self._sections_box,
h_expand=True,
v_expand=True,
)
body = Box(
name="org-dropdown-body",
orientation="v",
spacing=8,
children=[header_row, scroll],
h_expand=True,
v_expand=True,
)
body.set_size_request(self._width, int(ORG.get("dropdown_height", 480)))
self.add(body)
self.connect("key-press-event", self._on_key_press)
self._service.connect("items-changed", lambda _s, snap: self._refresh(snap))
self._refresh(self._service.snapshot)
def toggle(self) -> None:
if self.get_visible():
self.hide()
else:
self.show()
def show(self) -> None: # type: ignore[override]
super().show()
self.show_all()
def _on_key_press(self, _w, event):
if event.keyval == Gdk.KEY_Escape:
self.hide()
return True
return False
def _refresh(self, snapshot: OrgSnapshot) -> None:
for child in self._sections_box.get_children():
self._sections_box.remove(child)
child.destroy()
if not snapshot.items:
self._sections_box.add(
Label(
name="org-dropdown-empty",
label="Nothing on the agenda.",
h_align="start",
)
)
self._sections_box.show_all()
return
by_state: dict[str, list[OrgItem]] = {}
for it in snapshot.items:
by_state.setdefault(it.state, []).append(it)
for state in _state_order(list(by_state.keys())):
items = by_state.get(state, [])
if not items:
continue
section = self._build_section(state, items)
self._sections_box.add(section)
self._sections_box.show_all()
def _build_section(self, state: str, items: list[OrgItem]) -> Box:
section = Box(
name="org-dropdown-section",
orientation="v",
spacing=4,
style_classes=["org-state", f"org-state-{state.lower()}"],
)
header = Box(orientation="h", spacing=6)
header.add(
Label(
name="org-dropdown-section-title",
label=state,
h_align="start",
style_classes=["org-state-label"],
)
)
header.add(
Label(
label=f"({len(items)})",
h_align="start",
style_classes=["org-state-count"],
)
)
section.add(header)
for item in items:
section.add(self._build_item(item))
return section
def _build_item(self, item: OrgItem) -> Button:
title_parts = []
if item.priority:
title_parts.append(f"#{item.priority}")
title_parts.append(item.headline)
if item.tags:
title_parts.append(":" + ":".join(item.tags) + ":")
title = " ".join(title_parts)
title_label = Label(
label=title,
h_align="start",
ellipsization="end",
style_classes=["org-item-title"],
)
meta_bits = []
if item.scheduled:
meta_bits.append(f"S: {item.scheduled}")
if item.deadline:
meta_bits.append(f"D: {item.deadline}")
meta_bits.append(os.path.basename(item.file))
meta_label = Label(
label=" · ".join(meta_bits),
h_align="start",
style_classes=["org-item-meta"],
)
content = Box(orientation="v", spacing=2, h_expand=True)
content.add(title_label)
content.add(meta_label)
button = Button(
name="org-item",
child=content,
on_clicked=lambda *_: self._on_item_clicked(item),
style_classes=["org-item"],
)
return button
def _on_item_clicked(self, item: OrgItem) -> None:
_open_in_emacs(item)
self.hide()
class OrgWidget(Button):
def __init__(self, service: OrgService, dropdown: OrgDropdown | None, **kwargs):
self._service = service
self._dropdown = dropdown
self.icon = Label(label="✓", name="org-icon")
self.label = Label("0", name="org-count")
container = Box(orientation="h", spacing=4, children=[self.icon, self.label])
super().__init__(
name="org-widget",
child=container,
on_clicked=lambda *_: self._on_clicked(),
**kwargs,
)
self._service.connect("items-changed", lambda _s, snap: self._refresh(snap))
self._refresh(self._service.snapshot)
def _on_clicked(self) -> None:
if self._dropdown is not None:
self._dropdown.toggle()
def _refresh(self, snapshot: OrgSnapshot) -> None:
counted = list(ORG.get("counted_states", ["TODO", "NEXT", "IN-PROGRESS"]))
total = snapshot.total_counted(counted)
next_count = snapshot.counts.get("NEXT", 0)
in_progress = snapshot.counts.get("IN-PROGRESS", 0)
self.label.set_text(str(total))
classes = ["org-widget"]
if total == 0:
classes.append("empty")
if next_count > 0:
classes.append("has-next")
if in_progress > 0:
classes.append("has-in-progress")
self.set_style_classes(classes)
tooltip_lines = []
for state in _state_order(list(snapshot.counts.keys())):
n = snapshot.counts.get(state, 0)
if n:
tooltip_lines.append(f"{state}: {n}")
self.set_tooltip_text("\n".join(tooltip_lines) if tooltip_lines else "No open org items")
+480 -149
View File
@@ -1,20 +1,44 @@
import contextlib
import os
import urllib.parse
import urllib.request
import tempfile
from gi.repository import Gtk, GLib, Gio, Gdk
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 fabric.widgets.eventbox import EventBox
from ..widgets.circle_image import CircleImage
import bar.modules.icons as icons
from bar.services.mpris import MprisPlayerManager, MprisPlayer
from sims.modules.media_card import MediaCard
from sims.utils.artwork import file_key, resolve_artwork
import sims.modules.icons as icons
from sims.services.mpris import MprisPlayer, get_mpris_player_manager
from fabric import Fabricator
# from bar.modules.cavalcade import SpectrumRender
# 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):
@@ -413,7 +437,7 @@ class Player(Box):
)
self.switcher.set_stack(self.player_stack)
self.switcher.set_halign(Gtk.Align.CENTER)
self.mpris_manager = MprisPlayerManager()
self.mpris_manager = get_mpris_player_manager()
players = self.mpris_manager.players
if players:
for p in players:
@@ -503,30 +527,75 @@ class Player(Box):
return False
class PlayerSmall(CenterBox):
def __init__(self):
class PlayerSmall(EventBox):
"""Compact bar pill: spinning cover, title/artist and a play button.
Hovering the pill drops down a `MediaCard` with the full controls; the
card stays open while the pointer is on either the pill or the card.
"""
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
# Delay before the card opens (so sweeping across the bar doesn't flash
# it) and before it closes (so the pointer can cross the gap between the
# pill and the card).
CARD_SHOW_DELAY_MS = 250
CARD_HIDE_DELAY_MS = 300
def __init__(self, monitor: int | None = None):
super().__init__(
name="player-small", orientation="h", h_align="fill", v_align="center"
events=["enter-notify", "leave-notify"], v_align="center"
)
self._show_artist = False # toggle flag
self._display_options = ["cavalcade", "title", "artist"]
self.pill = Box(name="player-small", orientation="h", v_align="center")
self.add(self.pill)
self._monitor = monitor
self._card: MediaCard | None = None
self._hover_pill = False
self._hover_card = False
self._card_show_id = None
self._card_hide_id = None
self._cover_url = None
self._cover_path = None
self._cover_key = None
self._display_options = ["title", "artist"]
self._display_index = 0
self._current_display = "cavalcade"
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=Label(name="compact-mpris-icon-label", markup=icons.disc),
child=self.cover_stack,
)
# Remove scroll events; instead, add button press events.
self.mpris_icon.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.mpris_icon.connect("button-press-event", self._on_icon_button_press)
# Prevent the child from propagating events.
child = self.mpris_icon.get_child()
child.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
child.connect("button-press-event", lambda widget, event: True)
# Add hover effect
add_hover_cursor(self.mpris_icon)
self.mpris_label = Label(
@@ -536,36 +605,36 @@ class PlayerSmall(CenterBox):
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=Label(name="compact-mpris-button-label", markup=icons.play),
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 effect
add_hover_cursor(self.mpris_button)
# self.cavalcade = SpectrumRender()
# self.cavalcade_box = self.cavalcade.get_spectrum_box()
self.center_stack = Stack(
name="compact-mpris",
transition_type="crossfade",
transition_duration=100,
v_align="center",
v_expand=False,
children=[
# self.cavalcade_box,
self.mpris_label,
],
children=[self.mpris_label],
)
# self.center_stack.set_visible_child(self.cavalcade_box) # default to cavalcade
# Create additional compact view.
self.mpris_small = CenterBox(
name="compact-mpris",
orientation="h",
@@ -574,165 +643,427 @@ class PlayerSmall(CenterBox):
v_align="center",
v_expand=False,
start_children=self.mpris_icon,
center_children=self.center_stack, # Changed to center_stack to handle stack switching
center_children=self.center_stack,
end_children=self.mpris_button,
)
self.add(self.mpris_small)
self.pill.add(self.mpris_small)
self.mpris_manager = MprisPlayerManager()
self.connect("enter-notify-event", self._on_pill_enter)
self.connect("leave-notify-event", self._on_pill_leave)
self.mpris_manager = get_mpris_player_manager()
self.mpris_player = None
# Almacenar el índice del reproductor actual
self.current_index = 0
self._players = {}
self._player_handlers = {}
self._last_status = {}
players = self.mpris_manager.players
if players:
mp = MprisPlayer(players[self.current_index])
self.mpris_player = mp
self._apply_mpris_properties()
self.mpris_player.connect("changed", self._on_mpris_changed)
else:
self._apply_mpris_properties()
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)
self.mpris_button.connect("clicked", self._on_play_pause_clicked)
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):
loaded = False
key = file_key(image_path)
if key is not None:
if key == self._cover_key:
loaded = True # already showing it; skip re-decoding
else:
try:
self.cover.set_image_from_file(image_path)
loaded = True
except Exception:
pass
self._cover_path = image_path if loaded else None
self._cover_key = key if loaded else None
self.cover_stack.set_visible_child(self.cover if loaded else self.fallback_icon)
self._update_spin()
if self._card is not None:
self._card.set_cover(self._cover_path)
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 _update_cover(self, mp):
try:
url = mp.arturl if mp else None
except Exception:
url = None
self._cover_url = url
def done(path):
# The track may have changed while a download was in flight.
if self._cover_url == url:
self._set_cover_from_path(path)
resolve_artwork(url, done)
def _apply_mpris_properties(self):
if not self.mpris_player:
self.mpris_label.set_text("Nothing Playing")
self.mpris_button.get_child().set_markup(icons.stop)
self.mpris_icon.get_child().set_markup(icons.disc)
if self._current_display != "cavalcade":
self.center_stack.set_visible_child(
self.mpris_label
) # if was title or artist, keep showing label
# else:
# self.center_stack.set_visible_child(
# self.cavalcade_box
# ) # default to cavalcade if no 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._cover_url = None
self._cover_path = None
self._cover_key = None
self.center_stack.set_visible_child(self.mpris_label)
self._update_spin()
self._sync_card()
return
mp = self.mpris_player
# Choose icon based on player name.
player_name = (
mp.player_name.lower()
if hasattr(mp, "player_name") and mp.player_name
else ""
)
icon_markup = get_player_icon_markup_by_name(player_name)
self.mpris_icon.get_child().set_markup(icon_markup)
self._update_cover(mp)
self.update_play_pause_icon()
if self._current_display == "title":
text = mp.title if mp.title and mp.title.strip() else "Nothing Playing"
self.mpris_label.set_text(text)
self.center_stack.set_visible_child(self.mpris_label)
elif self._current_display == "artist":
text = mp.artist if mp.artist else "Nothing Playing"
self.mpris_label.set_text(text)
self.center_stack.set_visible_child(self.mpris_label)
# else: # default cavalcade
# self.center_stack.set_visible_child(self.cavalcade_box)
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)
self._sync_card()
# ------------------------------------------------------------------
# hover card
# ------------------------------------------------------------------
def _ensure_card(self) -> MediaCard:
if self._card is None:
card = MediaCard(monitor=self._monitor, on_select_player=self._select_player)
card.connect("enter-notify-event", self._on_card_enter)
card.connect("leave-notify-event", self._on_card_leave)
card.set_players(list(self._players.values()))
card.set_active(self.mpris_player)
card.set_cover(self._cover_path)
self.connect("destroy", lambda *_: card.destroy())
self._card = card
return self._card
def _sync_card(self):
card = self._card
if card is None:
return
if card.player is not self.mpris_player:
card.set_active(self.mpris_player)
card.set_cover(self._cover_path)
else:
card.refresh()
if self.mpris_player is None:
card.popdown()
def _select_player(self, mp):
if mp in self._players.values() and mp is not self.mpris_player:
self.mpris_player = mp
self._apply_mpris_properties()
@staticmethod
def _is_grab_crossing(event) -> bool:
# GTK synthesizes crossing events when a widget grabs the pointer
# (e.g. while dragging the card's seek bar); those aren't the pointer
# actually leaving.
return event.mode in (Gdk.CrossingMode.GRAB, Gdk.CrossingMode.GTK_GRAB)
def _on_pill_enter(self, _widget, _event):
self._hover_pill = True
self._cancel_card_hide()
card_open = self._card is not None and self._card.get_visible()
if not card_open and self._card_show_id is None:
self._card_show_id = GLib.timeout_add(
self.CARD_SHOW_DELAY_MS, self._show_card
)
return False
def _on_pill_leave(self, _widget, event):
if event.detail == Gdk.NotifyType.INFERIOR or self._is_grab_crossing(event):
return False
self._hover_pill = False
if self._card_show_id is not None:
GLib.source_remove(self._card_show_id)
self._card_show_id = None
self._schedule_card_hide()
return False
def _on_card_enter(self, _widget, _event):
self._hover_card = True
self._cancel_card_hide()
return False
def _on_card_leave(self, _widget, event):
if event.detail == Gdk.NotifyType.INFERIOR or self._is_grab_crossing(event):
return False
self._hover_card = False
self._schedule_card_hide()
return False
def _show_card(self):
self._card_show_id = None
if not self._hover_pill or not self._players or self.mpris_player is None:
return False
card = self._ensure_card()
res = self.translate_coordinates(self.get_toplevel(), 0, 0)
# PyGObject returns (x, y), or (ok, x, y) depending on version.
x = 0
if res:
x = res[1] if len(res) == 3 else res[0]
card.popup(int(x))
return False
def _schedule_card_hide(self):
if self._card_hide_id is None:
self._card_hide_id = GLib.timeout_add(
self.CARD_HIDE_DELAY_MS, self._maybe_hide_card
)
def _cancel_card_hide(self):
if self._card_hide_id is not None:
GLib.source_remove(self._card_hide_id)
self._card_hide_id = None
def _maybe_hide_card(self):
self._card_hide_id = None
if self._hover_pill or self._hover_card or self._card is None:
return False
if self._card.seeking:
# Pointer slipped off while scrubbing; close once released.
self._schedule_card_hide()
return False
self._card.popdown()
return False
def _on_icon_button_press(self, widget, event):
from gi.repository import Gdk
if event.type != Gdk.EventType.BUTTON_PRESS:
return True
if event.type == Gdk.EventType.BUTTON_PRESS:
players = self.mpris_manager.players
if not players:
if event.button == 2:
if not self.mpris_player:
return True
if event.button == 2: # Middle-click: cycle display
self._display_index = (self._display_index + 1) % len(
self._display_options
)
self._current_display = self._display_options[self._display_index]
self._apply_mpris_properties() # Re-apply to update label/cavalcade
return True
# Cambiar de reproductor según el botón presionado.
if event.button == 1: # Left-click: next player
self.current_index = (self.current_index + 1) % len(players)
elif event.button == 3: # Right-click: previous player
self.current_index = (self.current_index - 1) % len(players)
if self.current_index < 0:
self.current_index = len(players) - 1
mp_new = MprisPlayer(players[self.current_index])
self.mpris_player = mp_new
# Conectar el evento "changed" para que se actualice
self.mpris_player.connect("changed", self._on_mpris_changed)
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 # Se consume el evento
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:
if event.button == 1: # Click izquierdo -> track anterior
if self.mpris_player:
self.mpris_player.previous()
self.mpris_button.get_child().set_markup(icons.prev)
GLib.timeout_add(500, self._restore_play_pause_icon)
elif event.button == 3: # Click derecho -> siguiente track
if self.mpris_player:
self.mpris_player.next()
self.mpris_button.get_child().set_markup(icons.next)
GLib.timeout_add(500, self._restore_play_pause_icon)
elif event.button == 2: # Click medio -> play/pausa
if self.mpris_player:
self.mpris_player.play_pause()
self.update_play_pause_icon()
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 _on_icon_clicked(
self, widget
): # No longer used, logic moved to _on_icon_button_press
pass
def update_play_pause_icon(self):
if self.mpris_player and self.mpris_player.playback_status == "playing":
self.mpris_button.get_child().set_markup(icons.pause)
else:
self.mpris_button.get_child().set_markup(icons.play)
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 _on_play_pause_clicked(self, button):
if self.mpris_player:
self.mpris_player.play_pause()
self.update_play_pause_icon()
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
if self._card is not None:
self._card.set_players(list(self._players.values()))
def _on_mpris_changed(self, *args):
# Update properties when the player's state changes.
self._apply_mpris_properties()
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)
if self._card is not None:
self._card.set_players(list(self._players.values()))
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):
# When a new player appears, use it if no player is active.
self._track_player(player)
if not self.mpris_player:
mp = MprisPlayer(player)
self.mpris_player = mp
name = player.get_property("player-name")
self.mpris_player = self._players.get(name)
self._apply_mpris_properties()
self.mpris_player.connect("changed", self._on_mpris_changed)
def on_player_vanished(self, manager, player_name):
players = self.mpris_manager.players
if (
players
and self.mpris_player
and self.mpris_player.player_name == player_name
):
if players: # Check if players is not empty after vanishing
self.current_index = self.current_index % len(players)
new_player = MprisPlayer(players[self.current_index])
self.mpris_player = new_player
self.mpris_player.connect("changed", self._on_mpris_changed)
else:
self.mpris_player = None # No players left
elif not players:
self.mpris_player = None
self._apply_mpris_properties()
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()
+368
View File
@@ -0,0 +1,368 @@
from sims.config import STYLIX
from loguru import logger
# 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
}
# styles/colors.css palette name -> base16 slot. fabric compiles `:vars` to
# GTK `@define-color`, and named colors resolve across the whole style
# cascade, so redefining them in the stylix provider (added after main.css)
# retargets every `var(--x)` rule in styles/*.css as well -- not just the
# selectors overridden below.
PALETTE = {
"background": "base00",
"mid-bg": "base01",
"light-bg": "base02",
"dark-grey": "base03",
"light-grey": "base04",
"dark-fg": "base04",
"mid-fg": "base05",
"foreground": "base05",
"red": "base08",
"orange": "base09",
"gold": "base0A",
"lime": "base0B",
"turquoise": "base0C",
"blue": "base0D",
"violet": "base0E",
"pink": "base0F",
}
def resolve_colors(mode: str | None = None) -> dict[str, str]:
"""base16 colors for `mode` ("light"/"dark"): the matching
`stylix.variants.<mode>.colors`, then the base `stylix.colors`, then
DEFAULT_COLORS for any slot still missing."""
colors = dict(DEFAULT_COLORS)
if STYLIX.get("enable", False):
colors.update(STYLIX.get("colors") or {})
if mode is not None:
variant = (STYLIX.get("variants") or {}).get(mode) or {}
colors.update(variant.get("colors") or {})
return colors
def generate_stylix_css(mode: str | None = None) -> str | None:
"""Generate CSS using Stylix colors (for `mode`, if variants are set)"""
if not STYLIX.get("enable", False):
return None
colors = resolve_colors(mode)
fonts = STYLIX.get("fonts", {})
# 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)
logger.info(
f"[Stylix] Generating CSS (mode={mode}) - Base: {font_size}px, "
f"Small: {small_font}px, Large: {large_font}px"
)
palette = "\n".join(
f"@define-color {name} #{colors[slot]};" for name, slot in PALETTE.items()
)
# Generate GTK CSS with Stylix colors
css_content = f"""/* Stylix-generated theme */
{palette}
/* Apply Stylix font. This provider sits in front of main.css and GTK lets
the first provider that sets a property win regardless of selector
specificity, so a blanket `* {{ font-size }}` here would flatten every
size in the bar's own CSS. The bar (window#sims) therefore only gets the
size on its toplevel and inherits it; other windows keep the blanket
rule they were designed against. */
* {{
font-family: "{font_family}", sans-serif;
}}
window,
tooltip {{
font-size: {font_size}px;
}}
window:not(#sims) * {{
font-size: {font_size}px;
}}
/* Bar widgets are styled purely in the static styles/ css through the palette
above (see styles/colors.css for the semantic tokens). */
/* 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;
}}
/* 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;
}}
/* Theme (darkman light/dark) toggle */
#theme-toggle-button {{
background-color: transparent;
color: #{colors["base05"]};
border: none;
padding: 4px;
margin: 0px;
border-radius: 8px;
}}
#theme-toggle-button:hover {{
background-color: #{colors["base02"]};
}}
#theme-toggle-button.active {{
background-color: #{colors["base0D"]};
color: #{colors["base00"]};
}}
#theme-toggle-button:disabled {{
opacity: 0.4;
}}
#theme-toggle-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;
}}
"""
return css_content
+39
View File
@@ -0,0 +1,39 @@
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from sims.services.darkman import DarkmanService
class ThemeToggleButton(Button):
"""Flips darkman between light and dark mode.
Shows the active mode (moon + `active` class in dark mode) and is
insensitive while darkman is unreachable.
"""
def __init__(self, service: DarkmanService, **kwargs):
self._service = service
self.icon = Image(icon_size=16, name="theme-toggle-icon")
super().__init__(
name="theme-toggle-button",
child=self.icon,
on_clicked=lambda *_: self._service.toggle(),
**kwargs,
)
self._service.connect("changed", lambda _svc, mode: self._update(mode))
self._update(self._service.mode)
def _update(self, mode: str | None):
dark = mode == "dark"
self.icon.set_from_icon_name(
"weather-clear-night-symbolic" if dark else "weather-clear-symbolic", 16
)
if dark:
self.add_style_class("active")
else:
self.remove_style_class("active")
self.set_sensitive(mode is not None)
if mode is None:
self.set_tooltip_text("darkman is not running")
else:
self.set_tooltip_text(f"Switch to {'light' if dark else 'dark'} mode")
+85
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}")
+9
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...",
)
+19
View File
@@ -0,0 +1,19 @@
"""Shared audio service.
fabric's `Audio` wraps a libcvc (`Cvc.MixerControl`) client: constructing one
opens a PulseAudio/PipeWire connection, subscribes to every stream event and
enumerates sinks/sources. Widgets were creating one per output, so keep a
single process-wide instance instead.
"""
from fabric.audio.service import Audio
_service: "Audio | None" = None
def get_audio_service() -> "Audio":
"""Return the process-wide Audio service, creating it on first use."""
global _service
if _service is None:
_service = Audio()
return _service
+87
View File
@@ -0,0 +1,87 @@
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
_service: "BatteryService | None" = None
def get_battery_service(update_interval: int = 10000) -> "BatteryService":
"""Return the process-wide battery service, creating it on first use.
Only the first caller's `update_interval` wins, so the bar widget (10s) and
the buddy (15s) share one psutil poll instead of running their own.
"""
global _service
if _service is None:
_service = BatteryService(update_interval=update_interval)
return _service
+169
View File
@@ -0,0 +1,169 @@
"""Mood arbitration for the bar buddy.
Fuses CPU load, battery state, time of day, mail counts and click events into a
single `mood-changed` signal. Highest-priority active mood wins.
"""
import time
from datetime import datetime
from fabric.core.service import Service, Signal
from fabric.utils import invoke_repeater
from sims.services.battery import get_battery_service
from sims.services.mpris import MprisPlayer, get_mpris_player_manager
from sims.services.system_stats import get_system_stats_service
from sims.config import BATTERY, NOTMUCH
# Highest priority first. The first mood whose state is True wins.
MOOD_PRIORITY = ["petted", "excited", "busy", "bopping", "sleepy", "idle"]
PETTED_DURATION_S = 1.5
EXCITED_DURATION_S = 5.0
BUSY_CPU_THRESHOLD = 0.80
SLEEPY_BATTERY_THRESHOLD = 20 # percent
SLEEPY_HOUR_START = 23 # 23:00 inclusive
SLEEPY_HOUR_END = 7 # exclusive
TICK_INTERVAL_MS = 1000
class BuddyService(Service):
@Signal
def mood_changed(self, mood: str) -> None:
"""Emitted when the arbitrated mood changes."""
def __init__(self, notmuch_service=None, **kwargs):
super().__init__(**kwargs)
self._mood = "idle"
self._cpu = 0.0
self._battery_pct = 100
self._battery_charging = True
self._petted_until = 0.0
self._excited_until = 0.0
self._last_unread = None
self._stats = get_system_stats_service()
self._stats.connect("stats-changed", self._on_stats)
self._battery = None
if BATTERY.get("enable", False):
self._battery = get_battery_service()
self._battery.connect("battery-changed", self._on_battery)
self._notmuch = notmuch_service
if self._notmuch is not None:
self._notmuch.connect("counts-changed", self._on_notmuch)
self._mpris_manager = get_mpris_player_manager()
self._mpris_players: dict[str, MprisPlayer] = {}
for p in self._mpris_manager.players or []:
self._attach_player(p)
self._mpris_manager.connect("player-appeared", self._on_player_appeared)
self._mpris_manager.connect("player-vanished", self._on_player_vanished)
invoke_repeater(TICK_INTERVAL_MS, self._tick)
self._recompute()
# External triggers ---------------------------------------------------
@property
def mood(self) -> str:
"""Currently arbitrated mood."""
return self._mood
def pet(self):
"""Called when the buddy is clicked."""
self._petted_until = time.monotonic() + PETTED_DURATION_S
self._recompute()
# Service callbacks ---------------------------------------------------
def _on_stats(self, _service, cpu_fraction, _mem_fraction):
self._cpu = cpu_fraction
self._recompute()
def _on_battery(self, _service, percent, charging):
self._battery_pct = percent
self._battery_charging = charging
self._recompute()
def _on_notmuch(self, _service, unread, _debt):
if self._last_unread is not None and unread > self._last_unread:
self._excited_until = time.monotonic() + EXCITED_DURATION_S
self._last_unread = unread
self._recompute()
def _attach_player(self, player):
mp = MprisPlayer(player)
self._mpris_players[mp.player_name] = mp
mp.connect("changed", self._on_player_changed)
def _on_player_appeared(self, _manager, player):
self._attach_player(player)
self._recompute()
def _on_player_vanished(self, _manager, player_name: str):
self._mpris_players.pop(player_name, None)
self._recompute()
def _on_player_changed(self, _player):
self._recompute()
def _is_anything_playing(self) -> bool:
for mp in self._mpris_players.values():
try:
if mp.playback_status == "playing":
return True
except Exception:
continue
return False
def _tick(self):
# Re-arbitrate every second so transient moods (petted/excited) and
# the clock-driven sleepy window expire correctly.
self._recompute()
return True
# Arbitration ---------------------------------------------------------
def _states(self) -> dict[str, bool]:
now = time.monotonic()
hour = datetime.now().hour
is_night = hour >= SLEEPY_HOUR_START or hour < SLEEPY_HOUR_END
battery_low = (self._battery is not None
and self._battery_pct < SLEEPY_BATTERY_THRESHOLD
and not self._battery_charging)
return {
"petted": now < self._petted_until,
"excited": now < self._excited_until,
"busy": self._cpu > BUSY_CPU_THRESHOLD,
"bopping": self._is_anything_playing(),
"sleepy": battery_low or is_night,
"idle": True,
}
def _recompute(self):
states = self._states()
for mood in MOOD_PRIORITY:
if states.get(mood, False):
if mood != self._mood:
self._mood = mood
self.mood_changed(mood)
return
_service: "BuddyService | None" = None
def get_buddy_service(notmuch_service=None) -> "BuddyService":
"""Return the process-wide buddy service, creating it on first use.
`notmuch_service` only applies to the first caller (the bar that owns the
notmuch widget). One arbitrated mood and one re-arbitration ticker are
shared by every output instead of one per bar.
"""
global _service
if _service is None:
_service = BuddyService(notmuch_service=notmuch_service)
return _service
+68
View File
@@ -0,0 +1,68 @@
"""Screen-capture IPC subscriber.
Listens to fenster's `:capture` event, which is backed by riverfx's
`capture_sessions` events (river-window-management-v1 v5+). Fenster sends the
full aggregate on every change and replays it on subscribe:
{
"change": "active" | "inactive",
"outputs": [{"name": "DP-1", "sessions": 1}],
"windows": [{"id": 42, "app_id": "firefox", "title": "...", "sessions": 1}]
}
Create the singleton before the GLib main loop starts so the replayed initial
state is not missed.
"""
from fabric.core.service import Service, Signal
from loguru import logger
from sims.services.fenster import get_i3_connection
_service: "CaptureService | None" = None
class CaptureService(Service):
@Signal
def capture_changed(self) -> None:
"""Emitted when the set of captured outputs/windows changes."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._outputs: list[dict] = []
self._windows: list[dict] = []
i3 = get_i3_connection()
i3.connect("event::capture::active", self._on_event)
i3.connect("event::capture::inactive", self._on_event)
@property
def active(self) -> bool:
return bool(self._outputs or self._windows)
@property
def outputs(self) -> list[dict]:
"""Captured outputs: [{"name": str, "sessions": int}]."""
return list(self._outputs)
@property
def windows(self) -> list[dict]:
"""Captured windows: [{"id", "app_id", "title", "sessions"}]."""
return list(self._windows)
def _on_event(self, _i3, event):
outputs = event.data.get("outputs")
windows = event.data.get("windows")
if not isinstance(outputs, list) or not isinstance(windows, list):
logger.warning(f"[Capture] unexpected event payload: {event.data!r}")
return
if outputs == self._outputs and windows == self._windows:
return
self._outputs = outputs
self._windows = windows
self.capture_changed()
def get_capture_service() -> CaptureService:
global _service
if _service is None:
_service = CaptureService()
return _service
+171
View File
@@ -0,0 +1,171 @@
"""darkman control service.
Talks to darkman's control socket (`$XDG_RUNTIME_DIR/darkman/control.sock`,
a newline-delimited text protocol: `get`, `set light|dark`, `toggle`,
`watch`) so sims can show and switch the current light/dark mode.
A long-lived `watch` connection tracks the mode; darkman prints the current
mode immediately and then every change. Switching opens a short-lived
connection and sends `set <mode>`. If darkman is not running (yet), or
restarts, the watch connection is retried in the background.
This only *controls* darkman. Re-theming sims itself still happens through
the portal color-scheme (see `sims.services.theme`), which darkman updates
as part of every switch.
"""
import os
from fabric.core.service import Service, Signal
from gi.repository import Gio, GLib
from loguru import logger
from sims.config import DARKMAN
MODES = ("light", "dark")
_RETRY_MIN_S = 2
_RETRY_MAX_S = 30
_service: "DarkmanService | None" = None
def _default_socket_path() -> str:
runtime_dir = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
return os.path.join(runtime_dir, "darkman", "control.sock")
class DarkmanService(Service):
@Signal
def changed(self, mode: object) -> None:
"""Emitted with the new mode ("light", "dark"), or None while darkman
is unreachable."""
def __init__(self, socket_path: str | None = None, **kwargs):
super().__init__(**kwargs)
self._socket_path = os.path.expandvars(
os.path.expanduser(socket_path or _default_socket_path())
)
self._mode: str | None = None
self._client = Gio.SocketClient.new()
self._watch_conn: Gio.SocketConnection | None = None
self._watch_stream: Gio.DataInputStream | None = None
self._retry_s = _RETRY_MIN_S
self._retry_source: int | None = None
self._connect_watch()
@property
def mode(self) -> str | None:
return self._mode
@property
def available(self) -> bool:
return self._mode is not None
# -- control ---------------------------------------------------------
def set_mode(self, mode: str) -> None:
if mode not in MODES:
raise ValueError(f"invalid darkman mode: {mode!r}")
self._send(f"set {mode}")
def toggle(self) -> None:
if self._mode is None:
logger.warning("[Darkman] not connected, cannot toggle mode")
return
self.set_mode("light" if self._mode == "dark" else "dark")
def _send(self, command: str) -> None:
self._client.connect_async(
Gio.UnixSocketAddress.new(self._socket_path),
None,
self._on_command_connected,
command,
)
def _on_command_connected(self, client: Gio.SocketClient, result, command: str):
try:
conn = client.connect_finish(result)
except GLib.Error as e:
logger.warning(f"[Darkman] could not send {command!r}: {e.message}")
return
try:
# `set` gets no reply; a few bytes into a local socket never block.
conn.get_output_stream().write_all(f"{command}\n".encode(), None)
except GLib.Error as e:
logger.warning(f"[Darkman] could not send {command!r}: {e.message}")
finally:
conn.close(None)
# -- watch -----------------------------------------------------------
def _connect_watch(self) -> bool:
self._retry_source = None
self._client.connect_async(
Gio.UnixSocketAddress.new(self._socket_path),
None,
self._on_watch_connected,
)
return GLib.SOURCE_REMOVE
def _on_watch_connected(self, client: Gio.SocketClient, result):
try:
conn = client.connect_finish(result)
conn.get_output_stream().write_all(b"watch\n", None)
except GLib.Error as e:
logger.debug(f"[Darkman] socket {self._socket_path} unavailable: {e.message}")
self._schedule_retry()
return
logger.info(f"[Darkman] watching {self._socket_path}")
self._retry_s = _RETRY_MIN_S
self._watch_conn = conn
self._watch_stream = Gio.DataInputStream.new(conn.get_input_stream())
self._read_next()
def _read_next(self):
assert self._watch_stream is not None
self._watch_stream.read_line_async(
GLib.PRIORITY_DEFAULT, None, self._on_line
)
def _on_line(self, stream: Gio.DataInputStream, result):
try:
line, _length = stream.read_line_finish_utf8(result)
except GLib.Error as e:
logger.warning(f"[Darkman] watch connection failed: {e.message}")
line = None
if line is None:
# EOF: darkman stopped or restarted.
self._drop_watch()
self._schedule_retry()
return
mode = line.strip()
self._set_mode(mode if mode in MODES else None)
self._read_next()
def _drop_watch(self):
if self._watch_conn is not None:
self._watch_conn.close(None)
self._watch_conn = None
self._watch_stream = None
self._set_mode(None)
def _schedule_retry(self):
if self._retry_source is not None:
return
self._retry_source = GLib.timeout_add_seconds(self._retry_s, self._connect_watch)
self._retry_s = min(self._retry_s * 2, _RETRY_MAX_S)
def _set_mode(self, mode: str | None):
if mode == self._mode:
return
logger.info(f"[Darkman] mode={mode}")
self._mode = mode
self.changed(mode)
def get_darkman_service() -> DarkmanService:
global _service
if _service is None:
_service = DarkmanService(socket_path=DARKMAN.get("socket_path"))
return _service
+55
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
+246
View File
@@ -0,0 +1,246 @@
"""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
CAPTURE_EVENT = 0x80000065
@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()),
)
@@ -116,6 +116,24 @@ class MprisPlayer(Service):
GLib.idle_add(lambda: (setattr(self, "shuffle", not self.shuffle), False))
# else do nothing
def set_shuffle(self, do_shuffle: bool) -> None:
"""Like assigning `shuffle`, but lets DBus errors propagate (GObject
property setters swallow them), so callers can tell when a player
doesn't support shuffling."""
self._player.set_shuffle(do_shuffle)
self.notifier("shuffle")
def set_loop(self, status: str) -> None:
"""Like assigning `loop_status` ("none" / "track" / "playlist"), but
lets DBus errors propagate."""
loop_status = {
"none": Playerctl.LoopStatus.NONE,
"track": Playerctl.LoopStatus.TRACK,
"playlist": Playerctl.LoopStatus.PLAYLIST,
}[status]
self._player.set_loop_status(loop_status)
self.notifier("loop-status")
def play_pause(self):
if self.can_pause:
GLib.idle_add(lambda: (self._player.play_pause(), False))
@@ -265,7 +283,11 @@ class MprisPlayerManager(Service):
def on_name_appeard(self, manager, player_name: Playerctl.PlayerName):
logger.info(f"[MprisPlayer] {player_name.name} appeared")
new_player = Playerctl.Player.new_from_name(player_name)
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
@@ -275,8 +297,27 @@ class MprisPlayerManager(Service):
def add_players(self):
for player in self._manager.get_property("player-names"): # type: ignore
self._manager.manage_player(Playerctl.Player.new_from_name(player)) # 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
_service: "MprisPlayerManager | None" = None
def get_mpris_player_manager() -> "MprisPlayerManager":
"""Return the process-wide MPRIS manager, creating it on first use.
`Playerctl.PlayerManager.new()` plus one `Playerctl.Player` per MPRIS name
is the expensive part; every widget that wraps players should share this
manager and build its own `MprisPlayer` wrappers on top of it.
"""
global _service
if _service is None:
_service = MprisPlayerManager()
return _service
+106
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()
+172
View File
@@ -0,0 +1,172 @@
"""Org-mode agenda service.
Parses configured org files via `orgparse`, exposes a flat list of TODO-state
items grouped by state. Polls on an interval and re-reads files whose mtime
changed since the last sweep.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from glob import glob
from pathlib import Path
from typing import Iterable
from fabric.utils import invoke_repeater
from loguru import logger
try:
import orgparse
ORGPARSE_AVAILABLE = True
except ImportError:
ORGPARSE_AVAILABLE = False
logger.warning("[Org] orgparse not available — org widget disabled at runtime")
from sims.config import ORG
@dataclass
class OrgItem:
state: str
headline: str
file: str
line: int
tags: tuple[str, ...] = ()
scheduled: str | None = None
deadline: str | None = None
priority: str | None = None
@dataclass
class OrgSnapshot:
items: list[OrgItem] = field(default_factory=list)
counts: dict[str, int] = field(default_factory=dict)
def total_counted(self, counted_states: list[str]) -> int:
return sum(self.counts.get(s, 0) for s in counted_states)
class OrgService:
def __init__(self, update_interval: int = 60_000):
self._update_interval = update_interval
self._timer_id = None
self._mtimes: dict[str, float] = {}
self._snapshot = OrgSnapshot()
self._callbacks: list = []
self.update()
self._start_monitoring()
@property
def snapshot(self) -> OrgSnapshot:
return self._snapshot
def connect(self, signal_name: str, callback) -> None:
if signal_name == "items-changed":
self._callbacks.append(callback)
def _emit(self, snapshot: OrgSnapshot) -> None:
for cb in self._callbacks:
cb(self, snapshot)
def _start_monitoring(self):
if self._timer_id is None:
self._timer_id = invoke_repeater(self._update_interval, self._tick)
logger.info(
f"[Org] Started periodic updates every {self._update_interval/1000:.0f}s"
)
def _tick(self):
self.update()
return True
def _expand_paths(self) -> list[Path]:
raw = ORG.get("paths", []) or []
out: list[Path] = []
for entry in raw:
entry = os.path.expanduser(entry)
p = Path(entry)
if any(c in entry for c in "*?["):
for match in sorted(glob(entry, recursive=True)):
mp = Path(match)
if mp.is_file() and mp.suffix == ".org":
out.append(mp)
continue
if p.is_dir():
for match in sorted(p.rglob("*.org")):
out.append(match)
elif p.is_file():
out.append(p)
return out
def update(self):
if not ORG.get("enable", False):
return
if not ORGPARSE_AVAILABLE:
return
files = self._expand_paths()
if not files:
if self._snapshot.items:
self._snapshot = OrgSnapshot()
self._emit(self._snapshot)
return
# mtime-based change detection — skip parse if nothing changed
new_mtimes: dict[str, float] = {}
for f in files:
try:
new_mtimes[str(f)] = f.stat().st_mtime
except OSError:
continue
if new_mtimes == self._mtimes and self._snapshot.items:
return
self._mtimes = new_mtimes
todo_keywords = list(ORG.get("todo_keywords", ["TODO", "NEXT", "IN-PROGRESS"]))
done_keywords = list(ORG.get("done_keywords", ["DONE", "CANCELLED"]))
items: list[OrgItem] = []
for f in files:
try:
items.extend(_parse_file(f, todo_keywords, done_keywords))
except Exception as e:
logger.error(f"[Org] Failed to parse {f}: {e}")
counts: dict[str, int] = {}
for it in items:
counts[it.state] = counts.get(it.state, 0) + 1
self._snapshot = OrgSnapshot(items=items, counts=counts)
logger.info(f"[Org] Parsed {len(items)} items across {len(files)} files: {counts}")
self._emit(self._snapshot)
def _parse_file(
path: Path,
todo_keywords: list[str],
done_keywords: list[str],
) -> Iterable[OrgItem]:
env = orgparse.OrgEnv(
todos=todo_keywords,
dones=done_keywords,
filename=str(path),
)
root = orgparse.load(str(path), env=env)
for node in root[1:]:
state = node.todo
if not state or state in done_keywords:
continue
yield OrgItem(
state=state,
headline=node.heading or "(untitled)",
file=str(path),
line=node.linenumber,
tags=tuple(sorted(node.tags)),
scheduled=str(node.scheduled) if node.scheduled else None,
deadline=str(node.deadline) if node.deadline else None,
priority=node.priority,
)
+230
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)
+49
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
+82
View File
@@ -0,0 +1,82 @@
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
_service: "SystemStatsService | None" = None
def get_system_stats_service(update_interval: int = 3000) -> "SystemStatsService":
"""Return the process-wide stats service, creating it on first use.
`update_interval` only applies to the first caller: one poller feeds every
bar, and psutil's non-blocking `cpu_percent` keeps a process-global baseline
that extra pollers would keep resetting.
"""
global _service
if _service is None:
_service = SystemStatsService(update_interval=update_interval)
return _service
+122
View File
@@ -0,0 +1,122 @@
"""Light/dark theme mode service.
Follows the XDG desktop portal's `org.freedesktop.appearance color-scheme`
setting (served by darkman, GNOME, KDE, ...) and emits `changed` whenever the
effective mode flips. The mode is one of:
- "dark" -- portal reports prefer-dark (1)
- "light" -- portal reports prefer-light (2)
- None -- no preference (0) or no portal available; callers fall back
to the base stylix palette.
The portal is only queried when `stylix.variants` is configured, so setups
without light/dark palettes never touch DBus here.
"""
from fabric.core.service import Service, Signal
from gi.repository import Gio, GLib
from loguru import logger
from sims.config import STYLIX
PORTAL_BUS = "org.freedesktop.portal.Desktop"
PORTAL_PATH = "/org/freedesktop/portal/desktop"
SETTINGS_IFACE = "org.freedesktop.portal.Settings"
APPEARANCE_NS = "org.freedesktop.appearance"
COLOR_SCHEME_KEY = "color-scheme"
_SCHEME_TO_MODE = {1: "dark", 2: "light"}
_service: "ThemeService | None" = None
def _unwrap(value):
"""Strip nested GLib.Variant layers (`Read` wraps the value twice)."""
while isinstance(value, GLib.Variant):
value = value.unpack()
return value
class ThemeService(Service):
@Signal
def changed(self, mode: object) -> None:
"""Emitted with the new mode ("light", "dark" or None)."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._mode: str | None = None
self._bus: Gio.DBusConnection | None = None
if not STYLIX.get("enable", False) or not STYLIX.get("variants"):
return
try:
self._bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
except GLib.Error as e:
logger.warning(f"[Theme] no session bus, not following color-scheme: {e}")
return
self._bus.signal_subscribe(
PORTAL_BUS,
SETTINGS_IFACE,
"SettingChanged",
PORTAL_PATH,
None,
Gio.DBusSignalFlags.NONE,
self._on_setting_changed,
)
# Async so a slow portal activation at session start can't stall the
# bar; the palette is swapped in as soon as the reply lands.
self._read("ReadOne")
@property
def mode(self) -> str | None:
return self._mode
def _read(self, method: str):
assert self._bus is not None
self._bus.call(
PORTAL_BUS,
PORTAL_PATH,
SETTINGS_IFACE,
method,
GLib.Variant("(ss)", (APPEARANCE_NS, COLOR_SCHEME_KEY)),
None,
Gio.DBusCallFlags.NONE,
-1,
None,
self._on_read,
method,
)
def _on_read(self, bus: Gio.DBusConnection, result: Gio.AsyncResult, method: str):
try:
reply = bus.call_finish(result)
except GLib.Error as e:
if method == "ReadOne":
# Settings portal < v2 only has the (deprecated) Read.
self._read("Read")
return
logger.warning(f"[Theme] could not read color-scheme from portal: {e.message}")
return
self._set_scheme(_unwrap(reply.get_child_value(0)))
def _on_setting_changed(self, _bus, _sender, _path, _iface, _signal, params: GLib.Variant):
namespace, key, value = params.unpack()
if namespace == APPEARANCE_NS and key == COLOR_SCHEME_KEY:
self._set_scheme(_unwrap(value))
def _set_scheme(self, scheme):
mode = _SCHEME_TO_MODE.get(scheme) if isinstance(scheme, int) else None
if mode == self._mode:
return
logger.info(f"[Theme] color-scheme={scheme!r} -> mode={mode}")
self._mode = mode
self.changed(mode)
def get_theme_service() -> ThemeService:
global _service
if _service is None:
_service = ThemeService()
return _service
+227
View File
@@ -0,0 +1,227 @@
/* ------------------------------------------------------------------------
Bar shell
One visual language for every module:
- "chips": --surface fill, same height (bar height minus the 6px
vertical padding below), fully rounded, 10px side padding.
- a single accent color for "this is active" (workspace, play state),
tinted chips for "needs attention", solid fill only for alarms.
- text is foreground / --text-muted, icons are 16px.
------------------------------------------------------------------------ */
#sims-inner {
padding: 6px 12px;
background-color: var(--window-bg);
border-bottom: solid 1px var(--hairline);
border-radius: 0;
transition: border-radius 200ms ease;
}
#sims-inner.rounded-bottom {
border-radius: 0 0 28px 28px;
}
/* Shared chip look (workspaces.css applies the same to #workspaces) */
#player-small,
#widgets-container,
#org-widget,
#notmuch-widget,
#date-time {
min-height: 28px;
padding: 0 10px;
border-radius: 14px;
background-color: var(--surface);
transition: background-color 150ms ease;
}
#org-widget:hover,
#notmuch-widget:hover,
#date-time-button:hover #date-time {
background-color: var(--surface-hover);
}
/* ---- left ------------------------------------------------------------- */
#nixos-label {
color: var(--accent);
font-size: 18px;
padding: 0 6px 0 2px;
}
#buddy-container,
#buddy {
padding: 0;
}
#buddy-button {
padding: 0;
margin: 0 2px;
}
/* Compact player chip: circular cover hugging the left edge */
#player-small {
padding: 0 6px 0 3px;
}
#compact-mpris-icon,
#compact-mpris-button {
padding: 0;
margin: 0;
min-height: 0;
min-width: 0;
}
#compact-mpris-label {
color: var(--foreground);
font-weight: 500;
margin: 0 8px;
}
#compact-mpris-fallback {
color: var(--text-muted);
margin: 0 3px;
}
#compact-mpris-button-icon {
color: var(--text-muted);
transition: color 150ms ease;
}
#compact-mpris-button:hover #compact-mpris-button-icon {
color: var(--accent);
}
/* ---- center ----------------------------------------------------------- */
#active-window,
.active-window {
color: var(--text-muted);
font-weight: 500;
}
/* ---- right ------------------------------------------------------------ */
/* System cluster: mic, cpu/ram rings, tray, battery in one chip */
#widgets-container {
padding: 0 8px;
}
#microphone-button {
padding: 0 4px;
border-radius: 10px;
}
#microphone-icon {
color: var(--text-muted);
font-size: 16px;
}
#microphone-button:hover #microphone-icon {
color: var(--foreground);
}
#microphone-icon.muted {
color: var(--red);
}
/* CPU / RAM "activity rings": outer ring = RAM, inner ring = CPU.
CircularProgressBar draws its track with `color` and progress with
`border-color`; the border *width* must stay 0 or it inflates the line. */
#system-stats {
padding: 0 4px;
}
#ram-progress-bar,
#cpu-progress-bar {
background-color: transparent;
color: alpha(var(--foreground), 0.12);
border: solid 0 transparent;
}
#ram-progress-bar {
border-color: var(--accent);
}
#cpu-progress-bar {
border-color: var(--violet);
}
#system-tray {
padding: 0 2px;
}
#system-tray > button {
padding: 0 3px;
border-radius: 8px;
}
#system-tray > button:hover {
background-color: var(--surface-hover);
}
#battery-widget {
padding: 0 2px 0 4px;
}
#bat-icon {
color: var(--text-muted);
}
#bat-label {
color: var(--foreground);
font-feature-settings: "tnum";
}
#bat-icon.battery-low,
#bat-label.battery-low {
color: var(--red);
font-weight: bold;
}
/* Screen-share indicator: a bare red dot, only visible while sharing */
#capture-widget {
padding: 0 6px;
margin: 0;
}
#capture-dot {
color: var(--red);
font-size: 12px;
}
#capture-summary {
color: var(--text-muted);
margin-right: 6px;
}
/* Clock: bold time, muted date */
#date-time-button {
padding: 0;
margin: 0;
}
#date-time {
padding: 0 12px;
}
#clock-time {
font-weight: bold;
font-feature-settings: "tnum";
}
#clock-date {
color: var(--text-muted);
font-feature-settings: "tnum";
}
/* ---- tooltips --------------------------------------------------------- */
tooltip {
background-color: var(--window-bg);
border: solid 1px var(--hairline);
border-radius: 10px;
}
tooltip > * {
padding: 4px 8px;
}
+44
View File
@@ -0,0 +1,44 @@
/* Calendar widget styling */
/* 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;
}
+40
View File
@@ -0,0 +1,40 @@
: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;
/* Semantic tokens. Surfaces/text are derived from --foreground so they
work on both dark and light palettes (stylix redefines the base
colors at runtime and these follow). */
--accent: var(--blue);
--surface: alpha(var(--foreground), 0.06);
--surface-hover: alpha(var(--foreground), 0.11);
--surface-active: alpha(var(--foreground), 0.16);
--hairline: alpha(var(--foreground), 0.08);
--text-muted: alpha(var(--foreground), 0.62);
--text-faint: alpha(var(--foreground), 0.38);
--window-bg: alpha(var(--background), 0.94);
--module-bg: alpha(var(--mid-bg), 0.8);
--border-color: var(--light-bg);
--ws-active: var(--accent);
--ws-visible: alpha(var(--accent), 0.5);
--ws-inactive: alpha(var(--foreground), 0.55);
--ws-empty: alpha(var(--foreground), 0.18);
--ws-hover: alpha(var(--foreground), 0.85);
--ws-urgent: var(--red);
}
+92
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;
}
+31
View File
@@ -0,0 +1,31 @@
@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");
@import url("./org.css");
@import url("./media.css");
/* unset so we can style everything from the ground up. `all: unset`
makes font-size/font-family inherit, so the base font is set once on the
toplevels and any widget rule (e.g. icon sizes) can still override it. */
* {
all: unset;
color: var(--foreground);
}
window,
tooltip {
font-size: 16px;
font-family: "Jost*", sans-serif;
}
button {
background-size: 400% 400%;
}
+143
View File
@@ -0,0 +1,143 @@
/* Media hover card (drops down from the bar's compact player) */
#media-card {
background-color: transparent;
}
#media-card-body {
background-color: var(--window-bg);
border: solid 2px var(--border-color);
border-radius: 20px;
padding: 16px 18px 14px 18px;
}
#media-card-cover-fallback {
color: var(--light-grey);
background-color: var(--module-bg);
border-radius: 100px;
}
#media-card-player {
color: var(--light-grey);
font-size: 11px;
font-weight: bold;
letter-spacing: 1px;
}
#media-card-title {
font-size: 17px;
font-weight: bold;
}
#media-card-artist {
font-size: 14px;
color: var(--mid-fg);
}
#media-card-album {
font-size: 12px;
color: var(--light-grey);
}
/* Seek bar */
#media-card-progress {
min-height: 14px;
}
#media-card-progress trough {
min-height: 4px;
border-radius: 4px;
background-color: var(--light-bg);
}
#media-card-progress highlight {
min-height: 4px;
border-radius: 4px;
background-color: var(--blue);
}
#media-card-progress slider {
min-width: 12px;
min-height: 12px;
margin: -4px;
border-radius: 100px;
background-color: var(--foreground);
}
#media-card-progress:disabled highlight {
background-color: var(--dark-grey);
}
#media-card-time {
font-size: 11px;
color: var(--light-grey);
}
/* Transport controls */
#media-card-btn,
#media-card-toggle {
padding: 6px;
border-radius: 100px;
transition: background-color 150ms ease;
}
#media-card-btn:hover,
#media-card-toggle:hover {
background-color: var(--light-bg);
}
/* `* { color }` in main.css sets every widget's color directly, so icons
have to be targeted themselves rather than inheriting from the button. */
#media-card-toggle image {
color: var(--light-grey);
}
#media-card-toggle.active image {
color: var(--blue);
}
#media-card-btn:disabled,
#media-card-toggle:disabled,
#media-card-play:disabled {
opacity: 0.35;
}
#media-card-play {
padding: 10px;
border-radius: 100px;
background-color: var(--blue);
transition: background-color 150ms ease;
}
#media-card-play image {
color: var(--background);
}
#media-card-play:hover {
background-color: var(--turquoise);
}
/* Player switcher (only shown with more than one player) */
#media-card-player-chip {
padding: 2px 10px;
border-radius: 100px;
background-color: var(--module-bg);
transition: background-color 150ms ease;
}
#media-card-player-chip label {
font-size: 12px;
color: var(--light-grey);
}
#media-card-player-chip:hover {
background-color: var(--light-bg);
}
#media-card-player-chip.active {
background-color: var(--light-bg);
}
#media-card-player-chip.active label {
color: var(--foreground);
}
+30
View File
@@ -0,0 +1,30 @@
/* Context menus (system tray) */
menu {
padding: 4px;
border: solid 1px var(--hairline);
border-radius: 12px;
background-color: var(--window-bg);
}
menu > menuitem {
padding: 6px 10px;
border-radius: 8px;
}
menu > menuitem:hover {
background-color: alpha(var(--accent), 0.18);
}
menu > menuitem:hover > label {
color: var(--accent);
}
menu > menuitem:disabled > label {
color: var(--text-faint);
}
menu > separator {
min-height: 1px;
margin: 4px 6px;
background-color: var(--hairline);
}
+179
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
View File
@@ -0,0 +1,53 @@
/* Notmuch unread badge. Base chip look lives in bar.css.
Calm by default; tinted when there is unread mail, solid red only when
the email debt timer is in alarm. */
#notmuch-icon {
color: var(--text-muted);
}
#unread-count {
color: var(--foreground);
font-weight: bold;
font-feature-settings: "tnum";
min-width: 16px;
}
#notmuch-widget.has-unread {
background-color: alpha(var(--accent), 0.18);
}
#notmuch-widget.has-unread:hover {
background-color: alpha(var(--accent), 0.28);
}
#notmuch-widget.has-unread #notmuch-icon,
#notmuch-widget.has-unread #unread-count {
color: var(--accent);
}
#notmuch-widget.debt-warn {
background-color: alpha(var(--orange), 0.2);
}
#notmuch-widget.debt-warn:hover {
background-color: alpha(var(--orange), 0.3);
}
#notmuch-widget.debt-warn #notmuch-icon,
#notmuch-widget.debt-warn #unread-count {
color: var(--orange);
}
#notmuch-widget.debt-alarm {
background-color: var(--red);
}
#notmuch-widget.debt-alarm:hover {
background-color: shade(var(--red), 1.1);
}
#notmuch-widget.debt-alarm #notmuch-icon,
#notmuch-widget.debt-alarm #unread-count {
color: var(--background);
}
+125
View File
@@ -0,0 +1,125 @@
/* Org-agenda bar widget + dropdown. Base chip look lives in bar.css. */
#org-icon {
color: var(--text-muted);
}
#org-count {
font-weight: bold;
font-feature-settings: "tnum";
min-width: 16px;
}
#org-widget.empty {
opacity: 0.6;
}
#org-widget.has-next {
background-color: alpha(var(--accent), 0.18);
}
#org-widget.has-next:hover {
background-color: alpha(var(--accent), 0.28);
}
#org-widget.has-next #org-icon,
#org-widget.has-next #org-count {
color: var(--accent);
}
#org-widget.has-in-progress {
background-color: alpha(var(--violet), 0.2);
}
#org-widget.has-in-progress:hover {
background-color: alpha(var(--violet), 0.3);
}
#org-widget.has-in-progress #org-icon,
#org-widget.has-in-progress #org-count {
color: var(--violet);
}
/* Dropdown */
#org-dropdown {
background-color: var(--window-bg);
border-radius: 0 0 16px 16px;
border: 1px solid var(--border-color);
border-top: none;
}
#org-dropdown-body {
padding: 14px 16px;
}
#org-dropdown-header {
margin-bottom: 8px;
}
#org-dropdown-title {
font-size: 18px;
font-weight: bold;
}
#org-dropdown-close {
padding: 4px;
border-radius: 8px;
transition: background-color 0.15s ease;
}
#org-dropdown-close:hover {
background-color: var(--light-bg);
}
#org-dropdown-empty {
color: var(--light-grey);
font-style: italic;
padding: 12px 4px;
}
#org-dropdown-section {
padding: 6px 0;
}
#org-dropdown-section-title {
font-size: 13px;
font-weight: bold;
letter-spacing: 0.6px;
}
.org-state-next #org-dropdown-section-title {
color: var(--blue);
}
.org-state-in-progress #org-dropdown-section-title {
color: var(--violet);
}
.org-state-todo #org-dropdown-section-title {
color: var(--orange);
}
.org-state-count {
color: var(--light-grey);
font-size: 12px;
}
#org-item {
padding: 6px 8px;
border-radius: 8px;
transition: background-color 0.15s ease;
}
#org-item:hover {
background-color: var(--light-bg);
}
.org-item-title {
font-size: 14px;
}
.org-item-meta {
color: var(--light-grey);
font-size: 11px;
}
+61
View File
@@ -0,0 +1,61 @@
/* 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);
}
/* Theme (darkman light/dark) toggle -- same look as the vinyl button */
#theme-toggle-button {
background-color: var(--module-bg);
padding: 4px 8px;
border-radius: 12px;
transition: background-color 0.2s ease;
}
#theme-toggle-button:hover {
background-color: var(--light-bg);
}
#theme-toggle-button.active {
background-color: var(--pink);
}
#theme-toggle-button.active:hover {
background-color: var(--turquoise);
}
#theme-toggle-button:disabled {
opacity: 0.4;
}
#theme-toggle-icon {
color: var(--foreground);
}
#theme-toggle-button.active #theme-toggle-icon {
color: var(--background);
}
+54
View File
@@ -0,0 +1,54 @@
/* Workspace rail: small dots, the focused one stretches into an accent pill.
The chip is 28px tall; 10px vertical padding leaves 8px dots. */
#workspaces {
min-height: 8px;
padding: 10px 12px;
border-radius: 14px;
background-color: var(--surface);
}
#workspaces > button {
min-width: 8px;
min-height: 8px;
border-radius: 99px;
background-color: var(--ws-inactive);
transition: min-width 200ms cubic-bezier(0.4, 0, 0.2, 1),
background-color 150ms ease;
}
#workspaces > button > label {
font-size: 0px;
}
#workspaces > button.empty {
background-color: var(--ws-empty);
}
#workspaces > button.visible {
background-color: var(--ws-visible);
}
#workspaces > button:hover {
background-color: var(--ws-hover);
}
#workspaces > button.active {
min-width: 24px;
background-color: var(--ws-active);
}
#workspaces > button.urgent {
background-color: var(--ws-urgent);
animation: urgent-blink 1s infinite;
}
/* Workspace shown on a different monitor than this bar */
#workspaces > button.foreign {
opacity: 0.45;
}
@keyframes urgent-blink {
0% { opacity: 1.0; }
50% { opacity: 0.4; }
100% { opacity: 1.0; }
}
+95
View File
@@ -0,0 +1,95 @@
"""Resolve MPRIS `mpris:artUrl` values to local file paths.
Remote artwork (Spotify, browsers) is downloaded once per URL on a worker
thread and cached for the lifetime of the process, so every widget showing
the cover — the bar pill and the hover card — shares a single download
instead of re-fetching on every MPRIS `changed` emission.
"""
import os
import tempfile
import urllib.parse
import urllib.request
from collections.abc import Callable
from gi.repository import GLib
from loguru import logger
_CACHE_LIMIT = 32
_cache: dict[str, str | None] = {}
# url -> callbacks waiting for an in-flight download of that url
_pending: dict[str, list[Callable[[str | None], None]]] = {}
def _remember(url: str, path: str | None) -> None:
_cache[url] = path
while len(_cache) > _CACHE_LIMIT:
old_url = next(iter(_cache))
old_path = _cache.pop(old_url)
if old_path and old_path.startswith(tempfile.gettempdir()):
try:
os.unlink(old_path)
except OSError:
pass
def _download(url: str) -> None:
path: str | None = None
try:
suffix = os.path.splitext(urllib.parse.urlparse(url).path)[1] or ".png"
with urllib.request.urlopen(url, timeout=10) as response:
data = response.read()
with tempfile.NamedTemporaryFile(
delete=False, prefix="sims-art-", suffix=suffix
) as tmp:
tmp.write(data)
path = tmp.name
except Exception as e:
logger.debug(f"[Artwork] download failed for {url}: {e}")
def finish():
_remember(url, path)
for cb in _pending.pop(url, []):
cb(path)
return False
GLib.idle_add(finish)
def file_key(path: str | None) -> tuple[str, int] | None:
"""`(path, mtime)` for an existing file, else None. Some players rewrite
their artwork in place at a fixed path, so widgets compare this rather
than the bare path to decide whether the cover needs reloading."""
if not path:
return None
try:
return (path, os.stat(path).st_mtime_ns)
except OSError:
return None
def resolve_artwork(
arturl: str | None, callback: Callable[[str | None], None]
) -> None:
"""Call `callback(path_or_None)` on the main loop with a local file for
`arturl`. Local files resolve synchronously; http(s) URLs resolve after a
(cached) background download."""
if not arturl:
callback(None)
return
parsed = urllib.parse.urlparse(arturl)
if parsed.scheme in ("http", "https"):
if arturl in _cache:
callback(_cache[arturl])
return
waiters = _pending.get(arturl)
if waiters is not None:
waiters.append(callback)
return
_pending[arturl] = [callback]
GLib.Thread.new("sims-artwork", _download, arturl)
return
path = urllib.parse.unquote(parsed.path) if parsed.scheme == "file" else arturl
callback(path if path and os.path.isfile(path) else None)
+28
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
View File
+389
View File
@@ -0,0 +1,389 @@
from gi.repository import GdkPixbuf, GLib
from fabric.widgets.box import Box
from fabric.widgets.image import Image
from fabric.widgets.button import Button
from sims.modules.stylix import resolve_colors
from sims.services.theme import get_theme_service
# 16x16 sprite grid, displayed at SCALE x scale (32x32) with crisp pixels.
SPRITE_SIZE = 16
SCALE = 2
# Palette character → semantic role. Resolved to RGBA from stylix at render time.
# . transparent
# B body main
# H body highlight (lighter)
# b body shadow (darker)
# e eye dark
# w eye sparkle / white
# m mouth / closed-eye line
# c blush
# s sweat drop
# z z text
# * sparkle / excitement
# _ semi-transparent ground shadow
# ---------------------------------------------------------------------------
# Sprite construction: layered grid with strict 16x16 validation.
# ---------------------------------------------------------------------------
def _grid(rows: list[str]) -> list[str]:
if len(rows) != SPRITE_SIZE:
raise ValueError(f"sprite must be {SPRITE_SIZE} rows, got {len(rows)}")
for i, r in enumerate(rows):
if len(r) != SPRITE_SIZE:
raise ValueError(f"row {i} has {len(r)} chars (want {SPRITE_SIZE}): {r!r}")
return rows
def _overlay(base: list[str], *layers: list[tuple[int, int, str]]) -> list[str]:
grid = [list(r) for r in base]
for layer in layers:
for (y, x, ch) in layer:
if 0 <= y < SPRITE_SIZE and 0 <= x < SPRITE_SIZE:
grid[y][x] = ch
return ["".join(r) for r in grid]
def _shift(base: list[str], dy: int = 0, dx: int = 0) -> list[str]:
out = []
for y in range(SPRITE_SIZE):
src_y = y - dy
if 0 <= src_y < SPRITE_SIZE:
row = base[src_y]
else:
row = "." * SPRITE_SIZE
if dx > 0:
row = "." * dx + row[:-dx]
elif dx < 0:
row = row[-dx:] + "." * (-dx)
out.append(row)
return out
def _shift_overlay(overlay: list[tuple[int, int, str]], dy: int = 0, dx: int = 0) -> list[tuple[int, int, str]]:
return [(y + dy, x + dx, ch) for (y, x, ch) in overlay]
# Body shapes ---------------------------------------------------------------
BODY_REST = _grid([
"................",
"................",
"................",
".......BB.......",
"......BBBB......",
".....BBBBBB.....",
"....HBBBBBBB....",
"...HBBBBBBBBB...",
"..HBBBBBBBBBBB..",
"..BBBBBBBBBBBB..",
".BBBBBBBBBBBBBb.",
".BBBBBBBBBBBBBb.",
".BBBBBBBBBBBBbb.",
"BBBBBBBBBBBBBbbb",
"BBBBBBBBBBBBBbbb",
"................",
])
BODY_BOB = _shift(BODY_REST, dy=-1) # bobbed up by 1 row
BODY_SQUISH = _grid([
"................",
"................",
"................",
"................",
"......BBBB......",
".....BBBBBB.....",
"....BBBBBBBB....",
"...HBBBBBBBBB...",
"..HBBBBBBBBBBB..",
"..BBBBBBBBBBBB..",
".BBBBBBBBBBBBBb.",
".BBBBBBBBBBBBBb.",
"BBBBBBBBBBBBBbbb",
"BBBBBBBBBBBBBbbb",
"BBBBBBBBBBBBBbbb",
"................",
])
BODY_LEAN_L = _shift(BODY_REST, dx=-1)
BODY_LEAN_R = _shift(BODY_REST, dx=1)
# Face overlays. Eye row defaults to row 8 (rest pose); pass r= for bob/squish.
def eyes_open(r: int = 8) -> list[tuple[int, int, str]]:
return [(r, 5, "e"), (r, 10, "e")]
def eyes_blink(r: int = 8) -> list[tuple[int, int, str]]:
return [(r, 4, "m"), (r, 5, "m"), (r, 9, "m"), (r, 10, "m")]
def eyes_closed_happy(r: int = 8) -> list[tuple[int, int, str]]:
# ^^ shaped happy eyes
return [(r - 1, 4, "m"), (r - 1, 9, "m"),
(r, 5, "m"), (r, 10, "m"),
(r, 3, "m"), (r, 8, "m")]
def eyes_wide(r: int = 8) -> list[tuple[int, int, str]]:
return [(r - 1, 5, "w"), (r - 1, 10, "w"),
(r, 5, "e"), (r, 10, "e")]
def mouth_neutral(r: int = 11) -> list[tuple[int, int, str]]:
return [(r, 6, "m"), (r, 7, "m"), (r, 8, "m"), (r, 9, "m")]
def mouth_smile(r: int = 11) -> list[tuple[int, int, str]]:
return [(r, 6, "m"), (r, 9, "m"),
(r + 1, 7, "m"), (r + 1, 8, "m")]
def mouth_frown(r: int = 11) -> list[tuple[int, int, str]]:
return [(r, 7, "m"), (r, 8, "m"),
(r - 1, 6, "m"), (r - 1, 9, "m")]
def mouth_o(r: int = 11) -> list[tuple[int, int, str]]:
return [(r, 7, "m"), (r, 8, "m"),
(r + 1, 7, "m"), (r + 1, 8, "m")]
def blush(r: int = 9) -> list[tuple[int, int, str]]:
return [(r, 3, "c"), (r, 12, "c")]
# Accent overlays
SWEAT_HIGH = [(2, 13, "s"), (3, 13, "s")]
SWEAT_LOW = [(5, 13, "s"), (6, 13, "s")]
Z_SMALL = [(3, 12, "z"), (3, 13, "z")]
Z_LARGE = [(1, 13, "z"), (1, 14, "z"),
(2, 13, "z"), (2, 14, "z"),
(3, 12, "z"), (3, 13, "z")]
SPARKLE_LEFT = [(3, 2, "*"), (5, 1, "*")]
SPARKLE_RIGHT = [(3, 14, "*"), (5, 14, "*")]
# ---------------------------------------------------------------------------
# Frame compositions per mood
# ---------------------------------------------------------------------------
# Idle: bob + occasional blink. Most frames are eyes-open at rest.
IDLE_REST = _overlay(BODY_REST, eyes_open(8), mouth_neutral(11))
IDLE_BOB = _overlay(BODY_BOB, eyes_open(7), mouth_neutral(10))
IDLE_BLINK = _overlay(BODY_REST, eyes_blink(8), mouth_neutral(11))
# Petted: closed-happy eyes + smile + blush. Squish lowers face by 1 row.
PETTED_FLAT = _overlay(BODY_SQUISH, eyes_closed_happy(9), mouth_smile(12), blush(10))
PETTED_RECOVER = _overlay(BODY_REST, eyes_closed_happy(8), mouth_smile(11), blush(9))
# Excited: wide eyes, open mouth, sparkles, bouncing
EXCITED_LOW = _overlay(BODY_REST, eyes_wide(8), mouth_o(11),
SPARKLE_LEFT)
EXCITED_HIGH = _overlay(BODY_BOB, eyes_wide(7), mouth_o(10),
SPARKLE_LEFT, SPARKLE_RIGHT)
# Bopping: sway in time with music. Shift face with the body.
BOP_LEFT = _overlay(BODY_LEAN_L,
_shift_overlay(eyes_open(8), dx=-1),
_shift_overlay(mouth_smile(11), dx=-1))
BOP_RIGHT = _overlay(BODY_LEAN_R,
_shift_overlay(eyes_open(8), dx=1),
_shift_overlay(mouth_smile(11), dx=1))
# Busy: frown + sweat drops
BUSY_DROP_HIGH = _overlay(BODY_REST, eyes_open(8), mouth_frown(11), SWEAT_HIGH)
BUSY_DROP_LOW = _overlay(BODY_REST, eyes_open(8), mouth_frown(11), SWEAT_LOW)
# Sleepy: closed eyes, z floats, no mouth
SLEEPY_NO_Z = _overlay(BODY_REST, eyes_blink(8))
SLEEPY_Z_SMALL = _overlay(BODY_REST, eyes_blink(8), Z_SMALL)
SLEEPY_Z_LARGE = _overlay(BODY_REST, eyes_blink(8), Z_LARGE)
# (frames, frame_duration_ms, loop)
MOOD_FRAMES: dict[str, tuple[list[list[str]], int, bool]] = {
"idle": (
[IDLE_REST, IDLE_REST, IDLE_BOB, IDLE_REST, IDLE_REST, IDLE_BLINK],
300, True,
),
"petted": (
[PETTED_FLAT, PETTED_FLAT, PETTED_RECOVER, PETTED_RECOVER],
180, False,
),
"excited": (
[EXCITED_LOW, EXCITED_HIGH],
180, True,
),
"bopping": (
[BOP_LEFT, IDLE_REST, BOP_RIGHT, IDLE_REST],
220, True,
),
"busy": (
[BUSY_DROP_HIGH, BUSY_DROP_LOW],
260, True,
),
"sleepy": (
[SLEEPY_NO_Z, SLEEPY_NO_Z, SLEEPY_Z_SMALL, SLEEPY_Z_LARGE],
500, True,
),
}
# ---------------------------------------------------------------------------
# Pixbuf rendering
# ---------------------------------------------------------------------------
def _hex_to_rgba(hex_str: str, alpha: int = 255) -> tuple[int, int, int, int]:
h = hex_str.lstrip("#")
return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16), alpha)
def _mix(c1: tuple[int, int, int], c2: tuple[int, int, int], t: float) -> tuple[int, int, int]:
return (int(c1[0] * (1 - t) + c2[0] * t),
int(c1[1] * (1 - t) + c2[1] * t),
int(c1[2] * (1 - t) + c2[2] * t))
def _resolve_palette(mode: str | None = None) -> dict[str, tuple[int, int, int, int]]:
colors = resolve_colors(mode)
body_rgba = _hex_to_rgba(colors["base0D"])
body_rgb = body_rgba[:3]
light_rgb = _mix(body_rgb, (255, 255, 255), 0.35)
dark_rgb = _mix(body_rgb, (0, 0, 0), 0.30)
return {
".": (0, 0, 0, 0),
"B": body_rgba,
"H": light_rgb + (255,),
"b": dark_rgb + (255,),
"e": _hex_to_rgba(colors["base00"]),
"w": _hex_to_rgba(colors["base05"]),
"m": _hex_to_rgba(colors["base00"]),
"c": _hex_to_rgba(colors["base08"]),
"s": _hex_to_rgba(colors["base0C"]),
"z": _hex_to_rgba(colors["base05"]),
"*": _hex_to_rgba(colors["base0A"]),
"_": _hex_to_rgba(colors["base00"], alpha=80),
}
def _frame_to_pixbuf(rows: list[str], palette: dict[str, tuple[int, int, int, int]]) -> GdkPixbuf.Pixbuf:
out_size = SPRITE_SIZE * SCALE
rowstride = out_size * 4
buf = bytearray(rowstride * out_size)
for y in range(SPRITE_SIZE):
for x in range(SPRITE_SIZE):
ch = rows[y][x]
r, g, b, a = palette.get(ch, (0, 0, 0, 0))
for sy in range(SCALE):
for sx in range(SCALE):
o = (y * SCALE + sy) * rowstride + (x * SCALE + sx) * 4
buf[o] = r
buf[o + 1] = g
buf[o + 2] = b
buf[o + 3] = a
return GdkPixbuf.Pixbuf.new_from_bytes(
GLib.Bytes.new(bytes(buf)),
GdkPixbuf.Colorspace.RGB,
True, 8,
out_size, out_size, rowstride,
)
# ---------------------------------------------------------------------------
# Widget
# ---------------------------------------------------------------------------
class BuddyWidget(Box):
def __init__(self, on_pet=None, **kwargs):
super().__init__(name="buddy", v_align="center", **kwargs)
theme = get_theme_service()
self._palette = _resolve_palette(theme.mode)
theme.connect("changed", self._on_theme_changed)
self._cache: dict[int, GdkPixbuf.Pixbuf] = {}
self._mood = "idle"
self._frame_idx = 0
self._timer_id = None
self._on_pet = on_pet
out = SPRITE_SIZE * SCALE
self._image = Image(name="buddy-image")
self._image.set_size_request(out, out)
self._button = Button(
name="buddy-button",
child=self._image,
on_clicked=self._handle_click,
style="background: transparent; border: none; padding: 0; margin: 0; box-shadow: none;",
)
self.children = [self._button]
self._set_mood("idle")
self.show_all()
def _pixbuf_for(self, frame_rows: list[str]) -> GdkPixbuf.Pixbuf:
key = id(frame_rows)
if key not in self._cache:
self._cache[key] = _frame_to_pixbuf(frame_rows, self._palette)
return self._cache[key]
def _set_mood(self, mood: str):
if mood not in MOOD_FRAMES:
mood = "idle"
self._mood = mood
self._frame_idx = 0
if self._timer_id is not None:
GLib.source_remove(self._timer_id)
self._timer_id = None
_frames, dur, _loop = MOOD_FRAMES[mood]
self._render_current()
self._timer_id = GLib.timeout_add(dur, self._tick)
def _tick(self):
frames, _dur, loop = MOOD_FRAMES[self._mood]
self._frame_idx += 1
if self._frame_idx >= len(frames):
if loop:
self._frame_idx = 0
else:
self._frame_idx = len(frames) - 1
self._timer_id = None
if callable(self._on_pet) and self._mood == "petted":
GLib.timeout_add(120, self._notify_petted_done)
return False
self._render_current()
return True
def _render_current(self):
frames, _dur, _loop = MOOD_FRAMES[self._mood]
rows = frames[self._frame_idx]
self._image.set_from_pixbuf(self._pixbuf_for(rows))
def _notify_petted_done(self):
if callable(self._on_pet):
self._on_pet(done=True)
return False
def _handle_click(self, *_args):
if callable(self._on_pet):
self._on_pet(petted=True)
def _on_theme_changed(self, _theme, mode):
self._palette = _resolve_palette(mode)
self._cache.clear()
self._render_current()
def update_mood(self, mood: str):
if mood == self._mood:
return
self._set_mood(mood)
+240
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)
+136
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,
)
+103
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,
)