main.py
Python script, ASCII text executable
1from __future__ import annotations 2 3import os 4import sys 5import importlib 6import typing 7from itertools import accumulate, chain 8from pathlib import Path 9import ruamel.yaml as yaml 10 11os.environ["GI_TYPELIB_PATH"] = "/usr/local/lib/x86_64-linux-gnu/girepository-1.0" 12 13from ctypes import CDLL 14CDLL('libgtk4-layer-shell.so') 15 16import gi 17gi.require_version("Gtk", "4.0") 18gi.require_version("Gtk4LayerShell", "1.0") 19 20from gi.repository import Gtk, GLib, Gtk4LayerShell, Gdk, Gio, GObject 21 22sys.path.insert(0, str((Path(__file__).parent / "shared").resolve())) 23 24import panorama_panel 25 26 27custom_css = """ 28.panel-flash { 29animation: flash 1000ms ease-in-out 0s 2; 30} 31 32@keyframes flash { 330% { 34background-color: initial; 35} 3650% { 37background-color: #ffff0080; 38} 390% { 40background-color: initial; 41} 42} 43""" 44 45css_provider = Gtk.CssProvider() 46css_provider.load_from_data(custom_css) 47Gtk.StyleContext.add_provider_for_display( 48Gdk.Display.get_default(), 49css_provider, 50Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION 51) 52 53 54@Gtk.Template(filename="panel-configurator.ui") 55class PanelConfigurator(Gtk.Frame): 56__gtype_name__ = "PanelConfigurator" 57 58panel_size_adjustment: Gtk.Adjustment = Gtk.Template.Child() 59monitor_number_adjustment: Gtk.Adjustment = Gtk.Template.Child() 60top_position_radio: Gtk.CheckButton = Gtk.Template.Child() 61bottom_position_radio: Gtk.CheckButton = Gtk.Template.Child() 62left_position_radio: Gtk.CheckButton = Gtk.Template.Child() 63right_position_radio: Gtk.CheckButton = Gtk.Template.Child() 64 65def __init__(self, panel: Panel, **kwargs): 66super().__init__(**kwargs) 67self.panel = panel 68self.panel_size_adjustment.set_value(panel.size) 69 70match self.panel.position: 71case Gtk.PositionType.TOP: 72self.top_position_radio.set_active(True) 73case Gtk.PositionType.BOTTOM: 74self.bottom_position_radio.set_active(True) 75case Gtk.PositionType.LEFT: 76self.left_position_radio.set_active(True) 77case Gtk.PositionType.RIGHT: 78self.right_position_radio.set_active(True) 79 80self.top_position_radio.panel_position_target = Gtk.PositionType.TOP 81self.bottom_position_radio.panel_position_target = Gtk.PositionType.BOTTOM 82self.left_position_radio.panel_position_target = Gtk.PositionType.LEFT 83self.right_position_radio.panel_position_target = Gtk.PositionType.RIGHT 84 85@Gtk.Template.Callback() 86def update_panel_size(self, adjustment: Gtk.Adjustment): 87if not self.get_root(): 88return 89self.panel.set_size(int(adjustment.get_value())) 90 91@Gtk.Template.Callback() 92def move_panel(self, button: Gtk.CheckButton): 93if not self.get_root(): 94return 95if not button.get_active(): 96return 97print("Moving panel") 98self.panel.set_position(button.panel_position_target) 99self.update_panel_size(self.panel_size_adjustment) 100 101# Make the applets aware of the changed orientation 102for area in (self.panel.left_area, self.panel.centre_area, self.panel.right_area): 103applet = area.get_first_child() 104while applet: 105applet.set_orientation(self.panel.get_orientation()) 106applet.set_panel_position(self.panel.position) 107applet.queue_resize() 108applet = applet.get_next_sibling() 109 110@Gtk.Template.Callback() 111def move_to_monitor(self, adjustment: Gtk.Adjustment): 112if not self.get_root(): 113return 114app: PanoramaPanel = self.get_root().get_application() 115monitor = app.monitors[int(self.monitor_number_adjustment.get_value())] 116self.panel.unmap() 117Gtk4LayerShell.set_monitor(self.panel, monitor) 118self.panel.show() 119 120 121PANEL_POSITIONS_HUMAN = { 122Gtk.PositionType.TOP: "top", 123Gtk.PositionType.BOTTOM: "bottom", 124Gtk.PositionType.LEFT: "left", 125Gtk.PositionType.RIGHT: "right", 126} 127 128 129@Gtk.Template(filename="panel-manager.ui") 130class PanelManager(Gtk.Window): 131__gtype_name__ = "PanelManager" 132 133panel_editing_switch: Gtk.Switch = Gtk.Template.Child() 134panel_stack: Gtk.Stack = Gtk.Template.Child() 135current_panel: typing.Optional[Panel] = None 136 137def __init__(self, application: Gtk.Application, **kwargs): 138super().__init__(application=application, **kwargs) 139 140self.connect("close-request", lambda *args: self.destroy()) 141 142action_group = Gio.SimpleActionGroup() 143 144self.next_panel_action = Gio.SimpleAction(name="next-panel") 145action_group.add_action(self.next_panel_action) 146self.next_panel_action.connect("activate", lambda *args: self.panel_stack.set_visible_child(self.panel_stack.get_visible_child().get_next_sibling())) 147 148self.previous_panel_action = Gio.SimpleAction(name="previous-panel") 149action_group.add_action(self.previous_panel_action) 150self.previous_panel_action.connect("activate", lambda *args: self.panel_stack.set_visible_child(self.panel_stack.get_visible_child().get_prev_sibling())) 151 152self.insert_action_group("win", action_group) 153if isinstance(self.get_application(), PanoramaPanel): 154self.panel_editing_switch.set_active(application.edit_mode) 155self.panel_editing_switch.connect("state-set", self.set_edit_mode) 156 157self.connect("close-request", lambda *args: self.unflash_old_panel()) 158self.connect("close-request", lambda *args: self.destroy()) 159 160if isinstance(self.get_application(), PanoramaPanel): 161app: PanoramaPanel = self.get_application() 162for panel in app.panels: 163configurator = PanelConfigurator(panel) 164self.panel_stack.add_child(configurator) 165configurator.monitor_number_adjustment.set_upper(len(app.monitors)) 166 167self.panel_stack.set_visible_child(self.panel_stack.get_first_child()) 168self.panel_stack.connect("notify::visible-child", self.set_visible_panel) 169self.panel_stack.notify("visible-child") 170 171def unflash_old_panel(self): 172if self.current_panel: 173for area in (self.current_panel.left_area, self.current_panel.centre_area, self.current_panel.right_area): 174area.unflash() 175 176def set_visible_panel(self, stack: Gtk.Stack, pspec: GObject.ParamSpec): 177self.unflash_old_panel() 178 179panel: Panel = stack.get_visible_child().panel 180 181self.current_panel = panel 182self.next_panel_action.set_enabled(stack.get_visible_child().get_next_sibling() is not None) 183self.previous_panel_action.set_enabled(stack.get_visible_child().get_prev_sibling() is not None) 184 185# Start an animation to show the user what panel is being edited 186for area in (panel.left_area, panel.centre_area, panel.right_area): 187area.flash() 188 189def set_edit_mode(self, switch, value): 190if isinstance(self.get_application(), PanoramaPanel): 191self.get_application().set_edit_mode(value) 192 193@Gtk.Template.Callback() 194def save_settings(self, *args): 195if isinstance(self.get_application(), PanoramaPanel): 196print("Saving settings as user requested") 197self.get_application().save_config() 198 199 200def get_applet_directories(): 201data_home = Path(os.getenv("XDG_DATA_HOME", Path.home() / ".local" / "share")) 202data_dirs = [Path(d) for d in os.getenv("XDG_DATA_DIRS", "/usr/local/share:/usr/share").split(":")] 203 204all_paths = [data_home / "panorama-panel" / "applets"] + [d / "panorama-panel" / "applets" for d in data_dirs] 205return [d for d in all_paths if d.is_dir()] 206 207 208def get_config_file(): 209config_home = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) 210 211return config_home / "panorama-panel" / "config.yaml" 212 213 214class AppletArea(Gtk.Box): 215def __init__(self, orientation=Gtk.Orientation.HORIZONTAL): 216super().__init__() 217 218self.drop_target = Gtk.DropTarget.new(GObject.TYPE_UINT64, Gdk.DragAction.MOVE) 219self.drop_target.set_gtypes([GObject.TYPE_UINT64]) 220self.drop_target.connect("drop", self.drop_applet) 221 222def drop_applet(self, drop_target: Gtk.DropTarget, value: int, x: float, y: float): 223print(f"Dropping applet: {value}") 224applet: panorama_panel.Applet = self.get_root().get_application().drags.pop(value) 225print(f"Type: {applet.__class__.__name__}") 226old_area: AppletArea = applet.get_parent() 227old_area.remove(applet) 228self.append(applet) 229return True 230 231def set_edit_mode(self, value): 232panel: Panel = self.get_root() 233child = self.get_first_child() 234while child is not None: 235if value: 236child.make_draggable() 237else: 238child.restore_drag() 239child.set_opacity(0.75 if value else 1) 240child = child.get_next_sibling() 241 242if value: 243self.add_controller(self.drop_target) 244if panel.get_orientation() == Gtk.Orientation.HORIZONTAL: 245self.set_size_request(48, 0) 246elif panel.get_orientation() == Gtk.Orientation.VERTICAL: 247self.set_size_request(0, 48) 248else: 249self.remove_controller(self.drop_target) 250self.set_size_request(0, 0) 251 252def flash(self): 253self.add_css_class("panel-flash") 254 255def unflash(self): 256self.remove_css_class("panel-flash") 257 258 259class Panel(Gtk.Window): 260def __init__(self, application: Gtk.Application, monitor: Gdk.Monitor, position: Gtk.PositionType = Gtk.PositionType.TOP, size: int = 40, monitor_index: int = 0): 261super().__init__(application=application) 262self.set_decorated(False) 263self.position = None 264self.monitor_index = monitor_index 265 266Gtk4LayerShell.init_for_window(self) 267Gtk4LayerShell.set_monitor(self, monitor) 268 269Gtk4LayerShell.set_layer(self, Gtk4LayerShell.Layer.TOP) 270 271Gtk4LayerShell.auto_exclusive_zone_enable(self) 272 273box = Gtk.CenterBox() 274 275self.set_child(box) 276self.set_position(position) 277self.set_size(size) 278 279self.left_area = AppletArea(orientation=box.get_orientation()) 280self.centre_area = AppletArea(orientation=box.get_orientation()) 281self.right_area = AppletArea(orientation=box.get_orientation()) 282 283box.set_start_widget(self.left_area) 284box.set_center_widget(self.centre_area) 285box.set_end_widget(self.right_area) 286 287# Add a context menu 288menu = Gio.Menu() 289 290menu.append("Open _manager", "panel.manager") 291 292self.context_menu = Gtk.PopoverMenu.new_from_model(menu) 293self.context_menu.set_has_arrow(False) 294self.context_menu.set_parent(self) 295self.context_menu.set_halign(Gtk.Align.START) 296self.context_menu.set_flags(Gtk.PopoverMenuFlags.NESTED) 297 298right_click_controller = Gtk.GestureClick() 299right_click_controller.set_button(3) 300right_click_controller.connect("pressed", self.show_context_menu) 301 302self.add_controller(right_click_controller) 303 304action_group = Gio.SimpleActionGroup() 305manager_action = Gio.SimpleAction.new("manager", None) 306manager_action.connect("activate", self.show_manager) 307action_group.add_action(manager_action) 308self.insert_action_group("panel", action_group) 309 310def set_edit_mode(self, value): 311for area in (self.left_area, self.centre_area, self.right_area): 312area.set_edit_mode(value) 313 314def show_context_menu(self, gesture, n_presses, x, y): 315rect = Gdk.Rectangle() 316rect.x = int(x) 317rect.y = int(y) 318rect.width = 1 319rect.height = 1 320 321self.context_menu.set_pointing_to(rect) 322self.context_menu.popup() 323 324def show_manager(self, _0=None, _1=None): 325print("Showing manager") 326if self.get_application(): 327if not self.get_application().manager_window: 328self.get_application().manager_window = PanelManager(self.get_application()) 329self.get_application().manager_window.connect("close-request", self.get_application().reset_manager_window) 330self.get_application().manager_window.present() 331 332def get_orientation(self): 333box = self.get_first_child() 334return box.get_orientation() 335 336def set_size(self, value: int): 337self.size = int(value) 338if self.get_orientation() == Gtk.Orientation.HORIZONTAL: 339self.set_size_request(800, self.size) 340self.set_default_size(800, self.size) 341else: 342self.set_size_request(self.size, 600) 343self.set_default_size(self.size, 600) 344 345def set_position(self, position: Gtk.PositionType): 346self.position = position 347match self.position: 348case Gtk.PositionType.TOP: 349Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.BOTTOM, False) 350Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.TOP, True) 351Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.LEFT, True) 352Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.RIGHT, True) 353case Gtk.PositionType.BOTTOM: 354Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.TOP, False) 355Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.BOTTOM, True) 356Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.LEFT, True) 357Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.RIGHT, True) 358case Gtk.PositionType.LEFT: 359Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.RIGHT, False) 360Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.LEFT, True) 361Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.TOP, True) 362Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.BOTTOM, True) 363case Gtk.PositionType.RIGHT: 364Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.LEFT, False) 365Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.RIGHT, True) 366Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.TOP, True) 367Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.BOTTOM, True) 368box = self.get_first_child() 369match self.position: 370case Gtk.PositionType.TOP | Gtk.PositionType.BOTTOM: 371box.set_orientation(Gtk.Orientation.HORIZONTAL) 372case Gtk.PositionType.LEFT | Gtk.PositionType.RIGHT: 373box.set_orientation(Gtk.Orientation.VERTICAL) 374 375def get_all_subclasses(klass: type) -> list[type]: 376subclasses = [] 377for subclass in klass.__subclasses__(): 378subclasses.append(subclass) 379subclasses += get_all_subclasses(subclass) 380 381return subclasses 382 383def load_packages_from_dir(dir_path: Path): 384loaded_modules = [] 385 386for path in dir_path.iterdir(): 387if path.name.startswith("_"): 388continue 389 390if path.is_dir() and (path / "__init__.py").exists(): 391module_name = path.name 392spec = importlib.util.spec_from_file_location(module_name, path / "__init__.py") 393module = importlib.util.module_from_spec(spec) 394spec.loader.exec_module(module) 395loaded_modules.append(module) 396else: 397continue 398 399return loaded_modules 400 401 402PANEL_POSITIONS = { 403"top": Gtk.PositionType.TOP, 404"bottom": Gtk.PositionType.BOTTOM, 405"left": Gtk.PositionType.LEFT, 406"right": Gtk.PositionType.RIGHT, 407} 408 409 410PANEL_POSITIONS_REVERSE = { 411Gtk.PositionType.TOP: "top", 412Gtk.PositionType.BOTTOM: "bottom", 413Gtk.PositionType.LEFT: "left", 414Gtk.PositionType.RIGHT: "right", 415} 416 417 418class PanoramaPanel(Gtk.Application): 419def __init__(self): 420super().__init__(application_id="com.roundabout_host.panorama.panel") 421self.display = Gdk.Display.get_default() 422self.monitors = self.display.get_monitors() 423self.applets_by_name: dict[str, panorama_panel.Applet] = {} 424self.panels: list[Panel] = [] 425self.manager_window = None 426self.edit_mode = False 427self.drags = {} 428 429def do_startup(self): 430Gtk.Application.do_startup(self) 431for i, monitor in enumerate(self.monitors): 432geometry = monitor.get_geometry() 433print(f"Monitor {i}: {geometry.width}x{geometry.height} at {geometry.x},{geometry.y}") 434 435all_applets = list(chain.from_iterable(load_packages_from_dir(d) for d in get_applet_directories())) 436print("Applets:") 437subclasses = get_all_subclasses(panorama_panel.Applet) 438for subclass in subclasses: 439if subclass.__name__ in self.applets_by_name: 440print(f"Name conflict for applet {subclass.__name__}. Only one will be loaded.", file=sys.stderr) 441self.applets_by_name[subclass.__name__] = subclass 442 443with open(get_config_file(), "r") as config_file: 444yaml_loader = yaml.YAML(typ="rt") 445yaml_file = yaml_loader.load(config_file) 446for panel_data in yaml_file["panels"]: 447position = PANEL_POSITIONS[panel_data["position"]] 448monitor_index = panel_data["monitor"] 449if monitor_index >= len(self.monitors): 450continue 451monitor = self.monitors[monitor_index] 452size = panel_data["size"] 453 454panel = Panel(self, monitor, position, size, monitor_index) 455self.panels.append(panel) 456panel.show() 457 458print(f"{size}px panel on {position} edge of monitor {monitor_index}") 459 460for area_name, area in (("left", panel.left_area), ("centre", panel.centre_area), ("right", panel.right_area)): 461applet_list = panel_data["applets"].get(area_name) 462if applet_list is None: 463continue 464 465for applet in applet_list: 466item = list(applet.items())[0] 467AppletClass = self.applets_by_name[item[0]] 468options = item[1] 469applet_widget = AppletClass(orientation=panel.get_orientation(), config=options) 470applet_widget.set_panel_position(panel.position) 471 472area.append(applet_widget) 473 474def do_activate(self): 475Gio.Application.do_activate(self) 476 477def save_config(self): 478with open(get_config_file(), "w") as config_file: 479yaml_writer = yaml.YAML(typ="rt") 480data = {"panels": []} 481for panel in self.panels: 482panel_data = { 483"position": PANEL_POSITIONS_REVERSE[panel.position], 484"monitor": panel.monitor_index, 485"size": panel.size, 486"applets": {} 487} 488 489for area_name, area in (("left", panel.left_area), ("centre", panel.centre_area), ("right", panel.right_area)): 490panel_data["applets"][area_name] = [] 491applet = area.get_first_child() 492while applet is not None: 493panel_data["applets"][area_name].append({ 494applet.__class__.__name__: applet.get_config(), 495}) 496 497applet = applet.get_next_sibling() 498 499data["panels"].append(panel_data) 500 501yaml_writer.dump(data, config_file) 502 503def do_shutdown(self): 504print("Shutting down") 505Gtk.Application.do_shutdown(self) 506self.save_config() 507 508def set_edit_mode(self, value): 509self.edit_mode = value 510for panel in self.panels: 511panel.set_edit_mode(value) 512 513def reset_manager_window(self, *args): 514self.manager_window = None 515 516 517if __name__ == "__main__": 518app = PanoramaPanel() 519app.run(sys.argv) 520