__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 216self.middle_click_controller = Gtk.GestureClick(button=2) 217self.middle_click_controller.connect("released", self.close_associated) 218self.add_controller(self.middle_click_controller) 219 220def show_menu(self, gesture, n_presses, x, y): 221rect = Gdk.Rectangle() 222rect.x = int(x) 223rect.y = int(y) 224rect.width = 1 225rect.height = 1 226self.popover_menu.popup() 227 228def close_associated(self, *args): 229self.window_id.close() 230 231def minimise_associated(self, action, *args): 232if self.window_state.minimised: 233self.window_id.unset_minimized() 234else: 235self.window_id.set_minimized() 236 237def maximise_associated(self, action, *args): 238if self.window_state.maximised: 239self.window_id.unset_maximized() 240else: 241self.window_id.set_maximized() 242 243def provide_drag_data(self, source: Gtk.DragSource, x: float, y: float): 244app = self.get_root().get_application() 245app.drags[id(self)] = self 246value = GObject.Value() 247value.init(GObject.TYPE_UINT64) 248value.set_uint64(id(self)) 249return Gdk.ContentProvider.new_for_value(value) 250 251def drag_begin(self, source: Gtk.DragSource, drag: Gdk.Drag): 252paintable = Gtk.WidgetPaintable.new(self).get_current_image() 253source.set_icon(paintable, 0, 0) 254self.hide() 255 256def drag_cancel(self, source: Gtk.DragSource, drag: Gdk.Drag, reason: Gdk.DragCancelReason): 257self.show() 258return False 259 260@property 261def window_title(self): 262return self.label.get_text() 263 264@window_title.setter 265def window_title(self, value): 266self.label.set_text(value) 267 268def set_icon_from_app_id(self, app_id): 269app_ids = app_id.split() 270 271# If on Wayfire, find the IPC ID 272for app_id in app_ids: 273if app_id.startswith("wf-ipc-"): 274self.wf_ipc_id = int(app_id.removeprefix("wf-ipc-")) 275break 276 277# Try getting an icon from the correct theme 278icon_theme = Gtk.IconTheme.get_for_display(self.get_display()) 279 280for app_id in app_ids: 281if icon_theme.has_icon(app_id): 282self.icon.set_from_icon_name(app_id) 283return 284 285# If that doesn't work, try getting one from .desktop files 286for app_id in app_ids: 287try: 288desktop_file = Gio.DesktopAppInfo.new(app_id + ".desktop") 289if desktop_file: 290self.icon.set_from_gicon(desktop_file.get_icon()) 291return 292except TypeError: 293# Due to a bug, the constructor may sometimes return C NULL 294pass 295 296 297class WFWindowList(panorama_panel.Applet): 298name = _("Wayfire window list") 299description = _("Traditional window list (for Wayfire and other wlroots compositors)") 300 301def __init__(self, orientation=Gtk.Orientation.HORIZONTAL, config=None): 302super().__init__(orientation=orientation, config=config) 303if config is None: 304config = {} 305 306self.set_homogeneous(True) 307self.window_button_options = WindowButtonOptions(config.get("max_button_width", 256)) 308 309self.toplevel_buttons: dict[ZwlrForeignToplevelHandleV1, WindowButton] = {} 310self.toplevel_buttons_by_wf_id: dict[int, WindowButton] = {} 311# This button doesn't belong to any window but is used for the button group and to be 312# selected when no window is focused 313self.initial_button = Gtk.ToggleButton() 314 315self.display = None 316self.my_output = None 317self.wl_surface_ptr = None 318self.registry = None 319self.compositor = None 320self.seat = None 321 322self.context_menu = self.make_context_menu() 323panorama_panel.track_popover(self.context_menu) 324 325right_click_controller = Gtk.GestureClick() 326right_click_controller.set_button(3) 327right_click_controller.connect("pressed", self.show_context_menu) 328 329self.add_controller(right_click_controller) 330 331action_group = Gio.SimpleActionGroup() 332options_action = Gio.SimpleAction.new("options", None) 333options_action.connect("activate", self.show_options) 334action_group.add_action(options_action) 335self.insert_action_group("applet", action_group) 336# Wait for the widget to be in a layer-shell window before doing this 337self.connect("realize", lambda *args: self.get_wl_resources()) 338 339self.options_window = None 340 341# Support button reordering 342self.drop_target = Gtk.DropTarget.new(GObject.TYPE_UINT64, Gdk.DragAction.MOVE) 343self.drop_target.set_gtypes([GObject.TYPE_UINT64]) 344self.drop_target.connect("drop", self.drop_button) 345 346self.add_controller(self.drop_target) 347 348# Make a Wayfire socket for workspace handling 349try: 350import wayfire 351self.wf_socket = wayfire.WayfireSocket() 352self.wf_socket.watch() 353fd = self.wf_socket.client.fileno() 354GLib.io_add_watch(GLib.IOChannel.unix_new(fd), GLib.IO_IN, self.on_wf_event, priority=GLib.PRIORITY_HIGH) 355except: 356# Wayfire raises Exception itself, so it cannot be narrowed down 357self.wf_socket = None 358 359def on_wf_event(self, source, condition): 360if condition & GLib.IO_IN: 361try: 362message = self.wf_socket.read_next_event() 363event = message.get("event") 364match event: 365case "view-workspace-changed": 366view = message.get("view", {}) 367output = self.wf_socket.get_output(self.get_root().monitor_index + 1) 368current_workspace = output["workspace"]["x"], output["workspace"]["y"] 369if (message["to"]["x"], message["to"]["y"]) == current_workspace: 370if self.toplevel_buttons_by_wf_id[view["id"]].get_parent() is None: 371self.append(self.toplevel_buttons_by_wf_id[view["id"]]) 372else: 373if self.toplevel_buttons_by_wf_id[view["id"]].get_parent() is self: 374# Remove out-of-workspace window 375self.remove(self.toplevel_buttons_by_wf_id[view["id"]]) 376case "wset-workspace-changed": 377output_id = self.get_root().monitor_index + 1 378if message["wset-data"]["output-id"] == output_id: 379# It has changed on this monitor; refresh the window list 380self.filter_to_wf_workspace() 381 382except Exception as e: 383print("Error reading Wayfire event:", e) 384return True 385 386def drop_button(self, drop_target: Gtk.DropTarget, value: int, x: float, y: float): 387button: WindowButton = self.get_root().get_application().drags.pop(value) 388if button.get_parent() is not self: 389# Prevent dropping a button from another window list 390return False 391 392self.remove(button) 393# Find the position where to insert the applet 394# Probably we could use the assumption that buttons are homogeneous here for efficiency 395child = self.get_first_child() 396while child: 397allocation = child.get_allocation() 398child_x, child_y = self.translate_coordinates(self, 0, 0) 399if self.get_orientation() == Gtk.Orientation.HORIZONTAL: 400midpoint = child_x + allocation.width / 2 401if x < midpoint: 402button.insert_before(self, child) 403break 404elif self.get_orientation() == Gtk.Orientation.VERTICAL: 405midpoint = child_y + allocation.height / 2 406if y < midpoint: 407button.insert_before(self, child) 408break 409child = child.get_next_sibling() 410else: 411self.append(button) 412button.show() 413 414self.set_all_rectangles() 415return True 416 417def filter_to_wf_workspace(self): 418output = self.wf_socket.get_output(self.get_root().monitor_index + 1) 419for wf_id, button in self.toplevel_buttons_by_wf_id.items(): 420view = self.wf_socket.get_view(wf_id) 421mid_x = view["geometry"]["x"] + view["geometry"]["width"] / 2 422mid_y = view["geometry"]["y"] + view["geometry"]["height"] / 2 423output_width = output["geometry"]["width"] 424output_height = output["geometry"]["height"] 425if 0 <= mid_x < output_width and 0 <= mid_y < output_height: 426# It is in this workspace; keep it 427if button.get_parent() is None: 428self.append(button) 429else: 430# Remove it from this window list 431if button.get_parent() is self: 432self.remove(button) 433 434def get_wl_resources(self): 435ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p 436ctypes.pythonapi.PyCapsule_GetPointer.argtypes = (ctypes.py_object,) 437 438self.display = Display() 439wl_display_ptr = gtk.gdk_wayland_display_get_wl_display( 440ffi.cast("void *", ctypes.pythonapi.PyCapsule_GetPointer(self.get_root().get_native().get_display().__gpointer__, None))) 441self.display._ptr = wl_display_ptr 442self.event_queue = EventQueue(self.display) 443 444# Intentionally commented: the display is already connected by GTK 445# self.display.connect() 446 447my_monitor = Gtk4LayerShell.get_monitor(self.get_root()) 448 449# Iterate through monitors and get their Wayland output (wl_output) 450# This is a hack to ensure output_enter/leave is called for toplevels 451for monitor in self.get_root().get_native().get_display().get_monitors(): 452wl_output = gtk.gdk_wayland_monitor_get_wl_output(ffi.cast("void *", ctypes.pythonapi.PyCapsule_GetPointer(monitor.__gpointer__, None))) 453if wl_output: 454print("Create proxy") 455output_proxy = WlOutputProxy(wl_output, self.display) 456output_proxy.interface.registry[output_proxy._ptr] = output_proxy 457 458if monitor == my_monitor: 459self.my_output = output_proxy 460# End hack 461 462self.registry = self.display.get_registry() 463self.registry.dispatcher["global"] = self.on_global 464self.display.roundtrip() 465fd = self.display.get_fd() 466GLib.io_add_watch(fd, GLib.IO_IN, self.on_display_event) 467 468if self.wf_socket is not None: 469self.filter_to_wf_workspace() 470 471def on_display_event(self, source, condition): 472if condition & GLib.IO_IN: 473self.display.dispatch(queue=self.event_queue) 474return True 475 476def on_global(self, registry, name, interface, version): 477if interface == "zwlr_foreign_toplevel_manager_v1": 478self.print_log("Interface registered") 479self.manager = registry.bind(name, ZwlrForeignToplevelManagerV1, version) 480self.manager.dispatcher["toplevel"] = self.on_new_toplevel 481self.manager.dispatcher["finished"] = lambda *a: print("Toplevel manager finished") 482self.display.roundtrip() 483self.display.flush() 484elif interface == "wl_seat": 485self.print_log("Seat found") 486self.seat = registry.bind(name, WlSeat, version) 487elif interface == "wl_compositor": 488self.compositor = registry.bind(name, WlCompositor, version) 489self.wl_surface_ptr = gtk.gdk_wayland_surface_get_wl_surface( 490ffi.cast("void *", ctypes.pythonapi.PyCapsule_GetPointer( 491self.get_root().get_native().get_surface().__gpointer__, None))) 492 493def on_new_toplevel(self, manager: ZwlrForeignToplevelManagerV1, 494handle: ZwlrForeignToplevelHandleV1): 495handle.dispatcher["title"] = lambda h, title: self.on_title_changed(h, title) 496handle.dispatcher["app_id"] = lambda h, app_id: self.on_app_id_changed(h, app_id) 497handle.dispatcher["output_enter"] = self.on_output_entered 498handle.dispatcher["output_leave"] = self.on_output_left 499handle.dispatcher["state"] = lambda h, states: self.on_state_changed(h, states) 500handle.dispatcher["closed"] = lambda h: self.on_closed(h) 501 502def on_output_entered(self, handle, output): 503# TODO: make this configurable 504# TODO: on wayfire, append/remove buttons when the workspace changes 505if output != self.my_output: 506return 507if handle in self.toplevel_buttons: 508button = self.toplevel_buttons[handle] 509self.append(button) 510self.set_all_rectangles() 511 512def on_output_left(self, handle, output): 513if output != self.my_output: 514return 515if handle in self.toplevel_buttons: 516button = self.toplevel_buttons[handle] 517self.remove(button) 518self.set_all_rectangles() 519 520def on_title_changed(self, handle, title): 521if handle not in self.toplevel_buttons: 522button = WindowButton(handle, title) 523button.set_group(self.initial_button) 524button.set_layout_manager(WindowButtonLayoutManager(self.window_button_options)) 525button.connect("clicked", self.on_button_click) 526self.toplevel_buttons[handle] = button 527else: 528button = self.toplevel_buttons[handle] 529button.window_title = title 530 531def set_all_rectangles(self): 532child = self.get_first_child() 533while child is not None: 534if isinstance(child, WindowButton): 535surface = WlSurface() 536surface._ptr = self.wl_surface_ptr 537child.window_id.set_rectangle(surface, *get_widget_rect(child)) 538 539child = child.get_next_sibling() 540 541def on_button_click(self, button: WindowButton): 542# Set a rectangle for animation 543surface = WlSurface() 544surface._ptr = self.wl_surface_ptr 545button.window_id.set_rectangle(surface, *get_widget_rect(button)) 546if button.window_state.focused: 547# Already pressed in, so minimise the focused window 548button.window_id.set_minimized() 549else: 550button.window_id.unset_minimized() 551button.window_id.activate(self.seat) 552 553self.display.flush() 554 555def on_state_changed(self, handle, states): 556if handle in self.toplevel_buttons: 557state_info = WindowState.from_state_array(states) 558button = self.toplevel_buttons[handle] 559button.window_state = state_info 560if state_info.focused: 561button.set_active(True) 562else: 563self.initial_button.set_active(True) 564 565self.set_all_rectangles() 566 567def on_app_id_changed(self, handle, app_id): 568if handle in self.toplevel_buttons: 569button = self.toplevel_buttons[handle] 570button.set_icon_from_app_id(app_id) 571app_ids = app_id.split() 572for app_id in app_ids: 573if app_id.startswith("wf-ipc-"): 574self.toplevel_buttons_by_wf_id[int(app_id.removeprefix("wf-ipc-"))] = button 575 576def on_closed(self, handle): 577button: WindowButton = self.toplevel_buttons[handle] 578wf_id = button.wf_ipc_id 579if handle in self.toplevel_buttons: 580self.remove(self.toplevel_buttons[handle]) 581self.toplevel_buttons.pop(handle) 582if wf_id in self.toplevel_buttons_by_wf_id: 583self.toplevel_buttons_by_wf_id.pop(wf_id) 584 585self.set_all_rectangles() 586 587def make_context_menu(self): 588menu = Gio.Menu() 589menu.append(_("Window list _options"), "applet.options") 590context_menu = Gtk.PopoverMenu.new_from_model(menu) 591context_menu.set_has_arrow(False) 592context_menu.set_parent(self) 593context_menu.set_halign(Gtk.Align.START) 594context_menu.set_flags(Gtk.PopoverMenuFlags.NESTED) 595return context_menu 596 597def show_context_menu(self, gesture, n_presses, x, y): 598rect = Gdk.Rectangle() 599rect.x = int(x) 600rect.y = int(y) 601rect.width = 1 602rect.height = 1 603 604self.context_menu.set_pointing_to(rect) 605self.context_menu.popup() 606 607def show_options(self, _0=None, _1=None): 608if self.options_window is None: 609self.options_window = WindowListOptions() 610self.options_window.button_width_adjustment.set_value(self.window_button_options.max_width) 611self.options_window.button_width_adjustment.connect("value-changed", self.update_button_options) 612 613def reset_window(*args): 614self.options_window = None 615 616self.options_window.connect("close-request", reset_window) 617self.options_window.present() 618 619def update_button_options(self, adjustment): 620self.window_button_options.max_width = adjustment.get_value() 621child: Gtk.Widget = self.get_first_child() 622while child: 623child.queue_allocate() 624child.queue_resize() 625child.queue_draw() 626child = child.get_next_sibling() 627 628def get_config(self): 629return {"max_button_width": self.window_button_options.max_width} 630 631def output_changed(self): 632self.get_wl_resources() 633