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