__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 23import locale 24import typing 25from pathlib import Path 26from pywayland.client import Display, EventQueue 27from pywayland.protocol.wayland import WlRegistry, WlSeat, WlSurface, WlCompositor, WlOutput 28from pywayland.protocol.wayland.wl_output import WlOutputProxy 29from pywayland.protocol.wlr_foreign_toplevel_management_unstable_v1 import ( 30ZwlrForeignToplevelManagerV1, 31ZwlrForeignToplevelHandleV1 32) 33import panorama_panel 34 35import gi 36 37gi.require_version("Gtk", "4.0") 38gi.require_version("GdkWayland", "4.0") 39 40from gi.repository import Gtk, GLib, Gtk4LayerShell, Gio, Gdk, Pango, GObject 41 42 43module_directory = Path(__file__).resolve().parent 44 45locale.bindtextdomain("panorama-window-list", module_directory / "locale") 46_ = lambda x: locale.dgettext("panorama-window-list", x) 47 48 49import ctypes 50from cffi import FFI 51ffi = FFI() 52ffi.cdef(""" 53void * gdk_wayland_display_get_wl_display (void * display); 54void * gdk_wayland_surface_get_wl_surface (void * surface); 55void * gdk_wayland_monitor_get_wl_output (void * monitor); 56""") 57gtk = ffi.dlopen("libgtk-4.so.1") 58 59 60@Gtk.Template(filename=str(module_directory / "panorama-window-list-options.ui")) 61class WindowListOptions(Gtk.Window): 62__gtype_name__ = "WindowListOptions" 63button_width_adjustment: Gtk.Adjustment = Gtk.Template.Child() 64 65def __init__(self, **kwargs): 66super().__init__(**kwargs) 67 68self.connect("close-request", lambda *args: self.destroy()) 69 70 71def split_bytes_into_ints(array: bytes, size: int = 4) -> list[int]: 72if len(array) % size: 73raise ValueError(f"The byte string's length must be a multiple of {size}") 74 75values: list[int] = [] 76for i in range(0, len(array), size): 77values.append(int.from_bytes(array[i : i+size], byteorder=sys.byteorder)) 78 79return values 80 81 82def get_widget_rect(widget: Gtk.Widget) -> tuple[int, int, int, int]: 83width = int(widget.get_width()) 84height = int(widget.get_height()) 85 86toplevel = widget.get_root() 87if not toplevel: 88return None, None, width, height 89 90x, y = widget.translate_coordinates(toplevel, 0, 0) 91x = int(x) 92y = int(y) 93 94return x, y, width, height 95 96 97@dataclasses.dataclass 98class WindowState: 99minimised: bool 100maximised: bool 101fullscreen: bool 102focused: bool 103 104@classmethod 105def from_state_array(cls, array: bytes): 106values = split_bytes_into_ints(array) 107instance = cls(False, False, False, False) 108for value in values: 109match value: 110case 0: 111instance.maximised = True 112case 1: 113instance.minimised = True 114case 2: 115instance.focused = True 116case 3: 117instance.fullscreen = True 118 119return instance 120 121 122from gi.repository import Gtk, Gdk 123 124class WindowButtonOptions: 125def __init__(self, max_width: int): 126self.max_width = max_width 127 128class WindowButtonLayoutManager(Gtk.LayoutManager): 129def __init__(self, options: WindowButtonOptions, **kwargs): 130super().__init__(**kwargs) 131self.options = options 132 133def do_measure(self, widget, orientation, for_size): 134child = widget.get_first_child() 135if child is None: 136return 0, 0, 0, 0 137 138if orientation == Gtk.Orientation.HORIZONTAL: 139min_width, nat_width, min_height, nat_height = child.measure(Gtk.Orientation.HORIZONTAL, for_size) 140width = self.options.max_width 141return min_width, width, min_height, nat_height 142else: 143min_width, nat_width, min_height, nat_height = child.measure(Gtk.Orientation.VERTICAL, for_size) 144return min_height, nat_height, 0, 0 145 146def do_allocate(self, widget, width, height, baseline): 147child = widget.get_first_child() 148if child is None: 149return 150alloc_width = min(width, self.options.max_width) 151alloc = Gdk.Rectangle() 152alloc.x = 0 153alloc.y = 0 154alloc.width = alloc_width 155alloc.height = height 156child.allocate(alloc.width, alloc.height, baseline) 157 158 159class WindowButton(Gtk.ToggleButton): 160def __init__(self, window_id, window_title, **kwargs): 161super().__init__(**kwargs) 162 163self.window_id: ZwlrForeignToplevelHandleV1 = window_id 164self.wf_ipc_id: typing.Optional[int] = None 165self.set_has_frame(False) 166self.label = Gtk.Label() 167self.icon = Gtk.Image.new_from_icon_name("application-x-executable") 168box = Gtk.Box() 169box.append(self.icon) 170box.append(self.label) 171self.set_child(box) 172 173self.window_title = window_title 174self.window_state = WindowState(False, False, False, False) 175 176self.label.set_ellipsize(Pango.EllipsizeMode.END) 177self.set_hexpand(True) 178self.set_vexpand(True) 179 180self.drag_source = Gtk.DragSource(actions=Gdk.DragAction.MOVE) 181self.drag_source.connect("prepare", self.provide_drag_data) 182self.drag_source.connect("drag-begin", self.drag_begin) 183self.drag_source.connect("drag-cancel", self.drag_cancel) 184 185self.add_controller(self.drag_source) 186 187self.menu = Gio.Menu() 188self.minimise_item = Gio.MenuItem.new(_("_Minimise"), "button.minimise") 189self.maximise_item = Gio.MenuItem.new(_("Ma_ximise"), "button.maximise") 190self.menu.append_item(self.minimise_item) 191self.menu.append_item(self.maximise_item) 192self.menu.append(_("_Close"), "button.close") 193self.popover_menu = Gtk.PopoverMenu.new_from_model(self.menu) 194self.popover_menu.set_parent(self) 195self.popover_menu.set_flags(Gtk.PopoverMenuFlags.NESTED) 196self.popover_menu.set_has_arrow(False) 197self.popover_menu.set_halign(Gtk.Align.END) 198 199self.right_click_controller = Gtk.GestureClick(button=3) 200self.right_click_controller.connect("pressed", self.show_menu) 201self.add_controller(self.right_click_controller) 202 203self.action_group = Gio.SimpleActionGroup() 204close_action = Gio.SimpleAction.new("close") 205close_action.connect("activate", self.close_associated) 206self.action_group.insert(close_action) 207minimise_action = Gio.SimpleAction.new("minimise") 208minimise_action.connect("activate", self.minimise_associated) 209self.action_group.insert(minimise_action) 210maximise_action = Gio.SimpleAction.new("maximise") 211maximise_action.connect("activate", self.maximise_associated) 212self.action_group.insert(maximise_action) 213 214self.insert_action_group("button", self.action_group) 215 216def show_menu(self, gesture, n_presses, x, y): 217rect = Gdk.Rectangle() 218rect.x = int(x) 219rect.y = int(y) 220rect.width = 1 221rect.height = 1 222self.popover_menu.popup() 223 224def close_associated(self, action, *args): 225self.window_id.close() 226 227def minimise_associated(self, action, *args): 228if self.window_state.minimised: 229self.window_id.unset_minimized() 230else: 231self.window_id.set_minimized() 232 233def maximise_associated(self, action, *args): 234if self.window_state.maximised: 235self.window_id.unset_maximized() 236else: 237self.window_id.set_maximized() 238 239def provide_drag_data(self, source: Gtk.DragSource, x: float, y: float): 240app = self.get_root().get_application() 241app.drags[id(self)] = self 242value = GObject.Value() 243value.init(GObject.TYPE_UINT64) 244value.set_uint64(id(self)) 245return Gdk.ContentProvider.new_for_value(value) 246 247def drag_begin(self, source: Gtk.DragSource, drag: Gdk.Drag): 248paintable = Gtk.WidgetPaintable.new(self).get_current_image() 249source.set_icon(paintable, 0, 0) 250self.hide() 251 252def drag_cancel(self, source: Gtk.DragSource, drag: Gdk.Drag, reason: Gdk.DragCancelReason): 253self.show() 254return False 255 256@property 257def window_title(self): 258return self.label.get_text() 259 260@window_title.setter 261def window_title(self, value): 262self.label.set_text(value) 263 264def set_icon_from_app_id(self, app_id): 265app_ids = app_id.split() 266 267# If on Wayfire, find the IPC ID 268for app_id in app_ids: 269if app_id.startswith("wf-ipc-"): 270self.wf_ipc_id = int(app_id.removeprefix("wf-ipc-")) 271break 272 273# Try getting an icon from the correct theme 274icon_theme = Gtk.IconTheme.get_for_display(self.get_display()) 275 276for app_id in app_ids: 277if icon_theme.has_icon(app_id): 278self.icon.set_from_icon_name(app_id) 279return 280 281# If that doesn't work, try getting one from .desktop files 282for app_id in app_ids: 283try: 284desktop_file = Gio.DesktopAppInfo.new(app_id + ".desktop") 285if desktop_file: 286self.icon.set_from_gicon(desktop_file.get_icon()) 287return 288except TypeError: 289# Due to a bug, the constructor may sometimes return C NULL 290pass 291 292 293class WFWindowList(panorama_panel.Applet): 294name = _("Wayfire window list") 295description = _("Traditional window list (for Wayfire and other wlroots compositors)") 296 297def __init__(self, orientation=Gtk.Orientation.HORIZONTAL, config=None): 298super().__init__(orientation=orientation, config=config) 299if config is None: 300config = {} 301 302self.set_homogeneous(True) 303self.window_button_options = WindowButtonOptions(config.get("max_button_width", 256)) 304 305self.toplevel_buttons: dict[ZwlrForeignToplevelHandleV1, WindowButton] = {} 306self.toplevel_buttons_by_wf_id: dict[int, WindowButton] = {} 307# This button doesn't belong to any window but is used for the button group and to be 308# selected when no window is focused 309self.initial_button = Gtk.ToggleButton() 310 311self.display = None 312self.my_output = None 313self.wl_surface_ptr = None 314self.registry = None 315self.compositor = None 316self.seat = None 317 318self.context_menu = self.make_context_menu() 319panorama_panel.track_popover(self.context_menu) 320 321right_click_controller = Gtk.GestureClick() 322right_click_controller.set_button(3) 323right_click_controller.connect("pressed", self.show_context_menu) 324 325self.add_controller(right_click_controller) 326 327action_group = Gio.SimpleActionGroup() 328options_action = Gio.SimpleAction.new("options", None) 329options_action.connect("activate", self.show_options) 330action_group.add_action(options_action) 331self.insert_action_group("applet", action_group) 332# Wait for the widget to be in a layer-shell window before doing this 333self.connect("realize", lambda *args: self.get_wl_resources()) 334 335self.options_window = None 336 337# Support button reordering 338self.drop_target = Gtk.DropTarget.new(GObject.TYPE_UINT64, Gdk.DragAction.MOVE) 339self.drop_target.set_gtypes([GObject.TYPE_UINT64]) 340self.drop_target.connect("drop", self.drop_button) 341 342self.add_controller(self.drop_target) 343 344# Make a Wayfire socket for workspace handling 345try: 346import wayfire 347self.wf_socket = wayfire.WayfireSocket() 348self.wf_socket.watch() 349fd = self.wf_socket.client.fileno() 350GLib.io_add_watch(GLib.IOChannel.unix_new(fd), GLib.IO_IN, self.on_wf_event, priority=GLib.PRIORITY_HIGH) 351except: 352# Wayfire raises Exception itself, so it cannot be narrowed down 353self.wf_socket = None 354 355def on_wf_event(self, source, condition): 356if condition & GLib.IO_IN: 357try: 358message = self.wf_socket.read_next_event() 359event = message.get("event") 360match event: 361case "view-workspace-changed": 362view = message.get("view", {}) 363output = self.wf_socket.get_output(self.get_root().monitor_index + 1) 364current_workspace = output["workspace"]["x"], output["workspace"]["y"] 365if (message["to"]["x"], message["to"]["y"]) == current_workspace: 366if self.toplevel_buttons_by_wf_id[view["id"]].get_parent() is None: 367self.append(self.toplevel_buttons_by_wf_id[view["id"]]) 368else: 369if self.toplevel_buttons_by_wf_id[view["id"]].get_parent() is self: 370# Remove out-of-workspace window 371self.remove(self.toplevel_buttons_by_wf_id[view["id"]]) 372case "wset-workspace-changed": 373output_id = self.get_root().monitor_index + 1 374if message["wset-data"]["output-id"] == output_id: 375# It has changed on this monitor; refresh the window list 376self.filter_to_wf_workspace() 377 378except Exception as e: 379print("Error reading Wayfire event:", e) 380return True 381 382def drop_button(self, drop_target: Gtk.DropTarget, value: int, x: float, y: float): 383button: WindowButton = self.get_root().get_application().drags.pop(value) 384if button.get_parent() is not self: 385# Prevent dropping a button from another window list 386return False 387 388self.remove(button) 389# Find the position where to insert the applet 390# Probably we could use the assumption that buttons are homogeneous here for efficiency 391child = self.get_first_child() 392while child: 393allocation = child.get_allocation() 394child_x, child_y = self.translate_coordinates(self, 0, 0) 395if self.get_orientation() == Gtk.Orientation.HORIZONTAL: 396midpoint = child_x + allocation.width / 2 397if x < midpoint: 398button.insert_before(self, child) 399break 400elif self.get_orientation() == Gtk.Orientation.VERTICAL: 401midpoint = child_y + allocation.height / 2 402if y < midpoint: 403button.insert_before(self, child) 404break 405child = child.get_next_sibling() 406else: 407self.append(button) 408button.show() 409 410self.set_all_rectangles() 411return True 412 413def filter_to_wf_workspace(self): 414output = self.wf_socket.get_output(self.get_root().monitor_index + 1) 415for wf_id, button in self.toplevel_buttons_by_wf_id.items(): 416view = self.wf_socket.get_view(wf_id) 417mid_x = view["geometry"]["x"] + view["geometry"]["width"] / 2 418mid_y = view["geometry"]["y"] + view["geometry"]["height"] / 2 419output_width = output["geometry"]["width"] 420output_height = output["geometry"]["height"] 421if 0 <= mid_x < output_width and 0 <= mid_y < output_height: 422# It is in this workspace; keep it 423if button.get_parent() is None: 424self.append(button) 425else: 426# Remove it from this window list 427if button.get_parent() is self: 428self.remove(button) 429 430def get_wl_resources(self): 431ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p 432ctypes.pythonapi.PyCapsule_GetPointer.argtypes = (ctypes.py_object,) 433 434self.display = Display() 435wl_display_ptr = gtk.gdk_wayland_display_get_wl_display( 436ffi.cast("void *", ctypes.pythonapi.PyCapsule_GetPointer(self.get_root().get_native().get_display().__gpointer__, None))) 437self.display._ptr = wl_display_ptr 438self.event_queue = EventQueue(self.display) 439 440# Intentionally commented: the display is already connected by GTK 441# self.display.connect() 442 443my_monitor = Gtk4LayerShell.get_monitor(self.get_root()) 444 445# Iterate through monitors and get their Wayland output (wl_output) 446# This is a hack to ensure output_enter/leave is called for toplevels 447for monitor in self.get_root().get_native().get_display().get_monitors(): 448wl_output = gtk.gdk_wayland_monitor_get_wl_output(ffi.cast("void *", ctypes.pythonapi.PyCapsule_GetPointer(monitor.__gpointer__, None))) 449if wl_output: 450print("Create proxy") 451output_proxy = WlOutputProxy(wl_output, self.display) 452output_proxy.interface.registry[output_proxy._ptr] = output_proxy 453 454if monitor == my_monitor: 455self.my_output = output_proxy 456# End hack 457 458self.registry = self.display.get_registry() 459self.registry.dispatcher["global"] = self.on_global 460self.display.roundtrip() 461fd = self.display.get_fd() 462GLib.io_add_watch(fd, GLib.IO_IN, self.on_display_event) 463 464if self.wf_socket is not None: 465self.filter_to_wf_workspace() 466 467def on_display_event(self, source, condition): 468if condition & GLib.IO_IN: 469self.display.dispatch(queue=self.event_queue) 470return True 471 472def on_global(self, registry, name, interface, version): 473if interface == "zwlr_foreign_toplevel_manager_v1": 474self.print_log("Interface registered") 475self.manager = registry.bind(name, ZwlrForeignToplevelManagerV1, version) 476self.manager.dispatcher["toplevel"] = self.on_new_toplevel 477self.manager.dispatcher["finished"] = lambda *a: print("Toplevel manager finished") 478self.display.roundtrip() 479self.display.flush() 480elif interface == "wl_seat": 481self.print_log("Seat found") 482self.seat = registry.bind(name, WlSeat, version) 483elif interface == "wl_compositor": 484self.compositor = registry.bind(name, WlCompositor, version) 485self.wl_surface_ptr = gtk.gdk_wayland_surface_get_wl_surface( 486ffi.cast("void *", ctypes.pythonapi.PyCapsule_GetPointer( 487self.get_root().get_native().get_surface().__gpointer__, None))) 488 489def on_new_toplevel(self, manager: ZwlrForeignToplevelManagerV1, 490handle: ZwlrForeignToplevelHandleV1): 491handle.dispatcher["title"] = lambda h, title: self.on_title_changed(h, title) 492handle.dispatcher["app_id"] = lambda h, app_id: self.on_app_id_changed(h, app_id) 493handle.dispatcher["output_enter"] = self.on_output_entered 494handle.dispatcher["output_leave"] = self.on_output_left 495handle.dispatcher["state"] = lambda h, states: self.on_state_changed(h, states) 496handle.dispatcher["closed"] = lambda h: self.on_closed(h) 497 498def on_output_entered(self, handle, output): 499# TODO: make this configurable 500# TODO: on wayfire, append/remove buttons when the workspace changes 501if output != self.my_output: 502return 503if handle in self.toplevel_buttons: 504button = self.toplevel_buttons[handle] 505self.append(button) 506self.set_all_rectangles() 507 508def on_output_left(self, handle, output): 509if output != self.my_output: 510return 511if handle in self.toplevel_buttons: 512button = self.toplevel_buttons[handle] 513self.remove(button) 514self.set_all_rectangles() 515 516def on_title_changed(self, handle, title): 517if handle not in self.toplevel_buttons: 518button = WindowButton(handle, title) 519button.set_group(self.initial_button) 520button.set_layout_manager(WindowButtonLayoutManager(self.window_button_options)) 521button.connect("clicked", self.on_button_click) 522self.toplevel_buttons[handle] = button 523else: 524button = self.toplevel_buttons[handle] 525button.window_title = title 526 527def set_all_rectangles(self): 528child = self.get_first_child() 529while child is not None: 530if isinstance(child, WindowButton): 531surface = WlSurface() 532surface._ptr = self.wl_surface_ptr 533child.window_id.set_rectangle(surface, *get_widget_rect(child)) 534 535child = child.get_next_sibling() 536 537def on_button_click(self, button: WindowButton): 538# Set a rectangle for animation 539surface = WlSurface() 540surface._ptr = self.wl_surface_ptr 541button.window_id.set_rectangle(surface, *get_widget_rect(button)) 542if button.window_state.focused: 543# Already pressed in, so minimise the focused window 544button.window_id.set_minimized() 545else: 546button.window_id.unset_minimized() 547button.window_id.activate(self.seat) 548 549self.display.flush() 550 551def on_state_changed(self, handle, states): 552if handle in self.toplevel_buttons: 553state_info = WindowState.from_state_array(states) 554button = self.toplevel_buttons[handle] 555button.window_state = state_info 556if state_info.focused: 557button.set_active(True) 558else: 559self.initial_button.set_active(True) 560 561self.set_all_rectangles() 562 563def on_app_id_changed(self, handle, app_id): 564if handle in self.toplevel_buttons: 565button = self.toplevel_buttons[handle] 566button.set_icon_from_app_id(app_id) 567app_ids = app_id.split() 568for app_id in app_ids: 569if app_id.startswith("wf-ipc-"): 570self.toplevel_buttons_by_wf_id[int(app_id.removeprefix("wf-ipc-"))] = button 571 572def on_closed(self, handle): 573button: WindowButton = self.toplevel_buttons[handle] 574wf_id = button.wf_ipc_id 575if handle in self.toplevel_buttons: 576self.remove(self.toplevel_buttons[handle]) 577self.toplevel_buttons.pop(handle) 578if wf_id in self.toplevel_buttons_by_wf_id: 579self.toplevel_buttons_by_wf_id.pop(wf_id) 580 581self.set_all_rectangles() 582 583def make_context_menu(self): 584menu = Gio.Menu() 585menu.append(_("Window list _options"), "applet.options") 586context_menu = Gtk.PopoverMenu.new_from_model(menu) 587context_menu.set_has_arrow(False) 588context_menu.set_parent(self) 589context_menu.set_halign(Gtk.Align.START) 590context_menu.set_flags(Gtk.PopoverMenuFlags.NESTED) 591return context_menu 592 593def show_context_menu(self, gesture, n_presses, x, y): 594rect = Gdk.Rectangle() 595rect.x = int(x) 596rect.y = int(y) 597rect.width = 1 598rect.height = 1 599 600self.context_menu.set_pointing_to(rect) 601self.context_menu.popup() 602 603def show_options(self, _0=None, _1=None): 604if self.options_window is None: 605self.options_window = WindowListOptions() 606self.options_window.button_width_adjustment.set_value(self.window_button_options.max_width) 607self.options_window.button_width_adjustment.connect("value-changed", self.update_button_options) 608 609def reset_window(*args): 610self.options_window = None 611 612self.options_window.connect("close-request", reset_window) 613self.options_window.present() 614 615def update_button_options(self, adjustment): 616self.window_button_options.max_width = adjustment.get_value() 617child: Gtk.Widget = self.get_first_child() 618while child: 619child.queue_allocate() 620child.queue_resize() 621child.queue_draw() 622child = child.get_next_sibling() 623 624def get_config(self): 625return {"max_button_width": self.window_button_options.max_width} 626 627def output_changed(self): 628self.get_wl_resources() 629