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