Compare commits

92 Commits

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

2
.gitignore vendored Normal file
View File

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

15
Makefile Normal file
View File

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

14
README.md Normal file
View File

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

View File

@@ -1,173 +0,0 @@
/* Fabric bar.css
* https://github.com/Fabric-Development/fabric/blob/rewrite/examples/bar/bar.css
*/
/* we can use webcss variables, fabric compiles that to gtk css.
global variables can be stored in :vars */
:vars {
--background: #150d16;
--foreground: #f5dbc4;
--color0: #150d16;
--color1: #72448D;
--color2: #9C5995;
--color3: #D5719F;
--color4: #9A62F3;
--color5: #E075DF;
--color6: #F98F9F;
--color7: #f5dbc4;
--color8: #ab9989;
--color9: #72448D;
--color10: #9C5995;
--color11: #D5719F;
--color12: #9A62F3;
--color13: #E075DF;
--color14: #F98F9F;
--color15: #f5dbc4;
--window-bg: alpha(var(--background), 0.6);
--module-bg: alpha(var(--background), 0.4);
--border-color: var(--color11);
--ws-active: var(--color9);
--ws-inactive: var(--color3);
--ws-empty: var(--color8);
--ws-hover: var(--color1);
--ws-urgent: var(--color12);
}
/* unset so we can style everything from the ground up. */
* {
all: unset;
color: var(--foreground);
font-size: 16px;
font-family: "Jost*", sans-serif;
border-radius: 100px;
}
button {
background-size: 400% 400%;
}
#bar-inner {
padding: 4px;
border: solid 2px;
border-color: var(--border-color);
background-color: var(--window-bg);
min-height: 28px;
}
#workspaces {
padding: 6px;
min-width: 0px;
background-color: var(--module-bg);
}
#workspaces>button {
padding: 0px 8px;
transition: padding 0.05s steps(8);
background-color: var(--ws-inactive);
}
#workspaces>button>label {
font-size: 0px;
}
#workspaces>button:hover {
background-color: var(--ws-hover);
}
#workspaces>button.urgent {
background-color: var(--ws-urgent);
}
#workspaces>button.active {
padding: 0px 32px;
background-color: var(--ws-active);
}
#workspaces>button.empty {
background-color: var(--ws-empty);
}
#date-time,
#hyprland-language,
#hyprland-window {
background-color: var(--module-bg);
padding: 0px 8px;
}
menu>menuitem>label,
#date-time>label,
#hyprland-language>label,
#hyprland-window>label {
font-weight: 900;
}
/* 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(--border-color);
}
#cpu-progress-bar,
#ram-progress-bar,
#volume-progress-bar {
color: transparent;
background-color: transparent
}
#cpu-progress-bar {
border: solid 0px alpha(var(--color9), 0.8);
}
#ram-progress-bar,
#volume-progress-bar {
border: solid 0px var(--border-color);
}
#widgets-container {
background-color: var(--module-bg);
padding: 2px;
}
tooltip {
border: solid 2px;
border-color: var(--border-color);
background-color: var(--window-bg);
}
tooltip>* {
padding: 2px 4px
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,49 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from .wl_buffer import WlBuffer # noqa: F401
from .wl_callback import WlCallback # noqa: F401
from .wl_compositor import WlCompositor # noqa: F401
from .wl_data_device import WlDataDevice # noqa: F401
from .wl_data_device_manager import WlDataDeviceManager # noqa: F401
from .wl_data_offer import WlDataOffer # noqa: F401
from .wl_data_source import WlDataSource # noqa: F401
from .wl_display import WlDisplay # noqa: F401
from .wl_keyboard import WlKeyboard # noqa: F401
from .wl_output import WlOutput # noqa: F401
from .wl_pointer import WlPointer # noqa: F401
from .wl_region import WlRegion # noqa: F401
from .wl_registry import WlRegistry # noqa: F401
from .wl_seat import WlSeat # noqa: F401
from .wl_shell import WlShell # noqa: F401
from .wl_shell_surface import WlShellSurface # noqa: F401
from .wl_shm import WlShm # noqa: F401
from .wl_shm_pool import WlShmPool # noqa: F401
from .wl_subcompositor import WlSubcompositor # noqa: F401
from .wl_subsurface import WlSubsurface # noqa: F401
from .wl_surface import WlSurface # noqa: F401
from .wl_touch import WlTouch # noqa: F401

View File

@@ -1,107 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import Global, Interface, Proxy, Resource
class WlBuffer(Interface):
"""Content for a :class:`~pywayland.protocol.wayland.WlSurface`
A buffer provides the content for a
:class:`~pywayland.protocol.wayland.WlSurface`. Buffers are created through
factory interfaces such as :class:`~pywayland.protocol.wayland.WlShm`,
wp_linux_buffer_params (from the linux-dmabuf protocol extension) or
similar. It has a width and a height and can be attached to a
:class:`~pywayland.protocol.wayland.WlSurface`, but the mechanism by which
a client provides and updates the contents is defined by the buffer factory
interface.
If the buffer uses a format that has an alpha channel, the alpha channel is
assumed to be premultiplied in the color channels unless otherwise
specified.
Note, because :class:`WlBuffer` objects are created from multiple
independent factory interfaces, the :class:`WlBuffer` interface is frozen
at version 1.
"""
name = "wl_buffer"
version = 1
class WlBufferProxy(Proxy[WlBuffer]):
interface = WlBuffer
@WlBuffer.request()
def destroy(self) -> None:
"""Destroy a buffer
Destroy a buffer. If and how you need to release the backing storage is
defined by the buffer factory interface.
For possible side-effects to a surface, see :func:`WlSurface.attach()
<pywayland.protocol.wayland.WlSurface.attach>`.
"""
self._marshal(0)
self._destroy()
class WlBufferResource(Resource):
interface = WlBuffer
@WlBuffer.event()
def release(self) -> None:
"""Compositor releases buffer
Sent when this :class:`WlBuffer` is no longer used by the compositor.
The client is now free to reuse or destroy this buffer and its backing
storage.
If a client receives a release event before the frame callback
requested in the same :func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` that attaches this
:class:`WlBuffer` to a surface, then the client is immediately free to
reuse the buffer and its backing storage, and does not need a second
buffer for the next surface content update. Typically this is possible,
when the compositor maintains a copy of the
:class:`~pywayland.protocol.wayland.WlSurface` contents, e.g. as a GL
texture. This is an important optimization for GL(ES) compositors with
:class:`~pywayland.protocol.wayland.WlShm` clients.
"""
self._post_event(0)
class WlBufferGlobal(Global):
interface = WlBuffer
WlBuffer._gen_c()
WlBuffer.proxy_class = WlBufferProxy
WlBuffer.resource_class = WlBufferResource
WlBuffer.global_class = WlBufferGlobal

View File

@@ -1,85 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class WlCallback(Interface):
"""Callback object
Clients can handle the 'done' event to get notified when the related
request is done.
Note, because :class:`WlCallback` objects are created from multiple
independent factory interfaces, the :class:`WlCallback` interface is frozen
at version 1.
"""
name = "wl_callback"
version = 1
class WlCallbackProxy(Proxy[WlCallback]):
interface = WlCallback
class WlCallbackResource(Resource):
interface = WlCallback
@WlCallback.event(
Argument(ArgumentType.Uint),
)
def done(self, callback_data: int) -> None:
"""Done event
Notify the client when the related request is done.
:param callback_data:
request-specific data for the callback
:type callback_data:
`ArgumentType.Uint`
"""
self._post_event(0, callback_data)
class WlCallbackGlobal(Global):
interface = WlCallback
WlCallback._gen_c()
WlCallback.proxy_class = WlCallbackProxy
WlCallback.resource_class = WlCallbackResource
WlCallback.global_class = WlCallbackGlobal

View File

@@ -1,98 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_region import WlRegion
from .wl_surface import WlSurface
class WlCompositor(Interface):
"""The compositor singleton
A compositor. This object is a singleton global. The compositor is in
charge of combining the contents of multiple surfaces into one displayable
output.
"""
name = "wl_compositor"
version = 6
class WlCompositorProxy(Proxy[WlCompositor]):
interface = WlCompositor
@WlCompositor.request(
Argument(ArgumentType.NewId, interface=WlSurface),
)
def create_surface(self) -> Proxy[WlSurface]:
"""Create new surface
Ask the compositor to create a new surface.
:returns:
:class:`~pywayland.protocol.wayland.WlSurface` -- the new surface
"""
id = self._marshal_constructor(0, WlSurface)
return id
@WlCompositor.request(
Argument(ArgumentType.NewId, interface=WlRegion),
)
def create_region(self) -> Proxy[WlRegion]:
"""Create new region
Ask the compositor to create a new region.
:returns:
:class:`~pywayland.protocol.wayland.WlRegion` -- the new region
"""
id = self._marshal_constructor(1, WlRegion)
return id
class WlCompositorResource(Resource):
interface = WlCompositor
class WlCompositorGlobal(Global):
interface = WlCompositor
WlCompositor._gen_c()
WlCompositor.proxy_class = WlCompositorProxy
WlCompositor.resource_class = WlCompositorResource
WlCompositor.global_class = WlCompositorGlobal

View File

@@ -1,311 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_data_offer import WlDataOffer
from .wl_data_source import WlDataSource
from .wl_surface import WlSurface
class WlDataDevice(Interface):
"""Data transfer device
There is one :class:`WlDataDevice` per seat which can be obtained from the
global :class:`~pywayland.protocol.wayland.WlDataDeviceManager` singleton.
A :class:`WlDataDevice` provides access to inter-client data transfer
mechanisms such as copy-and-paste and drag-and-drop.
"""
name = "wl_data_device"
version = 3
class error(enum.IntEnum):
role = 0
class WlDataDeviceProxy(Proxy[WlDataDevice]):
interface = WlDataDevice
@WlDataDevice.request(
Argument(ArgumentType.Object, interface=WlDataSource, nullable=True),
Argument(ArgumentType.Object, interface=WlSurface),
Argument(ArgumentType.Object, interface=WlSurface, nullable=True),
Argument(ArgumentType.Uint),
)
def start_drag(self, source: WlDataSource | None, origin: WlSurface, icon: WlSurface | None, serial: int) -> None:
"""Start drag-and-drop operation
This request asks the compositor to start a drag-and-drop operation on
behalf of the client.
The source argument is the data source that provides the data for the
eventual data transfer. If source is NULL, enter, leave and motion
events are sent only to the client that initiated the drag and the
client is expected to handle the data passing internally. If source is
destroyed, the drag-and-drop session will be cancelled.
The origin surface is the surface where the drag originates and the
client must have an active implicit grab that matches the serial.
The icon surface is an optional (can be NULL) surface that provides an
icon to be moved around with the cursor. Initially, the top-left
corner of the icon surface is placed at the cursor hotspot, but
subsequent :func:`WlSurface.attach()
<pywayland.protocol.wayland.WlSurface.attach>` request can move the
relative position. Attach requests must be confirmed with
:func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` as usual. The icon
surface is given the role of a drag-and-drop icon. If the icon surface
already has another role, it raises a protocol error.
The input region is ignored for wl_surfaces with the role of a drag-
and-drop icon.
:param source:
data source for the eventual transfer
:type source:
:class:`~pywayland.protocol.wayland.WlDataSource` or `None`
:param origin:
surface where the drag originates
:type origin:
:class:`~pywayland.protocol.wayland.WlSurface`
:param icon:
drag-and-drop icon surface
:type icon:
:class:`~pywayland.protocol.wayland.WlSurface` or `None`
:param serial:
serial number of the implicit grab on the origin
:type serial:
`ArgumentType.Uint`
"""
self._marshal(0, source, origin, icon, serial)
@WlDataDevice.request(
Argument(ArgumentType.Object, interface=WlDataSource, nullable=True),
Argument(ArgumentType.Uint),
)
def set_selection(self, source: WlDataSource | None, serial: int) -> None:
"""Copy data to the selection
This request asks the compositor to set the selection to the data from
the source on behalf of the client.
To unset the selection, set the source to NULL.
:param source:
data source for the selection
:type source:
:class:`~pywayland.protocol.wayland.WlDataSource` or `None`
:param serial:
serial number of the event that triggered this request
:type serial:
`ArgumentType.Uint`
"""
self._marshal(1, source, serial)
@WlDataDevice.request(version=2)
def release(self) -> None:
"""Destroy data device
This request destroys the data device.
"""
self._marshal(2)
self._destroy()
class WlDataDeviceResource(Resource):
interface = WlDataDevice
@WlDataDevice.event(
Argument(ArgumentType.NewId, interface=WlDataOffer),
)
def data_offer(self, id: WlDataOffer) -> None:
"""Introduce a new :class:`~pywayland.protocol.wayland.WlDataOffer`
The data_offer event introduces a new
:class:`~pywayland.protocol.wayland.WlDataOffer` object, which will
subsequently be used in either the data_device.enter event (for drag-
and-drop) or the data_device.selection event (for selections).
Immediately following the data_device.data_offer event, the new
data_offer object will send out data_offer.offer events to describe the
mime types it offers.
:param id:
the new data_offer object
:type id:
:class:`~pywayland.protocol.wayland.WlDataOffer`
"""
self._post_event(0, id)
@WlDataDevice.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlSurface),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Object, interface=WlDataOffer, nullable=True),
)
def enter(self, serial: int, surface: WlSurface, x: float, y: float, id: WlDataOffer | None) -> None:
"""Initiate drag-and-drop session
This event is sent when an active drag-and-drop pointer enters a
surface owned by the client. The position of the pointer at enter time
is provided by the x and y arguments, in surface-local coordinates.
:param serial:
serial number of the enter event
:type serial:
`ArgumentType.Uint`
:param surface:
client surface entered
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface`
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Fixed`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Fixed`
:param id:
source data_offer object
:type id:
:class:`~pywayland.protocol.wayland.WlDataOffer` or `None`
"""
self._post_event(1, serial, surface, x, y, id)
@WlDataDevice.event()
def leave(self) -> None:
"""End drag-and-drop session
This event is sent when the drag-and-drop pointer leaves the surface
and the session ends. The client must destroy the
:class:`~pywayland.protocol.wayland.WlDataOffer` introduced at enter
time at this point.
"""
self._post_event(2)
@WlDataDevice.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
)
def motion(self, time: int, x: float, y: float) -> None:
"""Drag-and-drop session motion
This event is sent when the drag-and-drop pointer moves within the
currently focused surface. The new position of the pointer is provided
by the x and y arguments, in surface-local coordinates.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Fixed`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Fixed`
"""
self._post_event(3, time, x, y)
@WlDataDevice.event()
def drop(self) -> None:
"""End drag-and-drop session successfully
The event is sent when a drag-and-drop operation is ended because the
implicit grab is removed.
The drag-and-drop destination is expected to honor the last action
received through :func:`WlDataOffer.action()
<pywayland.protocol.wayland.WlDataOffer.action>`, if the resulting
action is "copy" or "move", the destination can still perform
:func:`WlDataOffer.receive()
<pywayland.protocol.wayland.WlDataOffer.receive>` requests, and is
expected to end all transfers with a :func:`WlDataOffer.finish()
<pywayland.protocol.wayland.WlDataOffer.finish>` request.
If the resulting action is "ask", the action will not be considered
final. The drag-and-drop destination is expected to perform one last
:func:`WlDataOffer.set_actions()
<pywayland.protocol.wayland.WlDataOffer.set_actions>` request, or
:func:`WlDataOffer.destroy()
<pywayland.protocol.wayland.WlDataOffer.destroy>` in order to cancel
the operation.
"""
self._post_event(4)
@WlDataDevice.event(
Argument(ArgumentType.Object, interface=WlDataOffer, nullable=True),
)
def selection(self, id: WlDataOffer | None) -> None:
"""Advertise new selection
The selection event is sent out to notify the client of a new
:class:`~pywayland.protocol.wayland.WlDataOffer` for the selection for
this device. The data_device.data_offer and the data_offer.offer
events are sent out immediately before this event to introduce the data
offer object. The selection event is sent to a client immediately
before receiving keyboard focus and when a new selection is set while
the client has keyboard focus. The data_offer is valid until a new
data_offer or NULL is received or until the client loses keyboard
focus. Switching surface with keyboard focus within the same client
doesn't mean a new selection will be sent. The client must destroy the
previous selection data_offer, if any, upon receiving this event.
:param id:
selection data_offer object
:type id:
:class:`~pywayland.protocol.wayland.WlDataOffer` or `None`
"""
self._post_event(5, id)
class WlDataDeviceGlobal(Global):
interface = WlDataDevice
WlDataDevice._gen_c()
WlDataDevice.proxy_class = WlDataDeviceProxy
WlDataDevice.resource_class = WlDataDeviceResource
WlDataDevice.global_class = WlDataDeviceGlobal

View File

@@ -1,126 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_data_device import WlDataDevice
from .wl_data_source import WlDataSource
from .wl_seat import WlSeat
class WlDataDeviceManager(Interface):
"""Data transfer interface
The :class:`WlDataDeviceManager` is a singleton global object that provides
access to inter-client data transfer mechanisms such as copy-and-paste and
drag-and-drop. These mechanisms are tied to a
:class:`~pywayland.protocol.wayland.WlSeat` and this interface lets a
client get a :class:`~pywayland.protocol.wayland.WlDataDevice`
corresponding to a :class:`~pywayland.protocol.wayland.WlSeat`.
Depending on the version bound, the objects created from the bound
:class:`WlDataDeviceManager` object will have different requirements for
functioning properly. See :func:`WlDataSource.set_actions()
<pywayland.protocol.wayland.WlDataSource.set_actions>`,
:func:`WlDataOffer.accept()
<pywayland.protocol.wayland.WlDataOffer.accept>` and
:func:`WlDataOffer.finish()
<pywayland.protocol.wayland.WlDataOffer.finish>` for details.
"""
name = "wl_data_device_manager"
version = 3
class dnd_action(enum.IntFlag):
none = 0
copy = 1
move = 2
ask = 4
class WlDataDeviceManagerProxy(Proxy[WlDataDeviceManager]):
interface = WlDataDeviceManager
@WlDataDeviceManager.request(
Argument(ArgumentType.NewId, interface=WlDataSource),
)
def create_data_source(self) -> Proxy[WlDataSource]:
"""Create a new data source
Create a new data source.
:returns:
:class:`~pywayland.protocol.wayland.WlDataSource` -- data source to
create
"""
id = self._marshal_constructor(0, WlDataSource)
return id
@WlDataDeviceManager.request(
Argument(ArgumentType.NewId, interface=WlDataDevice),
Argument(ArgumentType.Object, interface=WlSeat),
)
def get_data_device(self, seat: WlSeat) -> Proxy[WlDataDevice]:
"""Create a new data device
Create a new data device for a given seat.
:param seat:
seat associated with the data device
:type seat:
:class:`~pywayland.protocol.wayland.WlSeat`
:returns:
:class:`~pywayland.protocol.wayland.WlDataDevice` -- data device to
create
"""
id = self._marshal_constructor(1, WlDataDevice, seat)
return id
class WlDataDeviceManagerResource(Resource):
interface = WlDataDeviceManager
class WlDataDeviceManagerGlobal(Global):
interface = WlDataDeviceManager
WlDataDeviceManager._gen_c()
WlDataDeviceManager.proxy_class = WlDataDeviceManagerProxy
WlDataDeviceManager.resource_class = WlDataDeviceManagerResource
WlDataDeviceManager.global_class = WlDataDeviceManagerGlobal

View File

@@ -1,325 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class WlDataOffer(Interface):
"""Offer to transfer data
A :class:`WlDataOffer` represents a piece of data offered for transfer by
another client (the source client). It is used by the copy-and-paste and
drag-and-drop mechanisms. The offer describes the different mime types
that the data can be converted to and provides the mechanism for
transferring the data directly from the source client.
"""
name = "wl_data_offer"
version = 3
class error(enum.IntEnum):
invalid_finish = 0
invalid_action_mask = 1
invalid_action = 2
invalid_offer = 3
class WlDataOfferProxy(Proxy[WlDataOffer]):
interface = WlDataOffer
@WlDataOffer.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.String, nullable=True),
)
def accept(self, serial: int, mime_type: str | None) -> None:
"""Accept one of the offered mime types
Indicate that the client can accept the given mime type, or NULL for
not accepted.
For objects of version 2 or older, this request is used by the client
to give feedback whether the client can receive the given mime type, or
NULL if none is accepted; the feedback does not determine whether the
drag-and-drop operation succeeds or not.
For objects of version 3 or newer, this request determines the final
result of the drag-and-drop operation. If the end result is that no
mime types were accepted, the drag-and-drop operation will be cancelled
and the corresponding drag source will receive
:func:`WlDataSource.cancelled()
<pywayland.protocol.wayland.WlDataSource.cancelled>`. Clients may still
use this event in conjunction with :func:`WlDataSource.action()
<pywayland.protocol.wayland.WlDataSource.action>` for feedback.
:param serial:
serial number of the accept request
:type serial:
`ArgumentType.Uint`
:param mime_type:
mime type accepted by the client
:type mime_type:
`ArgumentType.String` or `None`
"""
self._marshal(0, serial, mime_type)
@WlDataOffer.request(
Argument(ArgumentType.String),
Argument(ArgumentType.FileDescriptor),
)
def receive(self, mime_type: str, fd: int) -> None:
"""Request that the data is transferred
To transfer the offered data, the client issues this request and
indicates the mime type it wants to receive. The transfer happens
through the passed file descriptor (typically created with the pipe
system call). The source client writes the data in the mime type
representation requested and then closes the file descriptor.
The receiving client reads from the read end of the pipe until EOF and
then closes its end, at which point the transfer is complete.
This request may happen multiple times for different mime types, both
before and after :func:`WlDataDevice.drop()
<pywayland.protocol.wayland.WlDataDevice.drop>`. Drag-and-drop
destination clients may preemptively fetch data or examine it more
closely to determine acceptance.
:param mime_type:
mime type desired by receiver
:type mime_type:
`ArgumentType.String`
:param fd:
file descriptor for data transfer
:type fd:
`ArgumentType.FileDescriptor`
"""
self._marshal(1, mime_type, fd)
@WlDataOffer.request()
def destroy(self) -> None:
"""Destroy data offer
Destroy the data offer.
"""
self._marshal(2)
self._destroy()
@WlDataOffer.request(version=3)
def finish(self) -> None:
"""The offer will no longer be used
Notifies the compositor that the drag destination successfully finished
the drag-and-drop operation.
Upon receiving this request, the compositor will emit
:func:`WlDataSource.dnd_finished()
<pywayland.protocol.wayland.WlDataSource.dnd_finished>` on the drag
source client.
It is a client error to perform other requests than
:func:`WlDataOffer.destroy()` after this one. It is also an error to
perform this request after a NULL mime type has been set in
:func:`WlDataOffer.accept()` or no action was received through
:func:`WlDataOffer.action()`.
If :func:`WlDataOffer.finish()` request is received for a non drag and
drop operation, the invalid_finish protocol error is raised.
"""
self._marshal(3)
@WlDataOffer.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
version=3,
)
def set_actions(self, dnd_actions: int, preferred_action: int) -> None:
"""Set the available/preferred drag-and-drop actions
Sets the actions that the destination side client supports for this
operation. This request may trigger the emission of
:func:`WlDataSource.action()
<pywayland.protocol.wayland.WlDataSource.action>` and
:func:`WlDataOffer.action()` events if the compositor needs to change
the selected action.
This request can be called multiple times throughout the drag-and-drop
operation, typically in response to :func:`WlDataDevice.enter()
<pywayland.protocol.wayland.WlDataDevice.enter>` or
:func:`WlDataDevice.motion()
<pywayland.protocol.wayland.WlDataDevice.motion>` events.
This request determines the final result of the drag-and-drop
operation. If the end result is that no action is accepted, the drag
source will receive :func:`WlDataSource.cancelled()
<pywayland.protocol.wayland.WlDataSource.cancelled>`.
The dnd_actions argument must contain only values expressed in the
:func:`WlDataDeviceManager.dnd_actions()
<pywayland.protocol.wayland.WlDataDeviceManager.dnd_actions>` enum, and
the preferred_action argument must only contain one of those values
set, otherwise it will result in a protocol error.
While managing an "ask" action, the destination drag-and-drop client
may perform further :func:`WlDataOffer.receive()` requests, and is
expected to perform one last :func:`WlDataOffer.set_actions()` request
with a preferred action other than "ask" (and optionally
:func:`WlDataOffer.accept()`) before requesting
:func:`WlDataOffer.finish()`, in order to convey the action selected by
the user. If the preferred action is not in the
:func:`WlDataOffer.source_actions()` mask, an error will be raised.
If the "ask" action is dismissed (e.g. user cancellation), the client
is expected to perform :func:`WlDataOffer.destroy()` right away.
This request can only be made on drag-and-drop offers, a protocol error
will be raised otherwise.
:param dnd_actions:
actions supported by the destination client
:type dnd_actions:
`ArgumentType.Uint`
:param preferred_action:
action preferred by the destination client
:type preferred_action:
`ArgumentType.Uint`
"""
self._marshal(4, dnd_actions, preferred_action)
class WlDataOfferResource(Resource):
interface = WlDataOffer
@WlDataOffer.event(
Argument(ArgumentType.String),
)
def offer(self, mime_type: str) -> None:
"""Advertise offered mime type
Sent immediately after creating the :class:`WlDataOffer` object. One
event per offered mime type.
:param mime_type:
offered mime type
:type mime_type:
`ArgumentType.String`
"""
self._post_event(0, mime_type)
@WlDataOffer.event(
Argument(ArgumentType.Uint),
version=3,
)
def source_actions(self, source_actions: int) -> None:
"""Notify the source-side available actions
This event indicates the actions offered by the data source. It will be
sent immediately after creating the :class:`WlDataOffer` object, or
anytime the source side changes its offered actions through
:func:`WlDataSource.set_actions()
<pywayland.protocol.wayland.WlDataSource.set_actions>`.
:param source_actions:
actions offered by the data source
:type source_actions:
`ArgumentType.Uint`
"""
self._post_event(1, source_actions)
@WlDataOffer.event(
Argument(ArgumentType.Uint),
version=3,
)
def action(self, dnd_action: int) -> None:
"""Notify the selected action
This event indicates the action selected by the compositor after
matching the source/destination side actions. Only one action (or none)
will be offered here.
This event can be emitted multiple times during the drag-and-drop
operation in response to destination side action changes through
:func:`WlDataOffer.set_actions()`.
This event will no longer be emitted after :func:`WlDataDevice.drop()
<pywayland.protocol.wayland.WlDataDevice.drop>` happened on the drag-
and-drop destination, the client must honor the last action received,
or the last preferred one set through :func:`WlDataOffer.set_actions()`
when handling an "ask" action.
Compositors may also change the selected action on the fly, mainly in
response to keyboard modifier changes during the drag-and-drop
operation.
The most recent action received is always the valid one. Prior to
receiving :func:`WlDataDevice.drop()
<pywayland.protocol.wayland.WlDataDevice.drop>`, the chosen action may
change (e.g. due to keyboard modifiers being pressed). At the time of
receiving :func:`WlDataDevice.drop()
<pywayland.protocol.wayland.WlDataDevice.drop>` the drag-and-drop
destination must honor the last action received.
Action changes may still happen after :func:`WlDataDevice.drop()
<pywayland.protocol.wayland.WlDataDevice.drop>`, especially on "ask"
actions, where the drag-and-drop destination may choose another action
afterwards. Action changes happening at this stage are always the
result of inter-client negotiation, the compositor shall no longer be
able to induce a different action.
Upon "ask" actions, it is expected that the drag-and-drop destination
may potentially choose a different action and/or mime type, based on
:func:`WlDataOffer.source_actions()` and finally chosen by the user
(e.g. popping up a menu with the available options). The final
:func:`WlDataOffer.set_actions()` and :func:`WlDataOffer.accept()`
requests must happen before the call to :func:`WlDataOffer.finish()`.
:param dnd_action:
action selected by the compositor
:type dnd_action:
`ArgumentType.Uint`
"""
self._post_event(2, dnd_action)
class WlDataOfferGlobal(Global):
interface = WlDataOffer
WlDataOffer._gen_c()
WlDataOffer.proxy_class = WlDataOfferProxy
WlDataOffer.resource_class = WlDataOfferResource
WlDataOffer.global_class = WlDataOfferGlobal

View File

@@ -1,273 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class WlDataSource(Interface):
"""Offer to transfer data
The :class:`WlDataSource` object is the source side of a
:class:`~pywayland.protocol.wayland.WlDataOffer`. It is created by the
source client in a data transfer and provides a way to describe the offered
data and a way to respond to requests to transfer the data.
"""
name = "wl_data_source"
version = 3
class error(enum.IntEnum):
invalid_action_mask = 0
invalid_source = 1
class WlDataSourceProxy(Proxy[WlDataSource]):
interface = WlDataSource
@WlDataSource.request(
Argument(ArgumentType.String),
)
def offer(self, mime_type: str) -> None:
"""Add an offered mime type
This request adds a mime type to the set of mime types advertised to
targets. Can be called several times to offer multiple types.
:param mime_type:
mime type offered by the data source
:type mime_type:
`ArgumentType.String`
"""
self._marshal(0, mime_type)
@WlDataSource.request()
def destroy(self) -> None:
"""Destroy the data source
Destroy the data source.
"""
self._marshal(1)
self._destroy()
@WlDataSource.request(
Argument(ArgumentType.Uint),
version=3,
)
def set_actions(self, dnd_actions: int) -> None:
"""Set the available drag-and-drop actions
Sets the actions that the source side client supports for this
operation. This request may trigger :func:`WlDataSource.action()` and
:func:`WlDataOffer.action()
<pywayland.protocol.wayland.WlDataOffer.action>` events if the
compositor needs to change the selected action.
The dnd_actions argument must contain only values expressed in the
:func:`WlDataDeviceManager.dnd_actions()
<pywayland.protocol.wayland.WlDataDeviceManager.dnd_actions>` enum,
otherwise it will result in a protocol error.
This request must be made once only, and can only be made on sources
used in drag-and-drop, so it must be performed before
:func:`WlDataDevice.start_drag()
<pywayland.protocol.wayland.WlDataDevice.start_drag>`. Attempting to
use the source other than for drag-and-drop will raise a protocol
error.
:param dnd_actions:
actions supported by the data source
:type dnd_actions:
`ArgumentType.Uint`
"""
self._marshal(2, dnd_actions)
class WlDataSourceResource(Resource):
interface = WlDataSource
@WlDataSource.event(
Argument(ArgumentType.String, nullable=True),
)
def target(self, mime_type: str | None) -> None:
"""A target accepts an offered mime type
Sent when a target accepts pointer_focus or motion events. If a target
does not accept any of the offered types, type is NULL.
Used for feedback during drag-and-drop.
:param mime_type:
mime type accepted by the target
:type mime_type:
`ArgumentType.String` or `None`
"""
self._post_event(0, mime_type)
@WlDataSource.event(
Argument(ArgumentType.String),
Argument(ArgumentType.FileDescriptor),
)
def send(self, mime_type: str, fd: int) -> None:
"""Send the data
Request for data from the client. Send the data as the specified mime
type over the passed file descriptor, then close it.
:param mime_type:
mime type for the data
:type mime_type:
`ArgumentType.String`
:param fd:
file descriptor for the data
:type fd:
`ArgumentType.FileDescriptor`
"""
self._post_event(1, mime_type, fd)
@WlDataSource.event()
def cancelled(self) -> None:
"""Selection was cancelled
This data source is no longer valid. There are several reasons why this
could happen:
- The data source has been replaced by another data source.
- The drag-and-drop operation was performed, but the drop destination
did not accept any of the mime types offered through
:func:`WlDataSource.target()`.
- The drag-and-drop operation was performed, but the drop destination
did not select any of the actions present in the mask offered through
:func:`WlDataSource.action()`.
- The drag-and-drop operation was performed but didn't happen over a
surface.
- The compositor cancelled the drag-and-drop operation (e.g. compositor
dependent timeouts to avoid stale drag-and-drop transfers).
The client should clean up and destroy this data source.
For objects of version 2 or older, :func:`WlDataSource.cancelled()`
will only be emitted if the data source was replaced by another data
source.
"""
self._post_event(2)
@WlDataSource.event(version=3)
def dnd_drop_performed(self) -> None:
"""The drag-and-drop operation physically finished
The user performed the drop action. This event does not indicate
acceptance, :func:`WlDataSource.cancelled()` may still be emitted
afterwards if the drop destination does not accept any mime type.
However, this event might however not be received if the compositor
cancelled the drag-and-drop operation before this event could happen.
Note that the data_source may still be used in the future and should
not be destroyed here.
"""
self._post_event(3)
@WlDataSource.event(version=3)
def dnd_finished(self) -> None:
"""The drag-and-drop operation concluded
The drop destination finished interoperating with this data source, so
the client is now free to destroy this data source and free all
associated data.
If the action used to perform the operation was "move", the source can
now delete the transferred data.
"""
self._post_event(4)
@WlDataSource.event(
Argument(ArgumentType.Uint),
version=3,
)
def action(self, dnd_action: int) -> None:
"""Notify the selected action
This event indicates the action selected by the compositor after
matching the source/destination side actions. Only one action (or none)
will be offered here.
This event can be emitted multiple times during the drag-and-drop
operation, mainly in response to destination side changes through
:func:`WlDataOffer.set_actions()
<pywayland.protocol.wayland.WlDataOffer.set_actions>`, and as the data
device enters/leaves surfaces.
It is only possible to receive this event after
:func:`WlDataSource.dnd_drop_performed()` if the drag-and-drop
operation ended in an "ask" action, in which case the final
:func:`WlDataSource.action()` event will happen immediately before
:func:`WlDataSource.dnd_finished()`.
Compositors may also change the selected action on the fly, mainly in
response to keyboard modifier changes during the drag-and-drop
operation.
The most recent action received is always the valid one. The chosen
action may change alongside negotiation (e.g. an "ask" action can turn
into a "move" operation), so the effects of the final action must
always be applied in :func:`WlDataOffer.dnd_finished()
<pywayland.protocol.wayland.WlDataOffer.dnd_finished>`.
Clients can trigger cursor surface changes from this point, so they
reflect the current action.
:param dnd_action:
action selected by the compositor
:type dnd_action:
`ArgumentType.Uint`
"""
self._post_event(5, dnd_action)
class WlDataSourceGlobal(Global):
interface = WlDataSource
WlDataSource._gen_c()
WlDataSource.proxy_class = WlDataSourceProxy
WlDataSource.resource_class = WlDataSourceResource
WlDataSource.global_class = WlDataSourceGlobal

View File

@@ -1,175 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from typing import Any
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_callback import WlCallback
from .wl_registry import WlRegistry
class WlDisplay(Interface):
"""Core global object
The core global object. This is a special singleton object. It is used
for internal Wayland protocol features.
"""
name = "wl_display"
version = 1
class error(enum.IntEnum):
invalid_object = 0
invalid_method = 1
no_memory = 2
implementation = 3
class WlDisplayProxy(Proxy[WlDisplay]):
interface = WlDisplay
@WlDisplay.request(
Argument(ArgumentType.NewId, interface=WlCallback),
)
def sync(self) -> Proxy[WlCallback]:
"""Asynchronous roundtrip
The sync request asks the server to emit the 'done' event on the
returned :class:`~pywayland.protocol.wayland.WlCallback` object. Since
requests are handled in-order and events are delivered in-order, this
can be used as a barrier to ensure all previous requests and the
resulting events have been handled.
The object returned by this request will be destroyed by the compositor
after the callback is fired and as such the client must not attempt to
use it after that point.
The callback_data passed in the callback is the event serial.
:returns:
:class:`~pywayland.protocol.wayland.WlCallback` -- callback object
for the sync request
"""
callback = self._marshal_constructor(0, WlCallback)
return callback
@WlDisplay.request(
Argument(ArgumentType.NewId, interface=WlRegistry),
)
def get_registry(self) -> Proxy[WlRegistry]:
"""Get global registry object
This request creates a registry object that allows the client to list
and bind the global objects available from the compositor.
It should be noted that the server side resources consumed in response
to a get_registry request can only be released when the client
disconnects, not when the client side proxy is destroyed. Therefore,
clients should invoke get_registry as infrequently as possible to avoid
wasting memory.
:returns:
:class:`~pywayland.protocol.wayland.WlRegistry` -- global registry
object
"""
registry = self._marshal_constructor(1, WlRegistry)
return registry
class WlDisplayResource(Resource):
interface = WlDisplay
@WlDisplay.event(
Argument(ArgumentType.Object),
Argument(ArgumentType.Uint),
Argument(ArgumentType.String),
)
def error(self, object_id: Any, code: int, message: str) -> None:
"""Fatal error event
The error event is sent out when a fatal (non-recoverable) error has
occurred. The object_id argument is the object where the error
occurred, most often in response to a request to that object. The code
identifies the error and is defined by the object interface. As such,
each interface defines its own set of error codes. The message is a
brief description of the error, for (debugging) convenience.
:param object_id:
object where the error occurred
:type object_id:
`ArgumentType.Object`
:param code:
error code
:type code:
`ArgumentType.Uint`
:param message:
error description
:type message:
`ArgumentType.String`
"""
self._post_event(0, object_id, code, message)
@WlDisplay.event(
Argument(ArgumentType.Uint),
)
def delete_id(self, id: int) -> None:
"""Acknowledge object id deletion
This event is used internally by the object ID management logic. When a
client deletes an object that it had created, the server will send this
event to acknowledge that it has seen the delete request. When the
client receives this event, it will know that it can safely reuse the
object ID.
:param id:
deleted object ID
:type id:
`ArgumentType.Uint`
"""
self._post_event(1, id)
class WlDisplayGlobal(Global):
interface = WlDisplay
WlDisplay._gen_c()
WlDisplay.proxy_class = WlDisplayProxy
WlDisplay.resource_class = WlDisplayResource
WlDisplay.global_class = WlDisplayGlobal

View File

@@ -1,276 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_surface import WlSurface
class WlKeyboard(Interface):
"""Keyboard input device
The :class:`WlKeyboard` interface represents one or more keyboards
associated with a seat.
"""
name = "wl_keyboard"
version = 9
class keymap_format(enum.IntEnum):
no_keymap = 0
xkb_v1 = 1
class key_state(enum.IntEnum):
released = 0
pressed = 1
class WlKeyboardProxy(Proxy[WlKeyboard]):
interface = WlKeyboard
@WlKeyboard.request(version=3)
def release(self) -> None:
"""Release the keyboard object
"""
self._marshal(0)
self._destroy()
class WlKeyboardResource(Resource):
interface = WlKeyboard
@WlKeyboard.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.FileDescriptor),
Argument(ArgumentType.Uint),
)
def keymap(self, format: int, fd: int, size: int) -> None:
"""Keyboard mapping
This event provides a file descriptor to the client which can be
memory-mapped in read-only mode to provide a keyboard mapping
description.
From version 7 onwards, the fd must be mapped with MAP_PRIVATE by the
recipient, as MAP_SHARED may fail.
:param format:
keymap format
:type format:
`ArgumentType.Uint`
:param fd:
keymap file descriptor
:type fd:
`ArgumentType.FileDescriptor`
:param size:
keymap size, in bytes
:type size:
`ArgumentType.Uint`
"""
self._post_event(0, format, fd, size)
@WlKeyboard.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlSurface),
Argument(ArgumentType.Array),
)
def enter(self, serial: int, surface: WlSurface, keys: list) -> None:
"""Enter event
Notification that this seat's keyboard focus is on a certain surface.
The compositor must send the :func:`WlKeyboard.modifiers()` event after
this event.
:param serial:
serial number of the enter event
:type serial:
`ArgumentType.Uint`
:param surface:
surface gaining keyboard focus
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface`
:param keys:
the currently pressed keys
:type keys:
`ArgumentType.Array`
"""
self._post_event(1, serial, surface, keys)
@WlKeyboard.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlSurface),
)
def leave(self, serial: int, surface: WlSurface) -> None:
"""Leave event
Notification that this seat's keyboard focus is no longer on a certain
surface.
The leave notification is sent before the enter notification for the
new focus.
After this event client must assume that all keys, including modifiers,
are lifted and also it must stop key repeating if there's some going
on.
:param serial:
serial number of the leave event
:type serial:
`ArgumentType.Uint`
:param surface:
surface that lost keyboard focus
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface`
"""
self._post_event(2, serial, surface)
@WlKeyboard.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def key(self, serial: int, time: int, key: int, state: int) -> None:
"""Key event
A key was pressed or released. The time argument is a timestamp with
millisecond granularity, with an undefined base.
The key is a platform-specific key code that can be interpreted by
feeding it to the keyboard mapping (see the keymap event).
If this event produces a change in modifiers, then the resulting
:func:`WlKeyboard.modifiers()` event must be sent after this event.
:param serial:
serial number of the key event
:type serial:
`ArgumentType.Uint`
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param key:
key that produced the event
:type key:
`ArgumentType.Uint`
:param state:
physical state of the key
:type state:
`ArgumentType.Uint`
"""
self._post_event(3, serial, time, key, state)
@WlKeyboard.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def modifiers(self, serial: int, mods_depressed: int, mods_latched: int, mods_locked: int, group: int) -> None:
"""Modifier and group state
Notifies clients that the modifier and/or group state has changed, and
it should update its local state.
:param serial:
serial number of the modifiers event
:type serial:
`ArgumentType.Uint`
:param mods_depressed:
depressed modifiers
:type mods_depressed:
`ArgumentType.Uint`
:param mods_latched:
latched modifiers
:type mods_latched:
`ArgumentType.Uint`
:param mods_locked:
locked modifiers
:type mods_locked:
`ArgumentType.Uint`
:param group:
keyboard layout
:type group:
`ArgumentType.Uint`
"""
self._post_event(4, serial, mods_depressed, mods_latched, mods_locked, group)
@WlKeyboard.event(
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
version=4,
)
def repeat_info(self, rate: int, delay: int) -> None:
"""Repeat rate and delay
Informs the client about the keyboard's repeat rate and delay.
This event is sent as soon as the :class:`WlKeyboard` object has been
created, and is guaranteed to be received by the client before any key
press event.
Negative values for either rate or delay are illegal. A rate of zero
will disable any repeating (regardless of the value of delay).
This event can be sent later on as well with a new value if necessary,
so clients should continue listening for the event past the creation of
:class:`WlKeyboard`.
:param rate:
the rate of repeating keys in characters per second
:type rate:
`ArgumentType.Int`
:param delay:
delay in milliseconds since key down until repeating starts
:type delay:
`ArgumentType.Int`
"""
self._post_event(5, rate, delay)
class WlKeyboardGlobal(Global):
interface = WlKeyboard
WlKeyboard._gen_c()
WlKeyboard.proxy_class = WlKeyboardProxy
WlKeyboard.resource_class = WlKeyboardResource
WlKeyboard.global_class = WlKeyboardGlobal

View File

@@ -1,349 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class WlOutput(Interface):
"""Compositor output region
An output describes part of the compositor geometry. The compositor works
in the 'compositor coordinate system' and an output corresponds to a
rectangular area in that space that is actually visible. This typically
corresponds to a monitor that displays part of the compositor space. This
object is published as global during start up, or when a monitor is
hotplugged.
"""
name = "wl_output"
version = 4
class subpixel(enum.IntEnum):
unknown = 0
none = 1
horizontal_rgb = 2
horizontal_bgr = 3
vertical_rgb = 4
vertical_bgr = 5
class transform(enum.IntEnum):
normal = 0
transform_90 = 1
transform_180 = 2
transform_270 = 3
flipped = 4
flipped_90 = 5
flipped_180 = 6
flipped_270 = 7
class mode(enum.IntFlag):
current = 0x1
preferred = 0x2
class WlOutputProxy(Proxy[WlOutput]):
interface = WlOutput
@WlOutput.request(version=3)
def release(self) -> None:
"""Release the output object
Using this request a client can tell the server that it is not going to
use the output object anymore.
"""
self._marshal(0)
self._destroy()
class WlOutputResource(Resource):
interface = WlOutput
@WlOutput.event(
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.String),
Argument(ArgumentType.String),
Argument(ArgumentType.Int),
)
def geometry(self, x: int, y: int, physical_width: int, physical_height: int, subpixel: int, make: str, model: str, transform: int) -> None:
"""Properties of the output
The geometry event describes geometric properties of the output. The
event is sent when binding to the output object and whenever any of the
properties change.
The physical size can be set to zero if it doesn't make sense for this
output (e.g. for projectors or virtual outputs).
The geometry event will be followed by a done event (starting from
version 2).
Note: :class:`WlOutput` only advertises partial information about the
output position and identification. Some compositors, for instance
those not implementing a desktop-style output layout or those exposing
virtual outputs, might fake this information. Instead of using x and y,
clients should use xdg_output.logical_position. Instead of using make
and model, clients should use name and description.
:param x:
x position within the global compositor space
:type x:
`ArgumentType.Int`
:param y:
y position within the global compositor space
:type y:
`ArgumentType.Int`
:param physical_width:
width in millimeters of the output
:type physical_width:
`ArgumentType.Int`
:param physical_height:
height in millimeters of the output
:type physical_height:
`ArgumentType.Int`
:param subpixel:
subpixel orientation of the output
:type subpixel:
`ArgumentType.Int`
:param make:
textual description of the manufacturer
:type make:
`ArgumentType.String`
:param model:
textual description of the model
:type model:
`ArgumentType.String`
:param transform:
transform that maps framebuffer to output
:type transform:
`ArgumentType.Int`
"""
self._post_event(0, x, y, physical_width, physical_height, subpixel, make, model, transform)
@WlOutput.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
)
def mode(self, flags: int, width: int, height: int, refresh: int) -> None:
"""Advertise available modes for the output
The mode event describes an available mode for the output.
The event is sent when binding to the output object and there will
always be one mode, the current mode. The event is sent again if an
output changes mode, for the mode that is now current. In other words,
the current mode is always the last mode that was received with the
current flag set.
Non-current modes are deprecated. A compositor can decide to only
advertise the current mode and never send other modes. Clients should
not rely on non-current modes.
The size of a mode is given in physical hardware units of the output
device. This is not necessarily the same as the output size in the
global compositor space. For instance, the output may be scaled, as
described in :func:`WlOutput.scale()`, or transformed, as described in
:func:`WlOutput.transform()`. Clients willing to retrieve the output
size in the global compositor space should use xdg_output.logical_size
instead.
The vertical refresh rate can be set to zero if it doesn't make sense
for this output (e.g. for virtual outputs).
The mode event will be followed by a done event (starting from version
2).
Clients should not use the refresh rate to schedule frames. Instead,
they should use the :func:`WlSurface.frame()
<pywayland.protocol.wayland.WlSurface.frame>` event or the
presentation-time protocol.
Note: this information is not always meaningful for all outputs. Some
compositors, such as those exposing virtual outputs, might fake the
refresh rate or the size.
:param flags:
bitfield of mode flags
:type flags:
`ArgumentType.Uint`
:param width:
width of the mode in hardware units
:type width:
`ArgumentType.Int`
:param height:
height of the mode in hardware units
:type height:
`ArgumentType.Int`
:param refresh:
vertical refresh rate in mHz
:type refresh:
`ArgumentType.Int`
"""
self._post_event(1, flags, width, height, refresh)
@WlOutput.event(version=2)
def done(self) -> None:
"""Sent all information about output
This event is sent after all other properties have been sent after
binding to the output object and after any other property changes done
after that. This allows changes to the output properties to be seen as
atomic, even if they happen via multiple events.
"""
self._post_event(2)
@WlOutput.event(
Argument(ArgumentType.Int),
version=2,
)
def scale(self, factor: int) -> None:
"""Output scaling properties
This event contains scaling geometry information that is not in the
geometry event. It may be sent after binding the output object or if
the output scale changes later. If it is not sent, the client should
assume a scale of 1.
A scale larger than 1 means that the compositor will automatically
scale surface buffers by this amount when rendering. This is used for
very high resolution displays where applications rendering at the
native resolution would be too small to be legible.
It is intended that scaling aware clients track the current output of a
surface, and if it is on a scaled output it should use
:func:`WlSurface.set_buffer_scale()
<pywayland.protocol.wayland.WlSurface.set_buffer_scale>` with the scale
of the output. That way the compositor can avoid scaling the surface,
and the client can supply a higher detail image.
The scale event will be followed by a done event.
:param factor:
scaling factor of output
:type factor:
`ArgumentType.Int`
"""
self._post_event(3, factor)
@WlOutput.event(
Argument(ArgumentType.String),
version=4,
)
def name(self, name: str) -> None:
"""Name of this output
Many compositors will assign user-friendly names to their outputs, show
them to the user, allow the user to refer to an output, etc. The client
may wish to know this name as well to offer the user similar behaviors.
The name is a UTF-8 string with no convention defined for its contents.
Each name is unique among all :class:`WlOutput` globals. The name is
only guaranteed to be unique for the compositor instance.
The same output name is used for all clients for a given
:class:`WlOutput` global. Thus, the name can be shared across processes
to refer to a specific :class:`WlOutput` global.
The name is not guaranteed to be persistent across sessions, thus
cannot be used to reliably identify an output in e.g. configuration
files.
Examples of names include 'HDMI-A-1', 'WL-1', 'X11-1', etc. However, do
not assume that the name is a reflection of an underlying DRM
connector, X11 connection, etc.
The name event is sent after binding the output object. This event is
only sent once per output object, and the name does not change over the
lifetime of the :class:`WlOutput` global.
Compositors may re-use the same output name if the :class:`WlOutput`
global is destroyed and re-created later. Compositors should avoid re-
using the same name if possible.
The name event will be followed by a done event.
:param name:
output name
:type name:
`ArgumentType.String`
"""
self._post_event(4, name)
@WlOutput.event(
Argument(ArgumentType.String),
version=4,
)
def description(self, description: str) -> None:
"""Human-readable description of this output
Many compositors can produce human-readable descriptions of their
outputs. The client may wish to know this description as well, e.g. for
output selection purposes.
The description is a UTF-8 string with no convention defined for its
contents. The description is not guaranteed to be unique among all
:class:`WlOutput` globals. Examples might include 'Foocorp 11" Display'
or 'Virtual X11 output via :1'.
The description event is sent after binding the output object and
whenever the description changes. The description is optional, and may
not be sent at all.
The description event will be followed by a done event.
:param description:
output description
:type description:
`ArgumentType.String`
"""
self._post_event(5, description)
class WlOutputGlobal(Global):
interface = WlOutput
WlOutput._gen_c()
WlOutput.proxy_class = WlOutputProxy
WlOutput.resource_class = WlOutputResource
WlOutput.global_class = WlOutputGlobal

View File

@@ -1,592 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_surface import WlSurface
class WlPointer(Interface):
"""Pointer input device
The :class:`WlPointer` interface represents one or more input devices, such
as mice, which control the pointer location and pointer_focus of a seat.
The :class:`WlPointer` interface generates motion, enter and leave events
for the surfaces that the pointer is located over, and button and axis
events for button presses, button releases and scrolling.
"""
name = "wl_pointer"
version = 9
class error(enum.IntEnum):
role = 0
class button_state(enum.IntEnum):
released = 0
pressed = 1
class axis(enum.IntEnum):
vertical_scroll = 0
horizontal_scroll = 1
class axis_source(enum.IntEnum):
wheel = 0
finger = 1
continuous = 2
wheel_tilt = 3
class axis_relative_direction(enum.IntEnum):
identical = 0
inverted = 1
class WlPointerProxy(Proxy[WlPointer]):
interface = WlPointer
@WlPointer.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlSurface, nullable=True),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
)
def set_cursor(self, serial: int, surface: WlSurface | None, hotspot_x: int, hotspot_y: int) -> None:
"""Set the pointer surface
Set the pointer surface, i.e., the surface that contains the pointer
image (cursor). This request gives the surface the role of a cursor. If
the surface already has another role, it raises a protocol error.
The cursor actually changes only if the pointer focus for this device
is one of the requesting client's surfaces or the surface parameter is
the current pointer surface. If there was a previous surface set with
this request it is replaced. If surface is NULL, the pointer image is
hidden.
The parameters hotspot_x and hotspot_y define the position of the
pointer surface relative to the pointer location. Its top-left corner
is always at (x, y) - (hotspot_x, hotspot_y), where (x, y) are the
coordinates of the pointer location, in surface-local coordinates.
On surface.attach requests to the pointer surface, hotspot_x and
hotspot_y are decremented by the x and y parameters passed to the
request. Attach must be confirmed by :func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` as usual.
The hotspot can also be updated by passing the currently set pointer
surface to this request with new values for hotspot_x and hotspot_y.
The input region is ignored for wl_surfaces with the role of a cursor.
When the use as a cursor ends, the
:class:`~pywayland.protocol.wayland.WlSurface` is unmapped.
The serial parameter must match the latest :func:`WlPointer.enter()`
serial number sent to the client. Otherwise the request will be
ignored.
:param serial:
serial number of the enter event
:type serial:
`ArgumentType.Uint`
:param surface:
pointer surface
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface` or `None`
:param hotspot_x:
surface-local x coordinate
:type hotspot_x:
`ArgumentType.Int`
:param hotspot_y:
surface-local y coordinate
:type hotspot_y:
`ArgumentType.Int`
"""
self._marshal(0, serial, surface, hotspot_x, hotspot_y)
@WlPointer.request(version=3)
def release(self) -> None:
"""Release the pointer object
Using this request a client can tell the server that it is not going to
use the pointer object anymore.
This request destroys the pointer proxy object, so clients must not
call wl_pointer_destroy() after using this request.
"""
self._marshal(1)
self._destroy()
class WlPointerResource(Resource):
interface = WlPointer
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlSurface),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
)
def enter(self, serial: int, surface: WlSurface, surface_x: float, surface_y: float) -> None:
"""Enter event
Notification that this seat's pointer is focused on a certain surface.
When a seat's focus enters a surface, the pointer image is undefined
and a client should respond to this event by setting an appropriate
pointer image with the set_cursor request.
:param serial:
serial number of the enter event
:type serial:
`ArgumentType.Uint`
:param surface:
surface entered by the pointer
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface`
:param surface_x:
surface-local x coordinate
:type surface_x:
`ArgumentType.Fixed`
:param surface_y:
surface-local y coordinate
:type surface_y:
`ArgumentType.Fixed`
"""
self._post_event(0, serial, surface, surface_x, surface_y)
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlSurface),
)
def leave(self, serial: int, surface: WlSurface) -> None:
"""Leave event
Notification that this seat's pointer is no longer focused on a certain
surface.
The leave notification is sent before the enter notification for the
new focus.
:param serial:
serial number of the leave event
:type serial:
`ArgumentType.Uint`
:param surface:
surface left by the pointer
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface`
"""
self._post_event(1, serial, surface)
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
)
def motion(self, time: int, surface_x: float, surface_y: float) -> None:
"""Pointer motion event
Notification of pointer location change. The arguments surface_x and
surface_y are the location relative to the focused surface.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param surface_x:
surface-local x coordinate
:type surface_x:
`ArgumentType.Fixed`
:param surface_y:
surface-local y coordinate
:type surface_y:
`ArgumentType.Fixed`
"""
self._post_event(2, time, surface_x, surface_y)
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def button(self, serial: int, time: int, button: int, state: int) -> None:
"""Pointer button event
Mouse button click and release notifications.
The location of the click is given by the last motion or enter event.
The time argument is a timestamp with millisecond granularity, with an
undefined base.
The button is a button code as defined in the Linux kernel's
linux/input-event-codes.h header file, e.g. BTN_LEFT.
Any 16-bit button code value is reserved for future additions to the
kernel's event code list. All other button codes above 0xFFFF are
currently undefined but may be used in future versions of this
protocol.
:param serial:
serial number of the button event
:type serial:
`ArgumentType.Uint`
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param button:
button that produced the event
:type button:
`ArgumentType.Uint`
:param state:
physical state of the button
:type state:
`ArgumentType.Uint`
"""
self._post_event(3, serial, time, button, state)
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Fixed),
)
def axis(self, time: int, axis: int, value: float) -> None:
"""Axis event
Scroll and other axis notifications.
For scroll events (vertical and horizontal scroll axes), the value
parameter is the length of a vector along the specified axis in a
coordinate space identical to those of motion events, representing a
relative movement along the specified axis.
For devices that support movements non-parallel to axes multiple axis
events will be emitted.
When applicable, for example for touch pads, the server can choose to
emit scroll events where the motion vector is equivalent to a motion
event vector.
When applicable, a client can transform its content relative to the
scroll distance.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param axis:
axis type
:type axis:
`ArgumentType.Uint`
:param value:
length of vector in surface-local coordinate space
:type value:
`ArgumentType.Fixed`
"""
self._post_event(4, time, axis, value)
@WlPointer.event(version=5)
def frame(self) -> None:
"""End of a pointer event sequence
Indicates the end of a set of events that logically belong together. A
client is expected to accumulate the data in all events within the
frame before proceeding.
All :class:`WlPointer` events before a :func:`WlPointer.frame()` event
belong logically together. For example, in a diagonal scroll motion the
compositor will send an optional :func:`WlPointer.axis_source()` event,
two :func:`WlPointer.axis()` events (horizontal and vertical) and
finally a :func:`WlPointer.frame()` event. The client may use this
information to calculate a diagonal vector for scrolling.
When multiple :func:`WlPointer.axis()` events occur within the same
frame, the motion vector is the combined motion of all events. When a
:func:`WlPointer.axis()` and a :func:`WlPointer.axis_stop()` event
occur within the same frame, this indicates that axis movement in one
axis has stopped but continues in the other axis. When multiple
:func:`WlPointer.axis_stop()` events occur within the same frame, this
indicates that these axes stopped in the same instance.
A :func:`WlPointer.frame()` event is sent for every logical event
group, even if the group only contains a single :class:`WlPointer`
event. Specifically, a client may get a sequence: motion, frame,
button, frame, axis, frame, axis_stop, frame.
The :func:`WlPointer.enter()` and :func:`WlPointer.leave()` events are
logical events generated by the compositor and not the hardware. These
events are also grouped by a :func:`WlPointer.frame()`. When a pointer
moves from one surface to another, a compositor should group the
:func:`WlPointer.leave()` event within the same
:func:`WlPointer.frame()`. However, a client must not rely on
:func:`WlPointer.leave()` and :func:`WlPointer.enter()` being in the
same :func:`WlPointer.frame()`. Compositor-specific policies may
require the :func:`WlPointer.leave()` and :func:`WlPointer.enter()`
event being split across multiple :func:`WlPointer.frame()` groups.
"""
self._post_event(5)
@WlPointer.event(
Argument(ArgumentType.Uint),
version=5,
)
def axis_source(self, axis_source: int) -> None:
"""Axis source event
Source information for scroll and other axes.
This event does not occur on its own. It is sent before a
:func:`WlPointer.frame()` event and carries the source information for
all events within that frame.
The source specifies how this event was generated. If the source is
:func:`WlPointer.axis_source()`.finger, a :func:`WlPointer.axis_stop()`
event will be sent when the user lifts the finger off the device.
If the source is :func:`WlPointer.axis_source()`.wheel,
:func:`WlPointer.axis_source()`.wheel_tilt or
:func:`WlPointer.axis_source()`.continuous, a
:func:`WlPointer.axis_stop()` event may or may not be sent. Whether a
compositor sends an axis_stop event for these sources is hardware-
specific and implementation-dependent; clients must not rely on
receiving an axis_stop event for these scroll sources and should treat
scroll sequences from these scroll sources as unterminated by default.
This event is optional. If the source is unknown for a particular axis
event sequence, no event is sent. Only one
:func:`WlPointer.axis_source()` event is permitted per frame.
The order of :func:`WlPointer.axis_discrete()` and
:func:`WlPointer.axis_source()` is not guaranteed.
:param axis_source:
source of the axis event
:type axis_source:
`ArgumentType.Uint`
"""
self._post_event(6, axis_source)
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
version=5,
)
def axis_stop(self, time: int, axis: int) -> None:
"""Axis stop event
Stop notification for scroll and other axes.
For some :func:`WlPointer.axis_source()` types, a
:func:`WlPointer.axis_stop()` event is sent to notify a client that the
axis sequence has terminated. This enables the client to implement
kinetic scrolling. See the :func:`WlPointer.axis_source()`
documentation for information on when this event may be generated.
Any :func:`WlPointer.axis()` events with the same axis_source after
this event should be considered as the start of a new axis motion.
The timestamp is to be interpreted identical to the timestamp in the
:func:`WlPointer.axis()` event. The timestamp value may be the same as
a preceding :func:`WlPointer.axis()` event.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param axis:
the axis stopped with this event
:type axis:
`ArgumentType.Uint`
"""
self._post_event(7, time, axis)
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Int),
version=5,
)
def axis_discrete(self, axis: int, discrete: int) -> None:
"""Axis click event
Discrete step information for scroll and other axes.
This event carries the axis value of the :func:`WlPointer.axis()` event
in discrete steps (e.g. mouse wheel clicks).
This event is deprecated with :class:`WlPointer` version 8 - this event
is not sent to clients supporting version 8 or later.
This event does not occur on its own, it is coupled with a
:func:`WlPointer.axis()` event that represents this axis value on a
continuous scale. The protocol guarantees that each axis_discrete event
is always followed by exactly one axis event with the same axis number
within the same :func:`WlPointer.frame()`. Note that the protocol
allows for other events to occur between the axis_discrete and its
coupled axis event, including other axis_discrete or axis events. A
:func:`WlPointer.frame()` must not contain more than one axis_discrete
event per axis type.
This event is optional; continuous scrolling devices like two-finger
scrolling on touchpads do not have discrete steps and do not generate
this event.
The discrete value carries the directional information. e.g. a value of
-2 is two steps towards the negative direction of this axis.
The axis number is identical to the axis number in the associated axis
event.
The order of :func:`WlPointer.axis_discrete()` and
:func:`WlPointer.axis_source()` is not guaranteed.
:param axis:
axis type
:type axis:
`ArgumentType.Uint`
:param discrete:
number of steps
:type discrete:
`ArgumentType.Int`
"""
self._post_event(8, axis, discrete)
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Int),
version=8,
)
def axis_value120(self, axis: int, value120: int) -> None:
"""Axis high-resolution scroll event
Discrete high-resolution scroll information.
This event carries high-resolution wheel scroll information, with each
multiple of 120 representing one logical scroll step (a wheel detent).
For example, an axis_value120 of 30 is one quarter of a logical scroll
step in the positive direction, a value120 of -240 are two logical
scroll steps in the negative direction within the same hardware event.
Clients that rely on discrete scrolling should accumulate the value120
to multiples of 120 before processing the event.
The value120 must not be zero.
This event replaces the :func:`WlPointer.axis_discrete()` event in
clients supporting :class:`WlPointer` version 8 or later.
Where a :func:`WlPointer.axis_source()` event occurs in the same
:func:`WlPointer.frame()`, the axis source applies to this event.
The order of :class:`WlPointer`.axis_value120 and
:func:`WlPointer.axis_source()` is not guaranteed.
:param axis:
axis type
:type axis:
`ArgumentType.Uint`
:param value120:
scroll distance as fraction of 120
:type value120:
`ArgumentType.Int`
"""
self._post_event(9, axis, value120)
@WlPointer.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
version=9,
)
def axis_relative_direction(self, axis: int, direction: int) -> None:
"""Axis relative physical direction event
Relative directional information of the entity causing the axis motion.
For a :func:`WlPointer.axis()` event, the
:func:`WlPointer.axis_relative_direction()` event specifies the
movement direction of the entity causing the :func:`WlPointer.axis()`
event. For example: - if a user's fingers on a touchpad move down and
this causes a :func:`WlPointer.axis()` vertical_scroll down event,
the physical direction is 'identical' - if a user's fingers on a
touchpad move down and this causes a :func:`WlPointer.axis()`
vertical_scroll up scroll up event ('natural scrolling'), the
physical direction is 'inverted'.
A client may use this information to adjust scroll motion of
components. Specifically, enabling natural scrolling causes the content
to change direction compared to traditional scrolling. Some widgets
like volume control sliders should usually match the physical direction
regardless of whether natural scrolling is active. This event enables
clients to match the scroll direction of a widget to the physical
direction.
This event does not occur on its own, it is coupled with a
:func:`WlPointer.axis()` event that represents this axis value. The
protocol guarantees that each axis_relative_direction event is always
followed by exactly one axis event with the same axis number within the
same :func:`WlPointer.frame()`. Note that the protocol allows for other
events to occur between the axis_relative_direction and its coupled
axis event.
The axis number is identical to the axis number in the associated axis
event.
The order of :func:`WlPointer.axis_relative_direction()`,
:func:`WlPointer.axis_discrete()` and :func:`WlPointer.axis_source()`
is not guaranteed.
:param axis:
axis type
:type axis:
`ArgumentType.Uint`
:param direction:
physical direction relative to axis motion
:type direction:
`ArgumentType.Uint`
"""
self._post_event(10, axis, direction)
class WlPointerGlobal(Global):
interface = WlPointer
WlPointer._gen_c()
WlPointer.proxy_class = WlPointerProxy
WlPointer.resource_class = WlPointerResource
WlPointer.global_class = WlPointerGlobal

View File

@@ -1,137 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
class WlRegion(Interface):
"""Region interface
A region object describes an area.
Region objects are used to describe the opaque and input regions of a
surface.
"""
name = "wl_region"
version = 1
class WlRegionProxy(Proxy[WlRegion]):
interface = WlRegion
@WlRegion.request()
def destroy(self) -> None:
"""Destroy region
Destroy the region. This will invalidate the object ID.
"""
self._marshal(0)
self._destroy()
@WlRegion.request(
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
)
def add(self, x: int, y: int, width: int, height: int) -> None:
"""Add rectangle to region
Add the specified rectangle to the region.
:param x:
region-local x coordinate
:type x:
`ArgumentType.Int`
:param y:
region-local y coordinate
:type y:
`ArgumentType.Int`
:param width:
rectangle width
:type width:
`ArgumentType.Int`
:param height:
rectangle height
:type height:
`ArgumentType.Int`
"""
self._marshal(1, x, y, width, height)
@WlRegion.request(
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
)
def subtract(self, x: int, y: int, width: int, height: int) -> None:
"""Subtract rectangle from region
Subtract the specified rectangle from the region.
:param x:
region-local x coordinate
:type x:
`ArgumentType.Int`
:param y:
region-local y coordinate
:type y:
`ArgumentType.Int`
:param width:
rectangle width
:type width:
`ArgumentType.Int`
:param height:
rectangle height
:type height:
`ArgumentType.Int`
"""
self._marshal(2, x, y, width, height)
class WlRegionResource(Resource):
interface = WlRegion
class WlRegionGlobal(Global):
interface = WlRegion
WlRegion._gen_c()
WlRegion.proxy_class = WlRegionProxy
WlRegion.resource_class = WlRegionResource
WlRegion.global_class = WlRegionGlobal

View File

@@ -1,167 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from typing import TypeVar
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
T = TypeVar("T", bound=Interface)
class WlRegistry(Interface):
"""Global registry object
The singleton global registry object. The server has a number of global
objects that are available to all clients. These objects typically
represent an actual object in the server (for example, an input device) or
they are singleton objects that provide extension functionality.
When a client creates a registry object, the registry object will emit a
global event for each global currently in the registry. Globals come and
go as a result of device or monitor hotplugs, reconfiguration or other
events, and the registry will send out global and global_remove events to
keep the client up to date with the changes. To mark the end of the
initial burst of events, the client can use the :func:`WlDisplay.sync()
<pywayland.protocol.wayland.WlDisplay.sync>` request immediately after
calling :func:`WlDisplay.get_registry()
<pywayland.protocol.wayland.WlDisplay.get_registry>`.
A client can bind to a global object by using the bind request. This
creates a client-side handle that lets the object emit events to the client
and lets the client invoke requests on the object.
"""
name = "wl_registry"
version = 1
class WlRegistryProxy(Proxy[WlRegistry]):
interface = WlRegistry
@WlRegistry.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.NewId),
)
def bind(self, name: int, interface: type[T], version: int) -> Proxy[T]:
"""Bind an object to the display
Binds a new, client-created object to the server using the specified
name as the identifier.
:param name:
unique numeric name of the object
:type name:
`ArgumentType.Uint`
:param interface:
Interface name
:type interface:
`string`
:param version:
Interface version
:type version:
`int`
:returns:
:class:`pywayland.client.proxy.Proxy` of specified Interface --
bounded object
"""
id = self._marshal_constructor(0, interface, name, interface.name, version)
return id
class WlRegistryResource(Resource):
interface = WlRegistry
@WlRegistry.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.String),
Argument(ArgumentType.Uint),
)
def global_(self, name: int, interface: str, version: int) -> None:
"""Announce global object
Notify the client of global objects.
The event notifies the client that a global object with the given name
is now available, and it implements the given version of the given
interface.
:param name:
numeric name of the global object
:type name:
`ArgumentType.Uint`
:param interface:
interface implemented by the object
:type interface:
`ArgumentType.String`
:param version:
interface version
:type version:
`ArgumentType.Uint`
"""
self._post_event(0, name, interface, version)
@WlRegistry.event(
Argument(ArgumentType.Uint),
)
def global_remove(self, name: int) -> None:
"""Announce removal of global object
Notify the client of removed global objects.
This event notifies the client that the global identified by name is no
longer available. If the client bound to the global using the bind
request, the client should now destroy that object.
The object remains valid and requests to the object will be ignored
until the client destroys it, to avoid races between the global going
away and a client sending a request to it.
:param name:
numeric name of the global object
:type name:
`ArgumentType.Uint`
"""
self._post_event(1, name)
class WlRegistryGlobal(Global):
interface = WlRegistry
WlRegistry._gen_c()
WlRegistry.proxy_class = WlRegistryProxy
WlRegistry.resource_class = WlRegistryResource
WlRegistry.global_class = WlRegistryGlobal

View File

@@ -1,232 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_keyboard import WlKeyboard
from .wl_pointer import WlPointer
from .wl_touch import WlTouch
class WlSeat(Interface):
"""Group of input devices
A seat is a group of keyboards, pointer and touch devices. This object is
published as a global during start up, or when such a device is hot
plugged. A seat typically has a pointer and maintains a keyboard focus and
a pointer focus.
"""
name = "wl_seat"
version = 9
class capability(enum.IntFlag):
pointer = 1
keyboard = 2
touch = 4
class error(enum.IntEnum):
missing_capability = 0
class WlSeatProxy(Proxy[WlSeat]):
interface = WlSeat
@WlSeat.request(
Argument(ArgumentType.NewId, interface=WlPointer),
)
def get_pointer(self) -> Proxy[WlPointer]:
"""Return pointer object
The ID provided will be initialized to the
:class:`~pywayland.protocol.wayland.WlPointer` interface for this seat.
This request only takes effect if the seat has the pointer capability,
or has had the pointer capability in the past. It is a protocol
violation to issue this request on a seat that has never had the
pointer capability. The missing_capability error will be sent in this
case.
:returns:
:class:`~pywayland.protocol.wayland.WlPointer` -- seat pointer
"""
id = self._marshal_constructor(0, WlPointer)
return id
@WlSeat.request(
Argument(ArgumentType.NewId, interface=WlKeyboard),
)
def get_keyboard(self) -> Proxy[WlKeyboard]:
"""Return keyboard object
The ID provided will be initialized to the
:class:`~pywayland.protocol.wayland.WlKeyboard` interface for this
seat.
This request only takes effect if the seat has the keyboard capability,
or has had the keyboard capability in the past. It is a protocol
violation to issue this request on a seat that has never had the
keyboard capability. The missing_capability error will be sent in this
case.
:returns:
:class:`~pywayland.protocol.wayland.WlKeyboard` -- seat keyboard
"""
id = self._marshal_constructor(1, WlKeyboard)
return id
@WlSeat.request(
Argument(ArgumentType.NewId, interface=WlTouch),
)
def get_touch(self) -> Proxy[WlTouch]:
"""Return touch object
The ID provided will be initialized to the
:class:`~pywayland.protocol.wayland.WlTouch` interface for this seat.
This request only takes effect if the seat has the touch capability, or
has had the touch capability in the past. It is a protocol violation to
issue this request on a seat that has never had the touch capability.
The missing_capability error will be sent in this case.
:returns:
:class:`~pywayland.protocol.wayland.WlTouch` -- seat touch
interface
"""
id = self._marshal_constructor(2, WlTouch)
return id
@WlSeat.request(version=5)
def release(self) -> None:
"""Release the seat object
Using this request a client can tell the server that it is not going to
use the seat object anymore.
"""
self._marshal(3)
self._destroy()
class WlSeatResource(Resource):
interface = WlSeat
@WlSeat.event(
Argument(ArgumentType.Uint),
)
def capabilities(self, capabilities: int) -> None:
"""Seat capabilities changed
This is emitted whenever a seat gains or loses the pointer, keyboard or
touch capabilities. The argument is a capability enum containing the
complete set of capabilities this seat has.
When the pointer capability is added, a client may create a
:class:`~pywayland.protocol.wayland.WlPointer` object using the
:func:`WlSeat.get_pointer()` request. This object will receive pointer
events until the capability is removed in the future.
When the pointer capability is removed, a client should destroy the
:class:`~pywayland.protocol.wayland.WlPointer` objects associated with
the seat where the capability was removed, using the
:func:`WlPointer.release()
<pywayland.protocol.wayland.WlPointer.release>` request. No further
pointer events will be received on these objects.
In some compositors, if a seat regains the pointer capability and a
client has a previously obtained
:class:`~pywayland.protocol.wayland.WlPointer` object of version 4 or
less, that object may start sending pointer events again. This behavior
is considered a misinterpretation of the intended behavior and must not
be relied upon by the client.
:class:`~pywayland.protocol.wayland.WlPointer` objects of version 5 or
later must not send events if created before the most recent event
notifying the client of an added pointer capability.
The above behavior also applies to
:class:`~pywayland.protocol.wayland.WlKeyboard` and
:class:`~pywayland.protocol.wayland.WlTouch` with the keyboard and
touch capabilities, respectively.
:param capabilities:
capabilities of the seat
:type capabilities:
`ArgumentType.Uint`
"""
self._post_event(0, capabilities)
@WlSeat.event(
Argument(ArgumentType.String),
version=2,
)
def name(self, name: str) -> None:
"""Unique identifier for this seat
In a multi-seat configuration the seat name can be used by clients to
help identify which physical devices the seat represents.
The seat name is a UTF-8 string with no convention defined for its
contents. Each name is unique among all :class:`WlSeat` globals. The
name is only guaranteed to be unique for the current compositor
instance.
The same seat names are used for all clients. Thus, the name can be
shared across processes to refer to a specific :class:`WlSeat` global.
The name event is sent after binding to the seat global. This event is
only sent once per seat object, and the name does not change over the
lifetime of the :class:`WlSeat` global.
Compositors may re-use the same seat name if the :class:`WlSeat` global
is destroyed and re-created later.
:param name:
seat identifier
:type name:
`ArgumentType.String`
"""
self._post_event(1, name)
class WlSeatGlobal(Global):
interface = WlSeat
WlSeat._gen_c()
WlSeat.proxy_class = WlSeatProxy
WlSeat.resource_class = WlSeatResource
WlSeat.global_class = WlSeatGlobal

View File

@@ -1,106 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_shell_surface import WlShellSurface
from .wl_surface import WlSurface
class WlShell(Interface):
"""Create desktop-style surfaces
This interface is implemented by servers that provide desktop-style user
interfaces.
It allows clients to associate a
:class:`~pywayland.protocol.wayland.WlShellSurface` with a basic surface.
Note! This protocol is deprecated and not intended for production use. For
desktop-style user interfaces, use xdg_shell. Compositors and clients
should not implement this interface.
"""
name = "wl_shell"
version = 1
class error(enum.IntEnum):
role = 0
class WlShellProxy(Proxy[WlShell]):
interface = WlShell
@WlShell.request(
Argument(ArgumentType.NewId, interface=WlShellSurface),
Argument(ArgumentType.Object, interface=WlSurface),
)
def get_shell_surface(self, surface: WlSurface) -> Proxy[WlShellSurface]:
"""Create a shell surface from a surface
Create a shell surface for an existing surface. This gives the
:class:`~pywayland.protocol.wayland.WlSurface` the role of a shell
surface. If the :class:`~pywayland.protocol.wayland.WlSurface` already
has another role, it raises a protocol error.
Only one shell surface can be associated with a given surface.
:param surface:
surface to be given the shell surface role
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface`
:returns:
:class:`~pywayland.protocol.wayland.WlShellSurface` -- shell
surface to create
"""
id = self._marshal_constructor(0, WlShellSurface, surface)
return id
class WlShellResource(Resource):
interface = WlShell
class WlShellGlobal(Global):
interface = WlShell
WlShell._gen_c()
WlShell.proxy_class = WlShellProxy
WlShell.resource_class = WlShellResource
WlShell.global_class = WlShellGlobal

View File

@@ -1,463 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_output import WlOutput
from .wl_seat import WlSeat
from .wl_surface import WlSurface
class WlShellSurface(Interface):
"""Desktop-style metadata interface
An interface that may be implemented by a
:class:`~pywayland.protocol.wayland.WlSurface`, for implementations that
provide a desktop-style user interface.
It provides requests to treat surfaces like toplevel, fullscreen or popup
windows, move, resize or maximize them, associate metadata like title and
class, etc.
On the server side the object is automatically destroyed when the related
:class:`~pywayland.protocol.wayland.WlSurface` is destroyed. On the client
side, wl_shell_surface_destroy() must be called before destroying the
:class:`~pywayland.protocol.wayland.WlSurface` object.
"""
name = "wl_shell_surface"
version = 1
class resize(enum.IntFlag):
none = 0
top = 1
bottom = 2
left = 4
top_left = 5
bottom_left = 6
right = 8
top_right = 9
bottom_right = 10
class transient(enum.IntFlag):
inactive = 0x1
class fullscreen_method(enum.IntEnum):
default = 0
scale = 1
driver = 2
fill = 3
class WlShellSurfaceProxy(Proxy[WlShellSurface]):
interface = WlShellSurface
@WlShellSurface.request(
Argument(ArgumentType.Uint),
)
def pong(self, serial: int) -> None:
"""Respond to a ping event
A client must respond to a ping event with a pong request or the client
may be deemed unresponsive.
:param serial:
serial number of the ping event
:type serial:
`ArgumentType.Uint`
"""
self._marshal(0, serial)
@WlShellSurface.request(
Argument(ArgumentType.Object, interface=WlSeat),
Argument(ArgumentType.Uint),
)
def move(self, seat: WlSeat, serial: int) -> None:
"""Start an interactive move
Start a pointer-driven move of the surface.
This request must be used in response to a button press event. The
server may ignore move requests depending on the state of the surface
(e.g. fullscreen or maximized).
:param seat:
seat whose pointer is used
:type seat:
:class:`~pywayland.protocol.wayland.WlSeat`
:param serial:
serial number of the implicit grab on the pointer
:type serial:
`ArgumentType.Uint`
"""
self._marshal(1, seat, serial)
@WlShellSurface.request(
Argument(ArgumentType.Object, interface=WlSeat),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
)
def resize(self, seat: WlSeat, serial: int, edges: int) -> None:
"""Start an interactive resize
Start a pointer-driven resizing of the surface.
This request must be used in response to a button press event. The
server may ignore resize requests depending on the state of the surface
(e.g. fullscreen or maximized).
:param seat:
seat whose pointer is used
:type seat:
:class:`~pywayland.protocol.wayland.WlSeat`
:param serial:
serial number of the implicit grab on the pointer
:type serial:
`ArgumentType.Uint`
:param edges:
which edge or corner is being dragged
:type edges:
`ArgumentType.Uint`
"""
self._marshal(2, seat, serial, edges)
@WlShellSurface.request()
def set_toplevel(self) -> None:
"""Make the surface a toplevel surface
Map the surface as a toplevel surface.
A toplevel surface is not fullscreen, maximized or transient.
"""
self._marshal(3)
@WlShellSurface.request(
Argument(ArgumentType.Object, interface=WlSurface),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Uint),
)
def set_transient(self, parent: WlSurface, x: int, y: int, flags: int) -> None:
"""Make the surface a transient surface
Map the surface relative to an existing surface.
The x and y arguments specify the location of the upper left corner of
the surface relative to the upper left corner of the parent surface, in
surface-local coordinates.
The flags argument controls details of the transient behaviour.
:param parent:
parent surface
:type parent:
:class:`~pywayland.protocol.wayland.WlSurface`
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Int`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Int`
:param flags:
transient surface behavior
:type flags:
`ArgumentType.Uint`
"""
self._marshal(4, parent, x, y, flags)
@WlShellSurface.request(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlOutput, nullable=True),
)
def set_fullscreen(self, method: int, framerate: int, output: WlOutput | None) -> None:
"""Make the surface a fullscreen surface
Map the surface as a fullscreen surface.
If an output parameter is given then the surface will be made
fullscreen on that output. If the client does not specify the output
then the compositor will apply its policy - usually choosing the output
on which the surface has the biggest surface area.
The client may specify a method to resolve a size conflict between the
output size and the surface size - this is provided through the method
parameter.
The framerate parameter is used only when the method is set to
"driver", to indicate the preferred framerate. A value of 0 indicates
that the client does not care about framerate. The framerate is
specified in mHz, that is framerate of 60000 is 60Hz.
A method of "scale" or "driver" implies a scaling operation of the
surface, either via a direct scaling operation or a change of the
output mode. This will override any kind of output scaling, so that
mapping a surface with a buffer size equal to the mode can fill the
screen independent of buffer_scale.
A method of "fill" means we don't scale up the buffer, however any
output scale is applied. This means that you may run into an edge case
where the application maps a buffer with the same size of the output
mode but buffer_scale 1 (thus making a surface larger than the output).
In this case it is allowed to downscale the results to fit the screen.
The compositor must reply to this request with a configure event with
the dimensions for the output on which the surface will be made
fullscreen.
:param method:
method for resolving size conflict
:type method:
`ArgumentType.Uint`
:param framerate:
framerate in mHz
:type framerate:
`ArgumentType.Uint`
:param output:
output on which the surface is to be fullscreen
:type output:
:class:`~pywayland.protocol.wayland.WlOutput` or `None`
"""
self._marshal(5, method, framerate, output)
@WlShellSurface.request(
Argument(ArgumentType.Object, interface=WlSeat),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlSurface),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Uint),
)
def set_popup(self, seat: WlSeat, serial: int, parent: WlSurface, x: int, y: int, flags: int) -> None:
"""Make the surface a popup surface
Map the surface as a popup.
A popup surface is a transient surface with an added pointer grab.
An existing implicit grab will be changed to owner-events mode, and the
popup grab will continue after the implicit grab ends (i.e. releasing
the mouse button does not cause the popup to be unmapped).
The popup grab continues until the window is destroyed or a mouse
button is pressed in any other client's window. A click in any of the
client's surfaces is reported as normal, however, clicks in other
clients' surfaces will be discarded and trigger the callback.
The x and y arguments specify the location of the upper left corner of
the surface relative to the upper left corner of the parent surface, in
surface-local coordinates.
:param seat:
seat whose pointer is used
:type seat:
:class:`~pywayland.protocol.wayland.WlSeat`
:param serial:
serial number of the implicit grab on the pointer
:type serial:
`ArgumentType.Uint`
:param parent:
parent surface
:type parent:
:class:`~pywayland.protocol.wayland.WlSurface`
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Int`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Int`
:param flags:
transient surface behavior
:type flags:
`ArgumentType.Uint`
"""
self._marshal(6, seat, serial, parent, x, y, flags)
@WlShellSurface.request(
Argument(ArgumentType.Object, interface=WlOutput, nullable=True),
)
def set_maximized(self, output: WlOutput | None) -> None:
"""Make the surface a maximized surface
Map the surface as a maximized surface.
If an output parameter is given then the surface will be maximized on
that output. If the client does not specify the output then the
compositor will apply its policy - usually choosing the output on which
the surface has the biggest surface area.
The compositor will reply with a configure event telling the expected
new surface size. The operation is completed on the next buffer attach
to this surface.
A maximized surface typically fills the entire output it is bound to,
except for desktop elements such as panels. This is the main difference
between a maximized shell surface and a fullscreen shell surface.
The details depend on the compositor implementation.
:param output:
output on which the surface is to be maximized
:type output:
:class:`~pywayland.protocol.wayland.WlOutput` or `None`
"""
self._marshal(7, output)
@WlShellSurface.request(
Argument(ArgumentType.String),
)
def set_title(self, title: str) -> None:
"""Set surface title
Set a short title for the surface.
This string may be used to identify the surface in a task bar, window
list, or other user interface elements provided by the compositor.
The string must be encoded in UTF-8.
:param title:
surface title
:type title:
`ArgumentType.String`
"""
self._marshal(8, title)
@WlShellSurface.request(
Argument(ArgumentType.String),
)
def set_class(self, class_: str) -> None:
"""Set surface class
Set a class for the surface.
The surface class identifies the general class of applications to which
the surface belongs. A common convention is to use the file name (or
the full path if it is a non-standard location) of the application's
.desktop file as the class.
:param class_:
surface class
:type class_:
`ArgumentType.String`
"""
self._marshal(9, class_)
class WlShellSurfaceResource(Resource):
interface = WlShellSurface
@WlShellSurface.event(
Argument(ArgumentType.Uint),
)
def ping(self, serial: int) -> None:
"""Ping client
Ping a client to check if it is receiving events and sending requests.
A client is expected to reply with a pong request.
:param serial:
serial number of the ping
:type serial:
`ArgumentType.Uint`
"""
self._post_event(0, serial)
@WlShellSurface.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
)
def configure(self, edges: int, width: int, height: int) -> None:
"""Suggest resize
The configure event asks the client to resize its surface.
The size is a hint, in the sense that the client is free to ignore it
if it doesn't resize, pick a smaller size (to satisfy aspect ratio or
resize in steps of NxM pixels).
The edges parameter provides a hint about how the surface was resized.
The client may use this information to decide how to adjust its content
to the new size (e.g. a scrolling area might adjust its content
position to leave the viewable content unmoved).
The client is free to dismiss all but the last configure event it
received.
The width and height arguments specify the size of the window in
surface-local coordinates.
:param edges:
how the surface was resized
:type edges:
`ArgumentType.Uint`
:param width:
new width of the surface
:type width:
`ArgumentType.Int`
:param height:
new height of the surface
:type height:
`ArgumentType.Int`
"""
self._post_event(1, edges, width, height)
@WlShellSurface.event()
def popup_done(self) -> None:
"""Popup interaction is done
The popup_done event is sent out when a popup grab is broken, that is,
when the user clicks a surface that doesn't belong to the client owning
the popup surface.
"""
self._post_event(2)
class WlShellSurfaceGlobal(Global):
interface = WlShellSurface
WlShellSurface._gen_c()
WlShellSurface.proxy_class = WlShellSurfaceProxy
WlShellSurface.resource_class = WlShellSurfaceResource
WlShellSurface.global_class = WlShellSurfaceGlobal

View File

@@ -1,235 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_shm_pool import WlShmPool
class WlShm(Interface):
"""Shared memory support
A singleton global object that provides support for shared memory.
Clients can create :class:`~pywayland.protocol.wayland.WlShmPool` objects
using the create_pool request.
On binding the :class:`WlShm` object one or more format events are emitted
to inform clients about the valid pixel formats that can be used for
buffers.
"""
name = "wl_shm"
version = 1
class error(enum.IntEnum):
invalid_format = 0
invalid_stride = 1
invalid_fd = 2
class format(enum.IntEnum):
argb8888 = 0
xrgb8888 = 1
c8 = 0x20203843
rgb332 = 0x38424752
bgr233 = 0x38524742
xrgb4444 = 0x32315258
xbgr4444 = 0x32314258
rgbx4444 = 0x32315852
bgrx4444 = 0x32315842
argb4444 = 0x32315241
abgr4444 = 0x32314241
rgba4444 = 0x32314152
bgra4444 = 0x32314142
xrgb1555 = 0x35315258
xbgr1555 = 0x35314258
rgbx5551 = 0x35315852
bgrx5551 = 0x35315842
argb1555 = 0x35315241
abgr1555 = 0x35314241
rgba5551 = 0x35314152
bgra5551 = 0x35314142
rgb565 = 0x36314752
bgr565 = 0x36314742
rgb888 = 0x34324752
bgr888 = 0x34324742
xbgr8888 = 0x34324258
rgbx8888 = 0x34325852
bgrx8888 = 0x34325842
abgr8888 = 0x34324241
rgba8888 = 0x34324152
bgra8888 = 0x34324142
xrgb2101010 = 0x30335258
xbgr2101010 = 0x30334258
rgbx1010102 = 0x30335852
bgrx1010102 = 0x30335842
argb2101010 = 0x30335241
abgr2101010 = 0x30334241
rgba1010102 = 0x30334152
bgra1010102 = 0x30334142
yuyv = 0x56595559
yvyu = 0x55595659
uyvy = 0x59565955
vyuy = 0x59555956
ayuv = 0x56555941
nv12 = 0x3231564E
nv21 = 0x3132564E
nv16 = 0x3631564E
nv61 = 0x3136564E
yuv410 = 0x39565559
yvu410 = 0x39555659
yuv411 = 0x31315559
yvu411 = 0x31315659
yuv420 = 0x32315559
yvu420 = 0x32315659
yuv422 = 0x36315559
yvu422 = 0x36315659
yuv444 = 0x34325559
yvu444 = 0x34325659
r8 = 0x20203852
r16 = 0x20363152
rg88 = 0x38384752
gr88 = 0x38385247
rg1616 = 0x32334752
gr1616 = 0x32335247
xrgb16161616f = 0x48345258
xbgr16161616f = 0x48344258
argb16161616f = 0x48345241
abgr16161616f = 0x48344241
xyuv8888 = 0x56555958
vuy888 = 0x34325556
vuy101010 = 0x30335556
y210 = 0x30313259
y212 = 0x32313259
y216 = 0x36313259
y410 = 0x30313459
y412 = 0x32313459
y416 = 0x36313459
xvyu2101010 = 0x30335658
xvyu12_16161616 = 0x36335658
xvyu16161616 = 0x38345658
y0l0 = 0x304C3059
x0l0 = 0x304C3058
y0l2 = 0x324C3059
x0l2 = 0x324C3058
yuv420_8bit = 0x38305559
yuv420_10bit = 0x30315559
xrgb8888_a8 = 0x38415258
xbgr8888_a8 = 0x38414258
rgbx8888_a8 = 0x38415852
bgrx8888_a8 = 0x38415842
rgb888_a8 = 0x38413852
bgr888_a8 = 0x38413842
rgb565_a8 = 0x38413552
bgr565_a8 = 0x38413542
nv24 = 0x3432564E
nv42 = 0x3234564E
p210 = 0x30313250
p010 = 0x30313050
p012 = 0x32313050
p016 = 0x36313050
axbxgxrx106106106106 = 0x30314241
nv15 = 0x3531564E
q410 = 0x30313451
q401 = 0x31303451
xrgb16161616 = 0x38345258
xbgr16161616 = 0x38344258
argb16161616 = 0x38345241
abgr16161616 = 0x38344241
class WlShmProxy(Proxy[WlShm]):
interface = WlShm
@WlShm.request(
Argument(ArgumentType.NewId, interface=WlShmPool),
Argument(ArgumentType.FileDescriptor),
Argument(ArgumentType.Int),
)
def create_pool(self, fd: int, size: int) -> Proxy[WlShmPool]:
"""Create a shm pool
Create a new :class:`~pywayland.protocol.wayland.WlShmPool` object.
The pool can be used to create shared memory based buffer objects. The
server will mmap size bytes of the passed file descriptor, to use as
backing memory for the pool.
:param fd:
file descriptor for the pool
:type fd:
`ArgumentType.FileDescriptor`
:param size:
pool size, in bytes
:type size:
`ArgumentType.Int`
:returns:
:class:`~pywayland.protocol.wayland.WlShmPool` -- pool to create
"""
id = self._marshal_constructor(0, WlShmPool, fd, size)
return id
class WlShmResource(Resource):
interface = WlShm
@WlShm.event(
Argument(ArgumentType.Uint),
)
def format(self, format: int) -> None:
"""Pixel format description
Informs the client about a valid pixel format that can be used for
buffers. Known formats include argb8888 and xrgb8888.
:param format:
buffer pixel format
:type format:
`ArgumentType.Uint`
"""
self._post_event(0, format)
class WlShmGlobal(Global):
interface = WlShm
WlShm._gen_c()
WlShm.proxy_class = WlShmProxy
WlShm.resource_class = WlShmResource
WlShm.global_class = WlShmGlobal

View File

@@ -1,159 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_buffer import WlBuffer
class WlShmPool(Interface):
"""A shared memory pool
The :class:`WlShmPool` object encapsulates a piece of memory shared between
the compositor and client. Through the :class:`WlShmPool` object, the
client can allocate shared memory
:class:`~pywayland.protocol.wayland.WlBuffer` objects. All objects created
through the same pool share the same underlying mapped memory. Reusing the
mapped memory avoids the setup/teardown overhead and is useful when
interactively resizing a surface or for many small buffers.
"""
name = "wl_shm_pool"
version = 1
class WlShmPoolProxy(Proxy[WlShmPool]):
interface = WlShmPool
@WlShmPool.request(
Argument(ArgumentType.NewId, interface=WlBuffer),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Uint),
)
def create_buffer(self, offset: int, width: int, height: int, stride: int, format: int) -> Proxy[WlBuffer]:
"""Create a buffer from the pool
Create a :class:`~pywayland.protocol.wayland.WlBuffer` object from the
pool.
The buffer is created offset bytes into the pool and has width and
height as specified. The stride argument specifies the number of bytes
from the beginning of one row to the beginning of the next. The format
is the pixel format of the buffer and must be one of those advertised
through the :func:`WlShm.format()
<pywayland.protocol.wayland.WlShm.format>` event.
A buffer will keep a reference to the pool it was created from so it is
valid to destroy the pool immediately after creating a buffer from it.
:param offset:
buffer byte offset within the pool
:type offset:
`ArgumentType.Int`
:param width:
buffer width, in pixels
:type width:
`ArgumentType.Int`
:param height:
buffer height, in pixels
:type height:
`ArgumentType.Int`
:param stride:
number of bytes from the beginning of one row to the beginning of
the next row
:type stride:
`ArgumentType.Int`
:param format:
buffer pixel format
:type format:
`ArgumentType.Uint`
:returns:
:class:`~pywayland.protocol.wayland.WlBuffer` -- buffer to create
"""
id = self._marshal_constructor(0, WlBuffer, offset, width, height, stride, format)
return id
@WlShmPool.request()
def destroy(self) -> None:
"""Destroy the pool
Destroy the shared memory pool.
The mmapped memory will be released when all buffers that have been
created from this pool are gone.
"""
self._marshal(1)
self._destroy()
@WlShmPool.request(
Argument(ArgumentType.Int),
)
def resize(self, size: int) -> None:
"""Change the size of the pool mapping
This request will cause the server to remap the backing memory for the
pool from the file descriptor passed when the pool was created, but
using the new size. This request can only be used to make the pool
bigger.
This request only changes the amount of bytes that are mmapped by the
server and does not touch the file corresponding to the file descriptor
passed at creation time. It is the client's responsibility to ensure
that the file is at least as big as the new pool size.
:param size:
new size of the pool, in bytes
:type size:
`ArgumentType.Int`
"""
self._marshal(2, size)
class WlShmPoolResource(Resource):
interface = WlShmPool
class WlShmPoolGlobal(Global):
interface = WlShmPool
WlShmPool._gen_c()
WlShmPool.proxy_class = WlShmPoolProxy
WlShmPool.resource_class = WlShmPoolResource
WlShmPool.global_class = WlShmPoolGlobal

View File

@@ -1,150 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_subsurface import WlSubsurface
from .wl_surface import WlSurface
class WlSubcompositor(Interface):
"""Sub-surface compositing
The global interface exposing sub-surface compositing capabilities. A
:class:`~pywayland.protocol.wayland.WlSurface`, that has sub-surfaces
associated, is called the parent surface. Sub-surfaces can be arbitrarily
nested and create a tree of sub-surfaces.
The root surface in a tree of sub-surfaces is the main surface. The main
surface cannot be a sub-surface, because sub-surfaces must always have a
parent.
A main surface with its sub-surfaces forms a (compound) window. For window
management purposes, this set of
:class:`~pywayland.protocol.wayland.WlSurface` objects is to be considered
as a single window, and it should also behave as such.
The aim of sub-surfaces is to offload some of the compositing work within a
window from clients to the compositor. A prime example is a video player
with decorations and video in separate
:class:`~pywayland.protocol.wayland.WlSurface` objects. This should allow
the compositor to pass YUV video buffer processing to dedicated overlay
hardware when possible.
"""
name = "wl_subcompositor"
version = 1
class error(enum.IntEnum):
bad_surface = 0
bad_parent = 1
class WlSubcompositorProxy(Proxy[WlSubcompositor]):
interface = WlSubcompositor
@WlSubcompositor.request()
def destroy(self) -> None:
"""Unbind from the subcompositor interface
Informs the server that the client will not be using this protocol
object anymore. This does not affect any other objects,
:class:`~pywayland.protocol.wayland.WlSubsurface` objects included.
"""
self._marshal(0)
self._destroy()
@WlSubcompositor.request(
Argument(ArgumentType.NewId, interface=WlSubsurface),
Argument(ArgumentType.Object, interface=WlSurface),
Argument(ArgumentType.Object, interface=WlSurface),
)
def get_subsurface(self, surface: WlSurface, parent: WlSurface) -> Proxy[WlSubsurface]:
"""Give a surface the role sub-surface
Create a sub-surface interface for the given surface, and associate it
with the given parent surface. This turns a plain
:class:`~pywayland.protocol.wayland.WlSurface` into a sub-surface.
The to-be sub-surface must not already have another role, and it must
not have an existing :class:`~pywayland.protocol.wayland.WlSubsurface`
object. Otherwise the bad_surface protocol error is raised.
Adding sub-surfaces to a parent is a double-buffered operation on the
parent (see :func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>`). The effect of adding a
sub-surface becomes visible on the next time the state of the parent
surface is applied.
The parent surface must not be one of the child surface's descendants,
and the parent must be different from the child surface, otherwise the
bad_parent protocol error is raised.
This request modifies the behaviour of :func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` request on the sub-
surface, see the documentation on
:class:`~pywayland.protocol.wayland.WlSubsurface` interface.
:param surface:
the surface to be turned into a sub-surface
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface`
:param parent:
the parent surface
:type parent:
:class:`~pywayland.protocol.wayland.WlSurface`
:returns:
:class:`~pywayland.protocol.wayland.WlSubsurface` -- the new sub-
surface object ID
"""
id = self._marshal_constructor(1, WlSubsurface, surface, parent)
return id
class WlSubcompositorResource(Resource):
interface = WlSubcompositor
class WlSubcompositorGlobal(Global):
interface = WlSubcompositor
WlSubcompositor._gen_c()
WlSubcompositor.proxy_class = WlSubcompositorProxy
WlSubcompositor.resource_class = WlSubcompositorResource
WlSubcompositor.global_class = WlSubcompositorGlobal

View File

@@ -1,271 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_surface import WlSurface
class WlSubsurface(Interface):
"""Sub-surface interface to a :class:`~pywayland.protocol.wayland.WlSurface`
An additional interface to a :class:`~pywayland.protocol.wayland.WlSurface`
object, which has been made a sub-surface. A sub-surface has one parent
surface. A sub-surface's size and position are not limited to that of the
parent. Particularly, a sub-surface is not automatically clipped to its
parent's area.
A sub-surface becomes mapped, when a non-NULL
:class:`~pywayland.protocol.wayland.WlBuffer` is applied and the parent
surface is mapped. The order of which one happens first is irrelevant. A
sub-surface is hidden if the parent becomes hidden, or if a NULL
:class:`~pywayland.protocol.wayland.WlBuffer` is applied. These rules apply
recursively through the tree of surfaces.
The behaviour of a :func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` request on a sub-surface
depends on the sub-surface's mode. The possible modes are synchronized and
desynchronized, see methods :func:`WlSubsurface.set_sync()` and
:func:`WlSubsurface.set_desync()`. Synchronized mode caches the
:class:`~pywayland.protocol.wayland.WlSurface` state to be applied when the
parent's state gets applied, and desynchronized mode applies the pending
:class:`~pywayland.protocol.wayland.WlSurface` state directly. A sub-
surface is initially in the synchronized mode.
Sub-surfaces also have another kind of state, which is managed by
:class:`WlSubsurface` requests, as opposed to
:class:`~pywayland.protocol.wayland.WlSurface` requests. This state
includes the sub-surface position relative to the parent surface
(:func:`WlSubsurface.set_position()`), and the stacking order of the parent
and its sub-surfaces (:func:`WlSubsurface.place_above()` and .place_below).
This state is applied when the parent surface's
:class:`~pywayland.protocol.wayland.WlSurface` state is applied, regardless
of the sub-surface's mode. As the exception, set_sync and set_desync are
effective immediately.
The main surface can be thought to be always in desynchronized mode, since
it does not have a parent in the sub-surfaces sense.
Even if a sub-surface is in desynchronized mode, it will behave as in
synchronized mode, if its parent surface behaves as in synchronized mode.
This rule is applied recursively throughout the tree of surfaces. This
means, that one can set a sub-surface into synchronized mode, and then
assume that all its child and grand-child sub-surfaces are synchronized,
too, without explicitly setting them.
Destroying a sub-surface takes effect immediately. If you need to
synchronize the removal of a sub-surface to the parent surface update,
unmap the sub-surface first by attaching a NULL
:class:`~pywayland.protocol.wayland.WlBuffer`, update parent, and then
destroy the sub-surface.
If the parent :class:`~pywayland.protocol.wayland.WlSurface` object is
destroyed, the sub-surface is unmapped.
"""
name = "wl_subsurface"
version = 1
class error(enum.IntEnum):
bad_surface = 0
class WlSubsurfaceProxy(Proxy[WlSubsurface]):
interface = WlSubsurface
@WlSubsurface.request()
def destroy(self) -> None:
"""Remove sub-surface interface
The sub-surface interface is removed from the
:class:`~pywayland.protocol.wayland.WlSurface` object that was turned
into a sub-surface with a :func:`WlSubcompositor.get_subsurface()
<pywayland.protocol.wayland.WlSubcompositor.get_subsurface>` request.
The wl_surface's association to the parent is deleted. The
:class:`~pywayland.protocol.wayland.WlSurface` is unmapped immediately.
"""
self._marshal(0)
self._destroy()
@WlSubsurface.request(
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
)
def set_position(self, x: int, y: int) -> None:
"""Reposition the sub-surface
This schedules a sub-surface position change. The sub-surface will be
moved so that its origin (top left corner pixel) will be at the
location x, y of the parent surface coordinate system. The coordinates
are not restricted to the parent surface area. Negative values are
allowed.
The scheduled coordinates will take effect whenever the state of the
parent surface is applied. When this happens depends on whether the
parent surface is in synchronized mode or not. See
:func:`WlSubsurface.set_sync()` and :func:`WlSubsurface.set_desync()`
for details.
If more than one set_position request is invoked by the client before
the commit of the parent surface, the position of a new request always
replaces the scheduled position from any previous request.
The initial position is 0, 0.
:param x:
x coordinate in the parent surface
:type x:
`ArgumentType.Int`
:param y:
y coordinate in the parent surface
:type y:
`ArgumentType.Int`
"""
self._marshal(1, x, y)
@WlSubsurface.request(
Argument(ArgumentType.Object, interface=WlSurface),
)
def place_above(self, sibling: WlSurface) -> None:
"""Restack the sub-surface
This sub-surface is taken from the stack, and put back just above the
reference surface, changing the z-order of the sub-surfaces. The
reference surface must be one of the sibling surfaces, or the parent
surface. Using any other surface, including this sub-surface, will
cause a protocol error.
The z-order is double-buffered. Requests are handled in order and
applied immediately to a pending state. The final pending state is
copied to the active state the next time the state of the parent
surface is applied. When this happens depends on whether the parent
surface is in synchronized mode or not. See
:func:`WlSubsurface.set_sync()` and :func:`WlSubsurface.set_desync()`
for details.
A new sub-surface is initially added as the top-most in the stack of
its siblings and parent.
:param sibling:
the reference surface
:type sibling:
:class:`~pywayland.protocol.wayland.WlSurface`
"""
self._marshal(2, sibling)
@WlSubsurface.request(
Argument(ArgumentType.Object, interface=WlSurface),
)
def place_below(self, sibling: WlSurface) -> None:
"""Restack the sub-surface
The sub-surface is placed just below the reference surface. See
:func:`WlSubsurface.place_above()`.
:param sibling:
the reference surface
:type sibling:
:class:`~pywayland.protocol.wayland.WlSurface`
"""
self._marshal(3, sibling)
@WlSubsurface.request()
def set_sync(self) -> None:
"""Set sub-surface to synchronized mode
Change the commit behaviour of the sub-surface to synchronized mode,
also described as the parent dependent mode.
In synchronized mode, :func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` on a sub-surface will
accumulate the committed state in a cache, but the state will not be
applied and hence will not change the compositor output. The cached
state is applied to the sub-surface immediately after the parent
surface's state is applied. This ensures atomic updates of the parent
and all its synchronized sub-surfaces. Applying the cached state will
invalidate the cache, so further parent surface commits do not
(re-)apply old state.
See :class:`WlSubsurface` for the recursive effect of this mode.
"""
self._marshal(4)
@WlSubsurface.request()
def set_desync(self) -> None:
"""Set sub-surface to desynchronized mode
Change the commit behaviour of the sub-surface to desynchronized mode,
also described as independent or freely running mode.
In desynchronized mode, :func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` on a sub-surface will
apply the pending state directly, without caching, as happens normally
with a :class:`~pywayland.protocol.wayland.WlSurface`. Calling
:func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` on the parent surface
has no effect on the sub-surface's
:class:`~pywayland.protocol.wayland.WlSurface` state. This mode allows
a sub-surface to be updated on its own.
If cached state exists when :func:`WlSurface.commit()
<pywayland.protocol.wayland.WlSurface.commit>` is called in
desynchronized mode, the pending state is added to the cached state,
and applied as a whole. This invalidates the cache.
Note: even if a sub-surface is set to desynchronized, a parent sub-
surface may override it to behave as synchronized. For details, see
:class:`WlSubsurface`.
If a surface's parent surface behaves as desynchronized, then the
cached state is applied on set_desync.
"""
self._marshal(5)
class WlSubsurfaceResource(Resource):
interface = WlSubsurface
class WlSubsurfaceGlobal(Global):
interface = WlSubsurface
WlSubsurface._gen_c()
WlSubsurface.proxy_class = WlSubsurfaceProxy
WlSubsurface.resource_class = WlSubsurfaceResource
WlSubsurface.global_class = WlSubsurfaceGlobal

View File

@@ -1,704 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import enum
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_buffer import WlBuffer
from .wl_callback import WlCallback
from .wl_output import WlOutput
from .wl_region import WlRegion
class WlSurface(Interface):
"""An onscreen surface
A surface is a rectangular area that may be displayed on zero or more
outputs, and shown any number of times at the compositor's discretion. They
can present wl_buffers, receive user input, and define a local coordinate
system.
The size of a surface (and relative positions on it) is described in
surface-local coordinates, which may differ from the buffer coordinates of
the pixel content, in case a buffer_transform or a buffer_scale is used.
A surface without a "role" is fairly useless: a compositor does not know
where, when or how to present it. The role is the purpose of a
:class:`WlSurface`. Examples of roles are a cursor for a pointer (as set by
:func:`WlPointer.set_cursor()
<pywayland.protocol.wayland.WlPointer.set_cursor>`), a drag icon
(:func:`WlDataDevice.start_drag()
<pywayland.protocol.wayland.WlDataDevice.start_drag>`), a sub-surface
(:func:`WlSubcompositor.get_subsurface()
<pywayland.protocol.wayland.WlSubcompositor.get_subsurface>`), and a window
as defined by a shell protocol (e.g. :func:`WlShell.get_shell_surface()
<pywayland.protocol.wayland.WlShell.get_shell_surface>`).
A surface can have only one role at a time. Initially a :class:`WlSurface`
does not have a role. Once a :class:`WlSurface` is given a role, it is set
permanently for the whole lifetime of the :class:`WlSurface` object. Giving
the current role again is allowed, unless explicitly forbidden by the
relevant interface specification.
Surface roles are given by requests in other interfaces such as
:func:`WlPointer.set_cursor()
<pywayland.protocol.wayland.WlPointer.set_cursor>`. The request should
explicitly mention that this request gives a role to a :class:`WlSurface`.
Often, this request also creates a new protocol object that represents the
role and adds additional functionality to :class:`WlSurface`. When a client
wants to destroy a :class:`WlSurface`, they must destroy this role object
before the :class:`WlSurface`, otherwise a defunct_role_object error is
sent.
Destroying the role object does not remove the role from the
:class:`WlSurface`, but it may stop the :class:`WlSurface` from "playing
the role". For instance, if a
:class:`~pywayland.protocol.wayland.WlSubsurface` object is destroyed, the
:class:`WlSurface` it was created for will be unmapped and forget its
position and z-order. It is allowed to create a
:class:`~pywayland.protocol.wayland.WlSubsurface` for the same
:class:`WlSurface` again, but it is not allowed to use the
:class:`WlSurface` as a cursor (cursor is a different role than sub-
surface, and role switching is not allowed).
"""
name = "wl_surface"
version = 6
class error(enum.IntEnum):
invalid_scale = 0
invalid_transform = 1
invalid_size = 2
invalid_offset = 3
defunct_role_object = 4
class WlSurfaceProxy(Proxy[WlSurface]):
interface = WlSurface
@WlSurface.request()
def destroy(self) -> None:
"""Delete surface
Deletes the surface and invalidates its object ID.
"""
self._marshal(0)
self._destroy()
@WlSurface.request(
Argument(ArgumentType.Object, interface=WlBuffer, nullable=True),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
)
def attach(self, buffer: WlBuffer | None, x: int, y: int) -> None:
"""Set the surface contents
Set a buffer as the content of this surface.
The new size of the surface is calculated based on the buffer size
transformed by the inverse buffer_transform and the inverse
buffer_scale. This means that at commit time the supplied buffer size
must be an integer multiple of the buffer_scale. If that's not the
case, an invalid_size error is sent.
The x and y arguments specify the location of the new pending buffer's
upper left corner, relative to the current buffer's upper left corner,
in surface-local coordinates. In other words, the x and y, combined
with the new surface size define in which directions the surface's size
changes. Setting anything other than 0 as x and y arguments is
discouraged, and should instead be replaced with using the separate
:func:`WlSurface.offset()` request.
When the bound :class:`WlSurface` version is 5 or higher, passing any
non-zero x or y is a protocol violation, and will result in an
'invalid_offset' error being raised. The x and y arguments are ignored
and do not change the pending state. To achieve equivalent semantics,
use :func:`WlSurface.offset()`.
Surface contents are double-buffered state, see
:func:`WlSurface.commit()`.
The initial surface contents are void; there is no content.
:func:`WlSurface.attach()` assigns the given
:class:`~pywayland.protocol.wayland.WlBuffer` as the pending
:class:`~pywayland.protocol.wayland.WlBuffer`.
:func:`WlSurface.commit()` makes the pending
:class:`~pywayland.protocol.wayland.WlBuffer` the new surface contents,
and the size of the surface becomes the size calculated from the
:class:`~pywayland.protocol.wayland.WlBuffer`, as described above.
After commit, there is no pending buffer until the next attach.
Committing a pending :class:`~pywayland.protocol.wayland.WlBuffer`
allows the compositor to read the pixels in the
:class:`~pywayland.protocol.wayland.WlBuffer`. The compositor may
access the pixels at any time after the :func:`WlSurface.commit()`
request. When the compositor will not access the pixels anymore, it
will send the :func:`WlBuffer.release()
<pywayland.protocol.wayland.WlBuffer.release>` event. Only after
receiving :func:`WlBuffer.release()
<pywayland.protocol.wayland.WlBuffer.release>`, the client may reuse
the :class:`~pywayland.protocol.wayland.WlBuffer`. A
:class:`~pywayland.protocol.wayland.WlBuffer` that has been attached
and then replaced by another attach instead of committed will not
receive a release event, and is not used by the compositor.
If a pending :class:`~pywayland.protocol.wayland.WlBuffer` has been
committed to more than one :class:`WlSurface`, the delivery of
:func:`WlBuffer.release()
<pywayland.protocol.wayland.WlBuffer.release>` events becomes
undefined. A well behaved client should not rely on
:func:`WlBuffer.release()
<pywayland.protocol.wayland.WlBuffer.release>` events in this case.
Alternatively, a client could create multiple
:class:`~pywayland.protocol.wayland.WlBuffer` objects from the same
backing storage or use wp_linux_buffer_release.
Destroying the :class:`~pywayland.protocol.wayland.WlBuffer` after
:func:`WlBuffer.release()
<pywayland.protocol.wayland.WlBuffer.release>` does not change the
surface contents. Destroying the
:class:`~pywayland.protocol.wayland.WlBuffer` before
:func:`WlBuffer.release()
<pywayland.protocol.wayland.WlBuffer.release>` is allowed as long as
the underlying buffer storage isn't re-used (this can happen e.g. on
client process termination). However, if the client destroys the
:class:`~pywayland.protocol.wayland.WlBuffer` before receiving the
:func:`WlBuffer.release()
<pywayland.protocol.wayland.WlBuffer.release>` event and mutates the
underlying buffer storage, the surface contents become undefined
immediately.
If :func:`WlSurface.attach()` is sent with a NULL
:class:`~pywayland.protocol.wayland.WlBuffer`, the following
:func:`WlSurface.commit()` will remove the surface content.
:param buffer:
buffer of surface contents
:type buffer:
:class:`~pywayland.protocol.wayland.WlBuffer` or `None`
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Int`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Int`
"""
self._marshal(1, buffer, x, y)
@WlSurface.request(
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
)
def damage(self, x: int, y: int, width: int, height: int) -> None:
"""Mark part of the surface damaged
This request is used to describe the regions where the pending buffer
is different from the current surface contents, and where the surface
therefore needs to be repainted. The compositor ignores the parts of
the damage that fall outside of the surface.
Damage is double-buffered state, see :func:`WlSurface.commit()`.
The damage rectangle is specified in surface-local coordinates, where x
and y specify the upper left corner of the damage rectangle.
The initial value for pending damage is empty: no damage.
:func:`WlSurface.damage()` adds pending damage: the new pending damage
is the union of old pending damage and the given rectangle.
:func:`WlSurface.commit()` assigns pending damage as the current
damage, and clears pending damage. The server will clear the current
damage as it repaints the surface.
Note! New clients should not use this request. Instead damage can be
posted with :func:`WlSurface.damage_buffer()` which uses buffer
coordinates instead of surface coordinates.
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Int`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Int`
:param width:
width of damage rectangle
:type width:
`ArgumentType.Int`
:param height:
height of damage rectangle
:type height:
`ArgumentType.Int`
"""
self._marshal(2, x, y, width, height)
@WlSurface.request(
Argument(ArgumentType.NewId, interface=WlCallback),
)
def frame(self) -> Proxy[WlCallback]:
"""Request a frame throttling hint
Request a notification when it is a good time to start drawing a new
frame, by creating a frame callback. This is useful for throttling
redrawing operations, and driving animations.
When a client is animating on a :class:`WlSurface`, it can use the
'frame' request to get notified when it is a good time to draw and
commit the next frame of animation. If the client commits an update
earlier than that, it is likely that some updates will not make it to
the display, and the client is wasting resources by drawing too often.
The frame request will take effect on the next
:func:`WlSurface.commit()`. The notification will only be posted for
one frame unless requested again. For a :class:`WlSurface`, the
notifications are posted in the order the frame requests were
committed.
The server must send the notifications so that a client will not send
excessive updates, while still allowing the highest possible update
rate for clients that wait for the reply before drawing again. The
server should give some time for the client to draw and commit after
sending the frame callback events to let it hit the next output
refresh.
A server should avoid signaling the frame callbacks if the surface is
not visible in any way, e.g. the surface is off-screen, or completely
obscured by other opaque surfaces.
The object returned by this request will be destroyed by the compositor
after the callback is fired and as such the client must not attempt to
use it after that point.
The callback_data passed in the callback is the current time, in
milliseconds, with an undefined base.
:returns:
:class:`~pywayland.protocol.wayland.WlCallback` -- callback object
for the frame request
"""
callback = self._marshal_constructor(3, WlCallback)
return callback
@WlSurface.request(
Argument(ArgumentType.Object, interface=WlRegion, nullable=True),
)
def set_opaque_region(self, region: WlRegion | None) -> None:
"""Set opaque region
This request sets the region of the surface that contains opaque
content.
The opaque region is an optimization hint for the compositor that lets
it optimize the redrawing of content behind opaque regions. Setting an
opaque region is not required for correct behaviour, but marking
transparent content as opaque will result in repaint artifacts.
The opaque region is specified in surface-local coordinates.
The compositor ignores the parts of the opaque region that fall outside
of the surface.
Opaque region is double-buffered state, see :func:`WlSurface.commit()`.
:func:`WlSurface.set_opaque_region()` changes the pending opaque
region. :func:`WlSurface.commit()` copies the pending region to the
current region. Otherwise, the pending and current regions are never
changed.
The initial value for an opaque region is empty. Setting the pending
opaque region has copy semantics, and the
:class:`~pywayland.protocol.wayland.WlRegion` object can be destroyed
immediately. A NULL :class:`~pywayland.protocol.wayland.WlRegion`
causes the pending opaque region to be set to empty.
:param region:
opaque region of the surface
:type region:
:class:`~pywayland.protocol.wayland.WlRegion` or `None`
"""
self._marshal(4, region)
@WlSurface.request(
Argument(ArgumentType.Object, interface=WlRegion, nullable=True),
)
def set_input_region(self, region: WlRegion | None) -> None:
"""Set input region
This request sets the region of the surface that can receive pointer
and touch events.
Input events happening outside of this region will try the next surface
in the server surface stack. The compositor ignores the parts of the
input region that fall outside of the surface.
The input region is specified in surface-local coordinates.
Input region is double-buffered state, see :func:`WlSurface.commit()`.
:func:`WlSurface.set_input_region()` changes the pending input region.
:func:`WlSurface.commit()` copies the pending region to the current
region. Otherwise the pending and current regions are never changed,
except cursor and icon surfaces are special cases, see
:func:`WlPointer.set_cursor()
<pywayland.protocol.wayland.WlPointer.set_cursor>` and
:func:`WlDataDevice.start_drag()
<pywayland.protocol.wayland.WlDataDevice.start_drag>`.
The initial value for an input region is infinite. That means the whole
surface will accept input. Setting the pending input region has copy
semantics, and the :class:`~pywayland.protocol.wayland.WlRegion` object
can be destroyed immediately. A NULL
:class:`~pywayland.protocol.wayland.WlRegion` causes the input region
to be set to infinite.
:param region:
input region of the surface
:type region:
:class:`~pywayland.protocol.wayland.WlRegion` or `None`
"""
self._marshal(5, region)
@WlSurface.request()
def commit(self) -> None:
"""Commit pending surface state
Surface state (input, opaque, and damage regions, attached buffers,
etc.) is double-buffered. Protocol requests modify the pending state,
as opposed to the current state in use by the compositor. A commit
request atomically applies all pending state, replacing the current
state. After commit, the new pending state is as documented for each
related request.
On commit, a pending :class:`~pywayland.protocol.wayland.WlBuffer` is
applied first, and all other state second. This means that all
coordinates in double-buffered state are relative to the new
:class:`~pywayland.protocol.wayland.WlBuffer` coming into use, except
for :func:`WlSurface.attach()` itself. If there is no pending
:class:`~pywayland.protocol.wayland.WlBuffer`, the coordinates are
relative to the current surface contents.
All requests that need a commit to become effective are documented to
affect double-buffered state.
Other interfaces may add further double-buffered surface state.
"""
self._marshal(6)
@WlSurface.request(
Argument(ArgumentType.Int),
version=2,
)
def set_buffer_transform(self, transform: int) -> None:
"""Sets the buffer transformation
This request sets an optional transformation on how the compositor
interprets the contents of the buffer attached to the surface. The
accepted values for the transform parameter are the values for
:func:`WlOutput.transform()
<pywayland.protocol.wayland.WlOutput.transform>`.
Buffer transform is double-buffered state, see
:func:`WlSurface.commit()`.
A newly created surface has its buffer transformation set to normal.
:func:`WlSurface.set_buffer_transform()` changes the pending buffer
transformation. :func:`WlSurface.commit()` copies the pending buffer
transformation to the current one. Otherwise, the pending and current
values are never changed.
The purpose of this request is to allow clients to render content
according to the output transform, thus permitting the compositor to
use certain optimizations even if the display is rotated. Using
hardware overlays and scanning out a client buffer for fullscreen
surfaces are examples of such optimizations. Those optimizations are
highly dependent on the compositor implementation, so the use of this
request should be considered on a case-by-case basis.
Note that if the transform value includes 90 or 270 degree rotation,
the width of the buffer will become the surface height and the height
of the buffer will become the surface width.
If transform is not one of the values from the
:func:`WlOutput.transform()
<pywayland.protocol.wayland.WlOutput.transform>` enum the
invalid_transform protocol error is raised.
:param transform:
transform for interpreting buffer contents
:type transform:
`ArgumentType.Int`
"""
self._marshal(7, transform)
@WlSurface.request(
Argument(ArgumentType.Int),
version=3,
)
def set_buffer_scale(self, scale: int) -> None:
"""Sets the buffer scaling factor
This request sets an optional scaling factor on how the compositor
interprets the contents of the buffer attached to the window.
Buffer scale is double-buffered state, see :func:`WlSurface.commit()`.
A newly created surface has its buffer scale set to 1.
:func:`WlSurface.set_buffer_scale()` changes the pending buffer scale.
:func:`WlSurface.commit()` copies the pending buffer scale to the
current one. Otherwise, the pending and current values are never
changed.
The purpose of this request is to allow clients to supply higher
resolution buffer data for use on high resolution outputs. It is
intended that you pick the same buffer scale as the scale of the output
that the surface is displayed on. This means the compositor can avoid
scaling when rendering the surface on that output.
Note that if the scale is larger than 1, then you have to attach a
buffer that is larger (by a factor of scale in each dimension) than the
desired surface size.
If scale is not positive the invalid_scale protocol error is raised.
:param scale:
positive scale for interpreting buffer contents
:type scale:
`ArgumentType.Int`
"""
self._marshal(8, scale)
@WlSurface.request(
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
version=4,
)
def damage_buffer(self, x: int, y: int, width: int, height: int) -> None:
"""Mark part of the surface damaged using buffer coordinates
This request is used to describe the regions where the pending buffer
is different from the current surface contents, and where the surface
therefore needs to be repainted. The compositor ignores the parts of
the damage that fall outside of the surface.
Damage is double-buffered state, see :func:`WlSurface.commit()`.
The damage rectangle is specified in buffer coordinates, where x and y
specify the upper left corner of the damage rectangle.
The initial value for pending damage is empty: no damage.
:func:`WlSurface.damage_buffer()` adds pending damage: the new pending
damage is the union of old pending damage and the given rectangle.
:func:`WlSurface.commit()` assigns pending damage as the current
damage, and clears pending damage. The server will clear the current
damage as it repaints the surface.
This request differs from :func:`WlSurface.damage()` in only one way -
it takes damage in buffer coordinates instead of surface-local
coordinates. While this generally is more intuitive than surface
coordinates, it is especially desirable when using wp_viewport or when
a drawing library (like EGL) is unaware of buffer scale and buffer
transform.
Note: Because buffer transformation changes and damage requests may be
interleaved in the protocol stream, it is impossible to determine the
actual mapping between surface and buffer damage until
:func:`WlSurface.commit()` time. Therefore, compositors wishing to take
both kinds of damage into account will have to accumulate damage from
the two requests separately and only transform from one to the other
after receiving the :func:`WlSurface.commit()`.
:param x:
buffer-local x coordinate
:type x:
`ArgumentType.Int`
:param y:
buffer-local y coordinate
:type y:
`ArgumentType.Int`
:param width:
width of damage rectangle
:type width:
`ArgumentType.Int`
:param height:
height of damage rectangle
:type height:
`ArgumentType.Int`
"""
self._marshal(9, x, y, width, height)
@WlSurface.request(
Argument(ArgumentType.Int),
Argument(ArgumentType.Int),
version=5,
)
def offset(self, x: int, y: int) -> None:
"""Set the surface contents offset
The x and y arguments specify the location of the new pending buffer's
upper left corner, relative to the current buffer's upper left corner,
in surface-local coordinates. In other words, the x and y, combined
with the new surface size define in which directions the surface's size
changes.
Surface location offset is double-buffered state, see
:func:`WlSurface.commit()`.
This request is semantically equivalent to and the replaces the x and y
arguments in the :func:`WlSurface.attach()` request in
:class:`WlSurface` versions prior to 5. See :func:`WlSurface.attach()`
for details.
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Int`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Int`
"""
self._marshal(10, x, y)
class WlSurfaceResource(Resource):
interface = WlSurface
@WlSurface.event(
Argument(ArgumentType.Object, interface=WlOutput),
)
def enter(self, output: WlOutput) -> None:
"""Surface enters an output
This is emitted whenever a surface's creation, movement, or resizing
results in some part of it being within the scanout region of an
output.
Note that a surface may be overlapping with zero or more outputs.
:param output:
output entered by the surface
:type output:
:class:`~pywayland.protocol.wayland.WlOutput`
"""
self._post_event(0, output)
@WlSurface.event(
Argument(ArgumentType.Object, interface=WlOutput),
)
def leave(self, output: WlOutput) -> None:
"""Surface leaves an output
This is emitted whenever a surface's creation, movement, or resizing
results in it no longer having any part of it within the scanout region
of an output.
Clients should not use the number of outputs the surface is on for
frame throttling purposes. The surface might be hidden even if no leave
event has been sent, and the compositor might expect new surface
content updates even if no enter event has been sent. The frame event
should be used instead.
:param output:
output left by the surface
:type output:
:class:`~pywayland.protocol.wayland.WlOutput`
"""
self._post_event(1, output)
@WlSurface.event(
Argument(ArgumentType.Int),
version=6,
)
def preferred_buffer_scale(self, factor: int) -> None:
"""Preferred buffer scale for the surface
This event indicates the preferred buffer scale for this surface. It is
sent whenever the compositor's preference changes.
It is intended that scaling aware clients use this event to scale their
content and use :func:`WlSurface.set_buffer_scale()` to indicate the
scale they have rendered with. This allows clients to supply a higher
detail buffer.
:param factor:
preferred scaling factor
:type factor:
`ArgumentType.Int`
"""
self._post_event(2, factor)
@WlSurface.event(
Argument(ArgumentType.Uint),
version=6,
)
def preferred_buffer_transform(self, transform: int) -> None:
"""Preferred buffer transform for the surface
This event indicates the preferred buffer transform for this surface.
It is sent whenever the compositor's preference changes.
It is intended that transform aware clients use this event to apply the
transform to their content and use
:func:`WlSurface.set_buffer_transform()` to indicate the transform they
have rendered with.
:param transform:
preferred transform
:type transform:
`ArgumentType.Uint`
"""
self._post_event(3, transform)
class WlSurfaceGlobal(Global):
interface = WlSurface
WlSurface._gen_c()
WlSurface.proxy_class = WlSurfaceProxy
WlSurface.resource_class = WlSurfaceResource
WlSurface.global_class = WlSurfaceGlobal

View File

@@ -1,304 +0,0 @@
# This file has been autogenerated by the pywayland scanner
# Copyright © 2008-2011 Kristian Høgsberg
# Copyright © 2010-2011 Intel Corporation
# Copyright © 2012-2013 Collabora, Ltd.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from pywayland.protocol_core import (
Argument,
ArgumentType,
Global,
Interface,
Proxy,
Resource,
)
from .wl_surface import WlSurface
class WlTouch(Interface):
"""Touchscreen input device
The :class:`WlTouch` interface represents a touchscreen associated with a
seat.
Touch interactions can consist of one or more contacts. For each contact, a
series of events is generated, starting with a down event, followed by zero
or more motion events, and ending with an up event. Events relating to the
same contact point can be identified by the ID of the sequence.
"""
name = "wl_touch"
version = 9
class WlTouchProxy(Proxy[WlTouch]):
interface = WlTouch
@WlTouch.request(version=3)
def release(self) -> None:
"""Release the touch object
"""
self._marshal(0)
self._destroy()
class WlTouchResource(Resource):
interface = WlTouch
@WlTouch.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Object, interface=WlSurface),
Argument(ArgumentType.Int),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
)
def down(self, serial: int, time: int, surface: WlSurface, id: int, x: float, y: float) -> None:
"""Touch down event and beginning of a touch sequence
A new touch point has appeared on the surface. This touch point is
assigned a unique ID. Future events from this touch point reference
this ID. The ID ceases to be valid after a touch up event and may be
reused in the future.
:param serial:
serial number of the touch down event
:type serial:
`ArgumentType.Uint`
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param surface:
surface touched
:type surface:
:class:`~pywayland.protocol.wayland.WlSurface`
:param id:
the unique ID of this touch point
:type id:
`ArgumentType.Int`
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Fixed`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Fixed`
"""
self._post_event(0, serial, time, surface, id, x, y)
@WlTouch.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Uint),
Argument(ArgumentType.Int),
)
def up(self, serial: int, time: int, id: int) -> None:
"""End of a touch event sequence
The touch point has disappeared. No further events will be sent for
this touch point and the touch point's ID is released and may be reused
in a future touch down event.
:param serial:
serial number of the touch up event
:type serial:
`ArgumentType.Uint`
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param id:
the unique ID of this touch point
:type id:
`ArgumentType.Int`
"""
self._post_event(1, serial, time, id)
@WlTouch.event(
Argument(ArgumentType.Uint),
Argument(ArgumentType.Int),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
)
def motion(self, time: int, id: int, x: float, y: float) -> None:
"""Update of touch point coordinates
A touch point has changed coordinates.
:param time:
timestamp with millisecond granularity
:type time:
`ArgumentType.Uint`
:param id:
the unique ID of this touch point
:type id:
`ArgumentType.Int`
:param x:
surface-local x coordinate
:type x:
`ArgumentType.Fixed`
:param y:
surface-local y coordinate
:type y:
`ArgumentType.Fixed`
"""
self._post_event(2, time, id, x, y)
@WlTouch.event()
def frame(self) -> None:
"""End of touch frame event
Indicates the end of a set of events that logically belong together. A
client is expected to accumulate the data in all events within the
frame before proceeding.
A :func:`WlTouch.frame()` terminates at least one event but otherwise
no guarantee is provided about the set of events within a frame. A
client must assume that any state not updated in a frame is unchanged
from the previously known state.
"""
self._post_event(3)
@WlTouch.event()
def cancel(self) -> None:
"""Touch session cancelled
Sent if the compositor decides the touch stream is a global gesture. No
further events are sent to the clients from that particular gesture.
Touch cancellation applies to all touch points currently active on this
client's surface. The client is responsible for finalizing the touch
points, future touch points on this surface may reuse the touch point
ID.
"""
self._post_event(4)
@WlTouch.event(
Argument(ArgumentType.Int),
Argument(ArgumentType.Fixed),
Argument(ArgumentType.Fixed),
version=6,
)
def shape(self, id: int, major: float, minor: float) -> None:
"""Update shape of touch point
Sent when a touchpoint has changed its shape.
This event does not occur on its own. It is sent before a
:func:`WlTouch.frame()` event and carries the new shape information for
any previously reported, or new touch points of that frame.
Other events describing the touch point such as :func:`WlTouch.down()`,
:func:`WlTouch.motion()` or :func:`WlTouch.orientation()` may be sent
within the same :func:`WlTouch.frame()`. A client should treat these
events as a single logical touch point update. The order of
:func:`WlTouch.shape()`, :func:`WlTouch.orientation()` and
:func:`WlTouch.motion()` is not guaranteed. A :func:`WlTouch.down()`
event is guaranteed to occur before the first :func:`WlTouch.shape()`
event for this touch ID but both events may occur within the same
:func:`WlTouch.frame()`.
A touchpoint shape is approximated by an ellipse through the major and
minor axis length. The major axis length describes the longer diameter
of the ellipse, while the minor axis length describes the shorter
diameter. Major and minor are orthogonal and both are specified in
surface-local coordinates. The center of the ellipse is always at the
touchpoint location as reported by :func:`WlTouch.down()` or
:func:`WlTouch.move()`.
This event is only sent by the compositor if the touch device supports
shape reports. The client has to make reasonable assumptions about the
shape if it did not receive this event.
:param id:
the unique ID of this touch point
:type id:
`ArgumentType.Int`
:param major:
length of the major axis in surface-local coordinates
:type major:
`ArgumentType.Fixed`
:param minor:
length of the minor axis in surface-local coordinates
:type minor:
`ArgumentType.Fixed`
"""
self._post_event(5, id, major, minor)
@WlTouch.event(
Argument(ArgumentType.Int),
Argument(ArgumentType.Fixed),
version=6,
)
def orientation(self, id: int, orientation: float) -> None:
"""Update orientation of touch point
Sent when a touchpoint has changed its orientation.
This event does not occur on its own. It is sent before a
:func:`WlTouch.frame()` event and carries the new shape information for
any previously reported, or new touch points of that frame.
Other events describing the touch point such as :func:`WlTouch.down()`,
:func:`WlTouch.motion()` or :func:`WlTouch.shape()` may be sent within
the same :func:`WlTouch.frame()`. A client should treat these events as
a single logical touch point update. The order of
:func:`WlTouch.shape()`, :func:`WlTouch.orientation()` and
:func:`WlTouch.motion()` is not guaranteed. A :func:`WlTouch.down()`
event is guaranteed to occur before the first
:func:`WlTouch.orientation()` event for this touch ID but both events
may occur within the same :func:`WlTouch.frame()`.
The orientation describes the clockwise angle of a touchpoint's major
axis to the positive surface y-axis and is normalized to the -180 to
+180 degree range. The granularity of orientation depends on the touch
device, some devices only support binary rotation values between 0 and
90 degrees.
This event is only sent by the compositor if the touch device supports
orientation reports.
:param id:
the unique ID of this touch point
:type id:
`ArgumentType.Int`
:param orientation:
angle between major axis and positive surface y-axis in degrees
:type orientation:
`ArgumentType.Fixed`
"""
self._post_event(6, id, orientation)
class WlTouchGlobal(Global):
interface = WlTouch
WlTouch._gen_c()
WlTouch.proxy_class = WlTouchProxy
WlTouch.resource_class = WlTouchResource
WlTouch.global_class = WlTouchGlobal

View File

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

View File

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

View File

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

View File

@@ -1,117 +0,0 @@
import logging
from dataclasses import dataclass, field
from typing import Dict, List
from fabric.core.service import Service, Signal, Property
from pywayland.client import Display
from pywayland.protocol.wayland import WlOutput, WlSeat
from ..generated.river_status_unstable_v1 import (
ZriverStatusManagerV1,
ZriverOutputStatusV1,
ZriverSeatStatusV1,
)
logger = logging.getLogger(__name__)
@dataclass
class OutputState:
id: int
output: WlOutput
status: ZriverOutputStatusV1 = None
focused_tags: List[int] = field(default_factory=list)
view_tags: List[int] = field(default_factory=list)
class River(Service):
@Property(bool, "readable", "is-ready", default_value=False)
def ready(self) -> bool:
return self._ready
@Signal
def ready(self):
return self.notify("ready")
@Signal("event", flags="detailed")
def event(self, event: object): ...
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._ready = False
self.display = None
self.registry = None
self.outputs: Dict[int, OutputState] = {}
self.status_mgr = None
self.seat = None
self.seat_status: ZriverSeatStatusV1 = None
self.ready.emit()
def on_start(self):
print("✅ River.on_start called")
logger.info("[RiverService] Starting River service...")
self.display = Display()
self.display.connect()
self.registry = self.display.get_registry()
self.registry.dispatcher["global"] = self._on_global
self.registry.dispatcher["global_remove"] = lambda *_: None
self.display.roundtrip()
if self.seat and self.status_mgr:
self.seat_status = self.status_mgr.get_river_seat_status(self.seat)
for id, output_state in self.outputs.items():
status = self.status_mgr.get_river_output_status(output_state.output)
output_state.status = status
status.dispatcher["focused_tags"] = self._make_focused_handler(id)
status.dispatcher["view_tags"] = self._make_view_handler(id)
self.display.roundtrip()
self._ready = True
self.ready.emit()
logger.info("[RiverService] Ready. Monitoring tags.")
def on_tick(self):
# Periodic poll
self.display.roundtrip()
def _on_global(self, registry, name, interface, version):
if interface == "wl_output":
output = registry.bind(name, WlOutput, version)
self.outputs[name] = OutputState(id=name, output=output)
elif interface == "wl_seat":
self.seat = registry.bind(name, WlSeat, version)
elif interface == "zriver_status_manager_v1":
self.status_mgr = registry.bind(name, ZriverStatusManagerV1, version)
def _make_focused_handler(self, output_id):
def handler(_, bitfield):
tags = self._decode_bitfield(bitfield)
self.outputs[output_id].focused_tags = tags
logger.debug(f"[RiverService] Output {output_id} focused: {tags}")
self.emit(f"event::focused_tags::{output_id}", tags)
return handler
def _make_view_handler(self, output_id):
def handler(_, array):
tags = self._decode_array_bitfields(array)
self.outputs[output_id].view_tags = tags
logger.debug(f"[RiverService] Output {output_id} views: {tags}")
self.emit(f"event::view_tags::{output_id}", tags)
return handler
def _decode_bitfield(self, bits: int) -> List[int]:
return [i for i in range(32) if bits & (1 << i)]
def _decode_array_bitfields(self, array) -> List[int]:
tags = set()
for bits in array:
tags.update(self._decode_bitfield(bits))
return sorted(tags)

View File

@@ -1,99 +0,0 @@
from fabric.core.service import Property
from fabric.widgets.button import Button
from fabric.widgets.box import Box
from fabric.widgets.eventbox import EventBox
from fabric.utils.helpers import bulk_connect
from .service import River
from gi.repository import Gdk
_connection: River | None = None
def get_river_connection() -> River:
global _connection
if not _connection:
_connection = River()
return _connection
class RiverWorkspaceButton(Button):
@Property(int, "readable")
def id(self) -> int:
return self._id
@Property(bool, "read-write", default_value=False)
def active(self) -> bool:
return self._active
@active.setter
def active(self, value: bool):
self._active = value
(self.remove_style_class if not value else self.add_style_class)("active")
@Property(bool, "read-write", default_value=False)
def empty(self) -> bool:
return self._empty
@empty.setter
def empty(self, value: bool):
self._empty = value
(self.remove_style_class if not value else self.add_style_class)("empty")
def __init__(self, id: int, label: str = None, **kwargs):
super().__init__(label or str(id), **kwargs)
self._id = id
self._active = False
self._empty = True
class RiverWorkspaces(EventBox):
def __init__(self, output_id: int, max_tags: int = 9, **kwargs):
super().__init__(events="scroll")
self.output_id = output_id
self.max_tags = max_tags
self.service = get_river_connection()
self._box = Box(**kwargs)
self.children = self._box
self._buttons = {i: RiverWorkspaceButton(i) for i in range(max_tags)}
for btn in self._buttons.values():
btn.connect("clicked", self.on_workspace_click)
self._box.add(btn)
# hook into River signals
self.service.connect(f"event::focused_tags::{output_id}", self.on_focus_change)
self.service.connect(f"event::view_tags::{output_id}", self.on_view_change)
if self.service.ready:
self.on_ready(None)
else:
self.service.connect("event::ready", self.on_ready)
self.connect("scroll-event", self.on_scroll)
def on_ready(self, _):
print(self.service.outputs)
def on_focus_change(self, _, tags: list[int]):
print(tags)
for i, btn in self._buttons.items():
btn.active = i in tags
def on_view_change(self, _, tags: list[int]):
print(tags)
for i, btn in self._buttons.items():
btn.empty = i not in tags
def on_workspace_click(self, btn: RiverWorkspaceButton):
import subprocess
subprocess.run(["riverctl", "tag", str(btn.id)])
return
def on_scroll(self, _, event: Gdk.EventScroll):
direction = event.direction # UP or DOWN
cmd = "tag +1" if direction == Gdk.ScrollDirection.DOWN else "tag -1"
import subprocess
subprocess.run(["riverctl", *cmd.split()])

View File

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

View File

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

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

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

7
example.yaml Normal file
View File

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

57
flake.lock generated
View File

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

269
flake.nix
View File

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

97
nix/derivation.nix Normal file
View File

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

View File

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

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

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

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

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

View File

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

20
scripts/cli_launcher.py Normal file
View File

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

21
scripts/launcher.py Executable file
View File

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

171
sims/cli.py Normal file
View File

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

78
sims/config.py Normal file
View File

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

244
sims/main.py Normal file
View File

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

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

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

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

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

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

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

View File

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

View File

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

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

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

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

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

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

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

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

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

View File

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

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

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

View File

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

View File

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

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

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

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

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

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

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

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

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

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

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

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

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

View File

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

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

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

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

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

View File

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

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

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

Some files were not shown because too many files have changed in this diff Show More