By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 __init__.py

View raw Download
text/plain • 13.82 kiB
Python script, ASCII text executable
        
            
1
"""
2
Traditional window list applet for the Panorama panel, compatible
3
with wlroots-based compositors.
4
Copyright 2025, roundabout-host.com <vlad@roundabout-host.com>
5
6
This program is free software: you can redistribute it and/or modify
7
it under the terms of the GNU General Public Licence as published by
8
the Free Software Foundation, either version 3 of the Licence, or
9
(at your option) any later version.
10
11
This program is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
GNU General Public Licence for more details.
15
16
You should have received a copy of the GNU General Public Licence
17
along with this program. If not, see <https://www.gnu.org/licenses/>.
18
"""
19
20
import dataclasses
21
import os
22
import sys
23
from pathlib import Path
24
from pywayland.client import Display
25
from pywayland.protocol.wayland import WlRegistry, WlSeat, WlSurface, WlCompositor
26
from pywayland.protocol.wlr_foreign_toplevel_management_unstable_v1 import (
27
ZwlrForeignToplevelManagerV1,
28
ZwlrForeignToplevelHandleV1
29
)
30
import panorama_panel
31
32
import gi
33
34
gi.require_version("Gtk", "4.0")
35
gi.require_version("GdkWayland", "4.0")
36
37
from gi.repository import Gtk, GLib, Gtk4LayerShell, Gio, Gdk, Pango
38
39
40
import ctypes
41
from cffi import FFI
42
ffi = FFI()
43
ffi.cdef("""
44
void * gdk_wayland_display_get_wl_display (void * display);
45
void * gdk_wayland_surface_get_wl_surface (void * surface);
46
""")
47
gtk = ffi.dlopen("libgtk-4.so.1")
48
49
50
module_directory = Path(__file__).resolve().parent
51
52
53
@Gtk.Template(filename=str(module_directory / "panorama-window-list-options.ui"))
54
class WindowListOptions(Gtk.Window):
55
__gtype_name__ = "WindowListOptions"
56
button_width_adjustment: Gtk.Adjustment = Gtk.Template.Child()
57
58
def __init__(self, **kwargs):
59
super().__init__(**kwargs)
60
61
self.connect("close-request", lambda *args: self.destroy())
62
63
64
def split_bytes_into_ints(array: bytes, size: int = 4) -> list[int]:
65
if len(array) % size:
66
raise ValueError(f"The byte string's length must be a multiple of {size}")
67
68
values: list[int] = []
69
for i in range(0, len(array), size):
70
values.append(int.from_bytes(array[i : i+size], byteorder=sys.byteorder))
71
72
return values
73
74
75
def get_widget_rect(widget: Gtk.Widget) -> tuple[int, int, int, int]:
76
width = int(widget.get_width())
77
height = int(widget.get_height())
78
79
toplevel = widget.get_root()
80
if not toplevel:
81
return None, None, width, height
82
83
x, y = widget.translate_coordinates(toplevel, 0, 0)
84
x = int(x)
85
y = int(y)
86
87
return x, y, width, height
88
89
90
@dataclasses.dataclass
91
class WindowState:
92
minimised: bool
93
maximised: bool
94
fullscreen: bool
95
focused: bool
96
97
@classmethod
98
def from_state_array(cls, array: bytes):
99
values = split_bytes_into_ints(array)
100
instance = cls(False, False, False, False)
101
for value in values:
102
match value:
103
case 0:
104
instance.maximised = True
105
case 1:
106
instance.minimised = True
107
case 2:
108
instance.focused = True
109
case 3:
110
instance.fullscreen = True
111
112
return instance
113
114
115
from gi.repository import Gtk, Gdk
116
117
class WindowButtonOptions:
118
def __init__(self, max_width: int):
119
self.max_width = max_width
120
121
class WindowButtonLayoutManager(Gtk.LayoutManager):
122
def __init__(self, options: WindowButtonOptions, **kwargs):
123
super().__init__(**kwargs)
124
self.options = options
125
126
def do_measure(self, widget, orientation, for_size):
127
child = widget.get_first_child()
128
if child is None:
129
return 0, 0, 0, 0
130
131
if orientation == Gtk.Orientation.HORIZONTAL:
132
min_width, nat_width, min_height, nat_height = child.measure(Gtk.Orientation.HORIZONTAL, for_size)
133
width = min(nat_width, self.options.max_width)
134
return min_width, width, min_height, nat_height
135
else:
136
min_width, nat_width, min_height, nat_height = child.measure(Gtk.Orientation.VERTICAL, for_size)
137
return min_height, nat_height, 0, 0
138
139
def do_allocate(self, widget, width, height, baseline):
140
child = widget.get_first_child()
141
if child is None:
142
return
143
alloc_width = min(width, self.options.max_width)
144
alloc = Gdk.Rectangle()
145
alloc.x = 0
146
alloc.y = 0
147
alloc.width = alloc_width
148
alloc.height = height
149
child.allocate(alloc.width, alloc.height, baseline)
150
151
152
class WindowButton(Gtk.ToggleButton):
153
def __init__(self, window_id, window_title, **kwargs):
154
super().__init__(**kwargs)
155
156
self.window_id: ZwlrForeignToplevelHandleV1 = window_id
157
self.set_has_frame(False)
158
self.label = Gtk.Label()
159
self.icon = Gtk.Image.new_from_icon_name("application-x-executable")
160
box = Gtk.Box()
161
box.append(self.icon)
162
box.append(self.label)
163
self.set_child(box)
164
165
self.window_title = window_title
166
self.window_state = WindowState(False, False, False, False)
167
168
self.label.set_ellipsize(Pango.EllipsizeMode.END)
169
self.set_hexpand(True)
170
self.set_vexpand(True)
171
172
@property
173
def window_title(self):
174
return self.label.get_text()
175
176
@window_title.setter
177
def window_title(self, value):
178
self.label.set_text(value)
179
180
def set_icon_from_app_id(self, app_id):
181
# Try getting an icon from the correct theme
182
app_ids = app_id.split()
183
icon_theme = Gtk.IconTheme.get_for_display(self.get_display())
184
185
for app_id in app_ids:
186
if icon_theme.has_icon(app_id):
187
self.icon.set_from_icon_name(app_id)
188
return
189
190
# If that doesn't work, try getting one from .desktop files
191
for app_id in app_ids:
192
try:
193
desktop_file = Gio.DesktopAppInfo.new(app_id + ".desktop")
194
if desktop_file:
195
self.icon.set_from_gicon(desktop_file.get_icon())
196
return
197
except TypeError:
198
# Due to a bug, the constructor may sometimes return C NULL
199
pass
200
201
202
class WFWindowList(panorama_panel.Applet):
203
name = "Wayfire window list"
204
description = "Traditional window list (for Wayfire)"
205
206
def __init__(self, orientation=Gtk.Orientation.HORIZONTAL, config=None):
207
super().__init__(orientation=orientation, config=config)
208
if config is None:
209
config = {}
210
211
self.set_homogeneous(True)
212
self.window_button_options = WindowButtonOptions(240)
213
214
self.toplevel_buttons: dict[ZwlrForeignToplevelHandleV1, WindowButton] = {}
215
# This button doesn't belong to any window but is used for the button group and to be
216
# selected when no window is focused
217
self.initial_button = Gtk.ToggleButton()
218
219
self.display = None
220
self.wl_surface_ptr = None
221
self.registry = None
222
self.compositor = None
223
self.seat = None
224
225
self.context_menu = self.make_context_menu()
226
panorama_panel.track_popover(self.context_menu)
227
228
right_click_controller = Gtk.GestureClick()
229
right_click_controller.set_button(3)
230
right_click_controller.connect("pressed", self.show_context_menu)
231
232
self.add_controller(right_click_controller)
233
234
action_group = Gio.SimpleActionGroup()
235
options_action = Gio.SimpleAction.new("options", None)
236
options_action.connect("activate", self.show_options)
237
action_group.add_action(options_action)
238
self.insert_action_group("applet", action_group)
239
# Wait for the widget to be in a layer-shell window before doing this
240
self.connect("realize", lambda *args: self.get_wl_resources())
241
242
self.options_window = None
243
244
def get_wl_resources(self):
245
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
246
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = (ctypes.py_object,)
247
248
self.display = Display()
249
wl_display_ptr = gtk.gdk_wayland_display_get_wl_display(
250
ffi.cast("void *", ctypes.pythonapi.PyCapsule_GetPointer(self.get_root().get_native().get_display().__gpointer__, None)))
251
self.display._ptr = wl_display_ptr
252
253
# Intentionally commented: the display is already connected by GTK
254
# self.display.connect()
255
256
self.registry = self.display.get_registry()
257
self.registry.dispatcher["global"] = self.on_global
258
self.display.roundtrip()
259
fd = self.display.get_fd()
260
GLib.io_add_watch(fd, GLib.IO_IN, self.on_display_event)
261
262
def on_display_event(self, source, condition):
263
if condition == GLib.IO_IN:
264
self.display.dispatch(block=True)
265
return True
266
267
def on_global(self, registry, name, interface, version):
268
if interface == "zwlr_foreign_toplevel_manager_v1":
269
self.print_log("Interface registered")
270
self.manager = registry.bind(name, ZwlrForeignToplevelManagerV1, version)
271
self.manager.dispatcher["toplevel"] = self.on_new_toplevel
272
self.manager.dispatcher["finished"] = lambda *a: print("Toplevel manager finished")
273
self.display.roundtrip()
274
self.display.flush()
275
elif interface == "wl_seat":
276
self.print_log("Seat found")
277
self.seat = registry.bind(name, WlSeat, version)
278
elif interface == "wl_compositor":
279
self.compositor = registry.bind(name, WlCompositor, version)
280
self.wl_surface_ptr = gtk.gdk_wayland_surface_get_wl_surface(
281
ffi.cast("void *", ctypes.pythonapi.PyCapsule_GetPointer(
282
self.get_root().get_native().get_surface().__gpointer__, None)))
283
284
def on_new_toplevel(self, manager: ZwlrForeignToplevelManagerV1,
285
handle: ZwlrForeignToplevelHandleV1):
286
handle.dispatcher["title"] = lambda h, title: self.on_title_changed(h, title)
287
handle.dispatcher["app_id"] = lambda h, app_id: self.on_app_id_changed(h, app_id)
288
handle.dispatcher["state"] = lambda h, states: self.on_state_changed(h, states)
289
handle.dispatcher["closed"] = lambda h: self.on_closed(h)
290
291
def on_title_changed(self, handle, title):
292
if handle not in self.toplevel_buttons:
293
button = WindowButton(handle, title)
294
button.set_group(self.initial_button)
295
button.set_layout_manager(WindowButtonLayoutManager(self.window_button_options))
296
button.connect("clicked", self.on_button_click)
297
self.toplevel_buttons[handle] = button
298
self.append(button)
299
else:
300
button = self.toplevel_buttons[handle]
301
button.window_title = title
302
303
self.set_all_rectangles()
304
305
def set_all_rectangles(self):
306
for button in self.toplevel_buttons.values():
307
surface = WlSurface()
308
surface._ptr = self.wl_surface_ptr
309
button.window_id.set_rectangle(surface, *get_widget_rect(button))
310
311
def on_button_click(self, button: WindowButton):
312
# Set a rectangle for animation
313
surface = WlSurface()
314
surface._ptr = self.wl_surface_ptr
315
button.window_id.set_rectangle(surface, *get_widget_rect(button))
316
if button.window_state.focused:
317
# Already pressed in, so minimise the focused window
318
button.window_id.set_minimized()
319
else:
320
button.window_id.unset_minimized()
321
button.window_id.activate(self.seat)
322
323
self.display.flush()
324
325
def on_state_changed(self, handle, states):
326
if handle in self.toplevel_buttons:
327
state_info = WindowState.from_state_array(states)
328
button = self.toplevel_buttons[handle]
329
button.window_state = state_info
330
if state_info.focused:
331
button.set_active(True)
332
else:
333
self.initial_button.set_active(True)
334
335
self.set_all_rectangles()
336
337
def on_app_id_changed(self, handle, app_id):
338
if handle in self.toplevel_buttons:
339
button = self.toplevel_buttons[handle]
340
button.set_icon_from_app_id(app_id)
341
342
def on_closed(self, handle):
343
if handle in self.toplevel_buttons:
344
self.remove(self.toplevel_buttons[handle])
345
self.toplevel_buttons.pop(handle)
346
347
self.set_all_rectangles()
348
349
def make_context_menu(self):
350
menu = Gio.Menu()
351
menu.append("Window list _options", "applet.options")
352
context_menu = Gtk.PopoverMenu.new_from_model(menu)
353
context_menu.set_has_arrow(False)
354
context_menu.set_parent(self)
355
context_menu.set_halign(Gtk.Align.START)
356
context_menu.set_flags(Gtk.PopoverMenuFlags.NESTED)
357
return context_menu
358
359
def show_context_menu(self, gesture, n_presses, x, y):
360
rect = Gdk.Rectangle()
361
rect.x = int(x)
362
rect.y = int(y)
363
rect.width = 1
364
rect.height = 1
365
366
self.context_menu.set_pointing_to(rect)
367
self.context_menu.popup()
368
369
def show_options(self, _0=None, _1=None):
370
if self.options_window is None:
371
self.options_window = WindowListOptions()
372
self.options_window.button_width_adjustment.set_value(self.window_button_options.max_width)
373
self.options_window.button_width_adjustment.connect("value-changed", self.update_button_options)
374
375
def reset_window(*args):
376
self.options_window = None
377
378
self.options_window.connect("close-request", reset_window)
379
self.options_window.present()
380
381
def update_button_options(self, adjustment):
382
self.window_button_options.max_width = adjustment.get_value()
383
child: Gtk.Widget = self.get_first_child()
384
while child:
385
child.queue_allocate()
386
child.queue_resize()
387
child.queue_draw()
388
child = child.get_next_sibling()
389
390
def get_config(self):
391
return {}