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