main.py
Python script, ASCII text executable
1from __future__ import annotations 2 3import os 4import sys 5import importlib 6from itertools import accumulate, chain 7from pathlib import Path 8import ruamel.yaml as yaml 9 10os.environ["GI_TYPELIB_PATH"] = "/usr/local/lib/x86_64-linux-gnu/girepository-1.0" 11 12from ctypes import CDLL 13CDLL('libgtk4-layer-shell.so') 14 15import gi 16gi.require_version("Gtk", "4.0") 17gi.require_version("Gtk4LayerShell", "1.0") 18 19from gi.repository import Gtk, GLib, Gtk4LayerShell, Gdk, Gio 20 21sys.path.insert(0, str((Path(__file__).parent / "shared").resolve())) 22 23import panorama_panel 24 25 26@Gtk.Template(filename="panel-manager.ui") 27class PanelManager(Gtk.Window): 28__gtype_name__ = "PanelManager" 29 30panel_editing_switch = Gtk.Template.Child() 31 32def __init__(self, application: Gtk.Application, **kwargs): 33super().__init__(application=application, **kwargs) 34 35self.connect("close-request", lambda *args: self.destroy()) 36 37action_group = Gio.SimpleActionGroup() 38 39toggle_edit_mode_action = Gio.SimpleAction(name="toggle-edit-mode-switch") 40action_group.add_action(toggle_edit_mode_action) 41toggle_edit_mode_action.connect("activate", lambda *args: self.panel_editing_switch.set_active(not self.panel_editing_switch.get_active())) 42 43self.insert_action_group("win", action_group) 44if isinstance(self.get_application(), PanoramaPanel): 45self.panel_editing_switch.set_active(application.edit_mode) 46self.panel_editing_switch.connect("state-set", self.set_edit_mode) 47 48self.connect("close-request", lambda *args: self.destroy()) 49 50def set_edit_mode(self, switch, value): 51if isinstance(self.get_application(), PanoramaPanel): 52self.get_application().set_edit_mode(value) 53 54 55def get_applet_directories(): 56data_home = Path(os.getenv("XDG_DATA_HOME", Path.home() / ".local" / "share")) 57data_dirs = [Path(d) for d in os.getenv("XDG_DATA_DIRS", "/usr/local/share:/usr/share").split(":")] 58 59all_paths = [data_home / "panorama-panel" / "applets"] + [d / "panorama-panel" / "applets" for d in data_dirs] 60return [d for d in all_paths if d.is_dir()] 61 62 63def get_config_file(): 64config_home = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) 65 66return config_home / "panorama-panel" / "config.yaml" 67 68 69class AppletArea(Gtk.Box): 70def __init__(self, orientation=Gtk.Orientation.HORIZONTAL): 71super().__init__() 72 73def set_edit_mode(self, value): 74child = self.get_first_child() 75while child is not None: 76child.set_sensitive(not value) 77child.set_opacity(0.75 if value else 1) 78child = child.get_next_sibling() 79 80 81class Panel(Gtk.Window): 82def __init__(self, application: Gtk.Application, monitor: Gdk.Monitor, position: Gtk.PositionType = Gtk.PositionType.TOP, size: int = 40, monitor_index: int = 0): 83super().__init__(application=application) 84self.set_default_size(800, size) 85self.set_decorated(False) 86self.position = position 87self.monitor_index = monitor_index 88self.size = size 89 90Gtk4LayerShell.init_for_window(self) 91 92Gtk4LayerShell.set_layer(self, Gtk4LayerShell.Layer.TOP) 93 94Gtk4LayerShell.auto_exclusive_zone_enable(self) 95Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.TOP, True) 96Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.LEFT, True) 97Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.RIGHT, True) 98 99box = Gtk.CenterBox() 100 101match position: 102case Gtk.PositionType.TOP | Gtk.PositionType.BOTTOM: 103box.set_orientation(Gtk.Orientation.HORIZONTAL) 104case Gtk.PositionType.LEFT | Gtk.PositionType.RIGHT: 105box.set_orientation(Gtk.Orientation.VERTICAL) 106 107self.set_child(box) 108 109self.left_area = AppletArea(orientation=box.get_orientation()) 110self.centre_area = AppletArea(orientation=box.get_orientation()) 111self.right_area = AppletArea(orientation=box.get_orientation()) 112 113box.set_start_widget(self.left_area) 114box.set_center_widget(self.centre_area) 115box.set_end_widget(self.right_area) 116 117# Add a context menu 118menu = Gio.Menu() 119 120menu.append("Open _manager", "panel.manager") 121 122self.context_menu = Gtk.PopoverMenu.new_from_model(menu) 123self.context_menu.set_has_arrow(False) 124self.context_menu.set_parent(self) 125self.context_menu.set_halign(Gtk.Align.START) 126self.context_menu.set_flags(Gtk.PopoverMenuFlags.NESTED) 127 128right_click_controller = Gtk.GestureClick() 129right_click_controller.set_button(3) 130right_click_controller.connect("pressed", self.show_context_menu) 131 132self.add_controller(right_click_controller) 133 134action_group = Gio.SimpleActionGroup() 135manager_action = Gio.SimpleAction.new("manager", None) 136manager_action.connect("activate", self.show_manager) 137action_group.add_action(manager_action) 138self.insert_action_group("panel", action_group) 139 140def set_edit_mode(self, value): 141for area in (self.left_area, self.centre_area, self.right_area): 142area.set_edit_mode(value) 143 144def show_context_menu(self, gesture, n_presses, x, y): 145rect = Gdk.Rectangle() 146rect.x = int(x) 147rect.y = int(y) 148rect.width = 1 149rect.height = 1 150 151self.context_menu.set_pointing_to(rect) 152self.context_menu.popup() 153 154def show_manager(self, _0=None, _1=None): 155print("Showing manager") 156if self.get_application(): 157if not self.get_application().manager_window: 158self.get_application().manager_window = PanelManager(self.get_application()) 159self.get_application().manager_window.connect("close-request", self.get_application().reset_manager_window) 160self.get_application().manager_window.present() 161 162def get_orientation(self): 163box = self.get_first_child() 164return box.get_orientation() 165 166 167def get_all_subclasses(klass: type) -> list[type]: 168subclasses = [] 169for subclass in klass.__subclasses__(): 170subclasses.append(subclass) 171subclasses += get_all_subclasses(subclass) 172 173return subclasses 174 175def load_packages_from_dir(dir_path: Path): 176loaded_modules = [] 177 178for path in dir_path.iterdir(): 179if path.name.startswith("_"): 180continue 181 182if path.is_dir() and (path / "__init__.py").exists(): 183module_name = path.name 184spec = importlib.util.spec_from_file_location(module_name, path / "__init__.py") 185module = importlib.util.module_from_spec(spec) 186spec.loader.exec_module(module) 187loaded_modules.append(module) 188else: 189continue 190 191return loaded_modules 192 193 194PANEL_POSITIONS = { 195"top": Gtk.PositionType.TOP, 196"bottom": Gtk.PositionType.BOTTOM, 197"left": Gtk.PositionType.LEFT, 198"right": Gtk.PositionType.RIGHT, 199} 200 201 202PANEL_POSITIONS_REVERSE = { 203Gtk.PositionType.TOP: "top", 204Gtk.PositionType.BOTTOM: "bottom", 205Gtk.PositionType.LEFT: "left", 206Gtk.PositionType.RIGHT: "right", 207} 208 209 210class PanoramaPanel(Gtk.Application): 211def __init__(self): 212super().__init__(application_id="com.roundabout_host.panorama.panel") 213self.display = Gdk.Display.get_default() 214self.monitors = self.display.get_monitors() 215self.applets_by_name = {} 216self.panels = [] 217self.manager_window = None 218self.edit_mode = False 219 220def do_startup(self): 221Gtk.Application.do_startup(self) 222for i, monitor in enumerate(self.monitors): 223geometry = monitor.get_geometry() 224print(f"Monitor {i}: {geometry.width}x{geometry.height} at {geometry.x},{geometry.y}") 225 226all_applets = list(chain.from_iterable(load_packages_from_dir(d) for d in get_applet_directories())) 227print("Applets:") 228subclasses = get_all_subclasses(panorama_panel.Applet) 229for subclass in subclasses: 230if subclass.__name__ in self.applets_by_name: 231print(f"Name conflict for applet {subclass.__name__}. Only one will be loaded.", file=sys.stderr) 232self.applets_by_name[subclass.__name__] = subclass 233 234with open(get_config_file(), "r") as config_file: 235yaml_loader = yaml.YAML(typ="rt") 236yaml_file = yaml_loader.load(config_file) 237for panel_data in yaml_file["panels"]: 238position = PANEL_POSITIONS[panel_data["position"]] 239monitor_index = panel_data["monitor"] 240monitor = self.monitors[monitor_index] 241size = panel_data["size"] 242 243panel = Panel(self, monitor, position, size, monitor_index) 244self.panels.append(panel) 245panel.show() 246 247print(f"{size}px panel on {position} edge of monitor {monitor_index}") 248 249for area_name, area in (("left", panel.left_area), ("centre", panel.centre_area), ("right", panel.right_area)): 250applet_list = panel_data["applets"].get(area_name) 251if applet_list is None: 252continue 253 254for applet in applet_list: 255item = list(applet.items())[0] 256AppletClass = self.applets_by_name[item[0]] 257options = item[1] 258applet_widget = AppletClass(orientation=panel.get_orientation(), config=options) 259 260area.append(applet_widget) 261 262def do_activate(self): 263Gio.Application.do_activate(self) 264 265def save_config(self): 266with open(get_config_file(), "w") as config_file: 267yaml_writer = yaml.YAML(typ="rt") 268data = {"panels": []} 269for panel in self.panels: 270panel_data = { 271"position": PANEL_POSITIONS_REVERSE[panel.position], 272"monitor": panel.monitor_index, 273"size": panel.size, 274"applets": {} 275} 276 277for area_name, area in (("left", panel.left_area), ("centre", panel.centre_area), ("right", panel.right_area)): 278panel_data["applets"][area_name] = [] 279applet = area.get_first_child() 280while applet is not None: 281panel_data["applets"][area_name].append({ 282applet.__class__.__name__: applet.get_config(), 283}) 284 285applet = applet.get_next_sibling() 286 287data["panels"].append(panel_data) 288 289yaml_writer.dump(data, config_file) 290 291def do_shutdown(self): 292print("Shutting down") 293Gtk.Application.do_shutdown(self) 294self.save_config() 295 296def set_edit_mode(self, value): 297self.edit_mode = value 298for panel in self.panels: 299panel.set_edit_mode(value) 300 301def reset_manager_window(self, *args): 302self.manager_window = None 303 304 305if __name__ == "__main__": 306app = PanoramaPanel() 307app.run(sys.argv) 308