By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 main.py

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