-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbar.py
More file actions
740 lines (648 loc) · 27.4 KB
/
bar.py
File metadata and controls
740 lines (648 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
#!/usr/bin/python3 -u
"""
Description: Main GTK bar class that spawns the bar
Author: thnikk
"""
# For GTK4 Layer Shell to get linked before libwayland-client we must explicitly load it before importing with gi
from ctypes import CDLL
CDLL('libgtk4-layer-shell.so')
import gi
import os
import logging
from subprocess import run, CalledProcessError
import json
import time
import common as c
import module
import ipc
gi.require_version('Gtk', '4.0')
gi.require_version('Gtk4LayerShell', '1.0')
from gi.repository import Gtk, Gdk, Gtk4LayerShell, GLib # noqa
# Import DBus for sleep/resume handling
from gi.repository import Gio
class Display:
""" Display class """
def __init__(self, config, app):
self.app = app
# Set by reload() so the shutdown handler knows to exec.
self._reloading = False
# Replace the process image only after GTK has fully shut down so
# that GLib-managed subprocesses (e.g. bwrap/glycin from GdkPixbuf
# image loading) are reaped before execv() is called.
def _on_shutdown(application):
if self._reloading:
import sys
os.execv(sys.executable, [sys.executable] + sys.argv)
else:
# Normal exit: terminate subprocesses (e.g. nmcli monitor)
# before the process dies. reload() already calls these
# before app.quit(), so this only runs on a true exit.
module.stop_all_workers()
module.clear_instances()
self.app.connect('shutdown', _on_shutdown)
self.display = Gdk.Display.get_default()
self.display.connect('closed', self._on_display_closed)
monitors = self.display.get_monitors()
monitors.connect("items-changed", self.on_monitors_changed)
self.wm = self.get_wm()
self.config = config
self.bars = {}
self.monitors = self.get_monitors()
self.plugs = self.get_plugs()
# Track loaded CSS providers to prevent leaks
self.css_providers = []
# Load CSS once and store as string for PyInstaller temp path safety
self.default_css_data = None
css_path = c.get_resource_path('style.css')
try:
with open(css_path, 'r') as f:
self.default_css_data = f.read()
except Exception as e:
c.print_debug(
f"Failed to load default CSS: {e}",
name='display', color='red'
)
# Apply initial CSS
self.apply_css()
# Track sleep state to avoid scheduling reloads while sleeping
self.is_sleeping = False
# GLib source ID of the pending debounced reload timer
self._reload_timer_id = None
self._setup_dbus_sleep_handler()
# Watch for reload signal from settings
self.reload_file = os.path.expanduser('~/.cache/pybar/.reload')
self.reload_done_file = os.path.expanduser(
'~/.cache/pybar/.reload_done'
)
GLib.timeout_add_seconds(1, self._check_reload_signal)
# Start IPC socket server
self.ipc = ipc.IPCServer(self)
self.ipc.start()
def get_wm(self):
try:
run(['swaymsg', '-q'], check=True)
return 'sway'
except CalledProcessError:
return 'hyprland'
def apply_css(self):
"""Apply default and user CSS"""
self.clear_css()
# Load default CSS
if self.default_css_data:
self._add_css_provider(self.default_css_data, from_string=True)
# Apply dynamic overrides from config
dynamic_css = self._generate_dynamic_css()
if dynamic_css:
self._add_css_provider(dynamic_css, from_string=True)
# Load custom CSS
if 'style' in self.config:
self._add_css_provider(self.config['style'], from_string=False)
def _generate_dynamic_css(self):
"""Generate CSS from config values"""
css = []
bar_height = self.config.get('bar-height')
font_size = self.config.get('font-size')
floating_mode = self.config.get('floating-mode', False)
corner_radius = self.config.get('corner-radius', 0)
bar_opacity = self.config.get('bar-opacity')
popover_opacity = self.config.get('popover-opacity')
# Generate .bar CSS if any bar properties are set
if (bar_height is not None or font_size is not None or
floating_mode or corner_radius > 0 or
bar_opacity is not None):
css.append(".bar {")
if bar_height is not None:
css.append(f" min-height: {bar_height}px;")
if font_size is not None:
css.append(f" font-size: {font_size}px;")
if bar_opacity is not None:
css.append(f" opacity: {bar_opacity};")
# Apply full border when floating mode is enabled
if floating_mode:
css.append(
" border: 1px solid rgba(255, 255, 255, 0.1);"
)
if corner_radius > 0:
css.append(
f" border-radius: {corner_radius}px;"
)
else:
css.append(" border-radius: 0px;")
else:
# Only top border when floating mode is disabled
css.append(" border: none;")
css.append(
" border-top: 1px solid rgba(255, 255, 255, 0.1);"
)
css.append(" border-radius: 0px;")
css.append("}")
# Generate popover contents CSS if opacity is set
if popover_opacity is not None:
css.append("popover contents {")
css.append(f" opacity: {popover_opacity};")
css.append("}")
return "\n".join(css) if css else None
def _add_css_provider(self, data, from_string=False):
"""Helper to create and attach a CSS provider"""
try:
css_provider = Gtk.CssProvider()
if from_string:
data_bytes = data.encode('utf-8')
css_provider.load_from_data(data_bytes, len(data_bytes))
else:
css_provider.load_from_path(os.path.expanduser(data))
Gtk.StyleContext.add_provider_for_display(
self.display, css_provider,
Gtk.STYLE_PROVIDER_PRIORITY_USER
)
self.css_providers.append(css_provider)
except GLib.GError as e:
c.print_debug(
f"Failed to load CSS: {e}",
name='display', color='red'
)
def clear_css(self):
"""Remove all attached CSS providers"""
for provider in self.css_providers:
Gtk.StyleContext.remove_provider_for_display(
self.display, provider
)
self.css_providers.clear()
def _setup_dbus_sleep_handler(self):
""" Setup DBus listener for sleep/resume events """
try:
# Connect to systemd-logind's PrepareForSleep signal
self.dbus_proxy = Gio.DBusProxy.new_for_bus_sync(
Gio.BusType.SYSTEM,
Gio.DBusProxyFlags.NONE,
None,
'org.freedesktop.login1',
'/org/freedesktop/login1',
'org.freedesktop.login1.Manager',
None
)
if self.dbus_proxy:
self.dbus_proxy.connect(
'g-signal::PrepareForSleep',
self._on_prepare_for_sleep
)
logging.info("DBus sleep handler registered successfully")
except Exception as e:
logging.error(f"Failed to setup DBus sleep handler: {e}")
def _on_display_closed(self, display, is_error):
"""Restart if the GDK display is closed due to an error."""
if not is_error:
return
import sys
logging.warning("GDK display closed with error; restarting")
os.execv(sys.executable, [sys.executable] + sys.argv)
def _on_prepare_for_sleep(self, proxy, sender_name, signal_name,
parameters):
""" Handle PrepareForSleep signal from logind """
if len(parameters) > 0:
entering = parameters[0]
if entering:
logging.info("System entering sleep")
self.is_sleeping = True
else:
logging.info("System waking from sleep - scheduling reload")
self.is_sleeping = False
GLib.idle_add(self._on_wake_from_sleep)
def _on_wake_from_sleep(self):
""" Schedule a debounced reload after waking from sleep """
self._schedule_reload()
def _schedule_reload(self):
"""
Debounced reload: reset the 5s timer on each call.
Only fires once the timer elapses without being reset,
so multiple rapid monitor-add events collapse into one reload.
"""
if self._reload_timer_id is not None:
GLib.source_remove(self._reload_timer_id)
self._reload_timer_id = GLib.timeout_add_seconds(
5, self._do_reload
)
def _do_reload(self):
""" Timer callback: clear the timer ID and trigger a reload """
self._reload_timer_id = None
self.reload()
return False
def get_monitors(self):
""" Get monitor objects from gdk """
monitors = self.display.get_monitors()
return [monitors.get_item(i) for i in range(monitors.get_n_items())]
def get_plugs(self):
"""
Get monitor plug names for Wayland outputs.
Tries multiple methods and retries to get proper connector names.
"""
plugs = []
for monitor in self.monitors:
name = self._get_monitor_name(monitor, len(plugs))
plugs.append(name)
return plugs
def _get_monitor_name(self, monitor, index, max_retries=3):
"""
Get monitor name with retry logic.
After suspend, connector info may not be immediately available.
"""
for attempt in range(max_retries):
# Try to get the connector name (e.g., eDP-1, HDMI-A-1)
name = None
try:
name = monitor.get_connector()
except AttributeError:
pass
if name:
logging.debug(
f"Got connector name '{name}' for monitor {index}"
)
return name
# Try model as fallback
if not name:
try:
name = monitor.get_model()
if name:
logging.debug(
f"Using model name '{name}' for monitor {index}"
)
return name
except AttributeError:
pass
# If we still don't have a name and haven't exhausted retries
if attempt < max_retries - 1:
logging.debug(
f"Connector not available for monitor {index}, "
f"retrying... (attempt {attempt + 1}/{max_retries})"
)
time.sleep(0.2)
# Last resort: use generic name but log warning
fallback = f"monitor_{index}"
logging.warning(
f"Could not get connector name for monitor {index}, "
f"using fallback '{fallback}'. "
f"This may cause issues with outputs filter."
)
return fallback
def on_monitors_changed(self, model, position, removed, added):
""" Handle monitor changes """
if removed > 0:
# Destroy bars for monitors no longer present
current_plugs = set(
self._get_monitor_name(m, i)
for i, m in enumerate(self.get_monitors())
)
for plug in list(self.bars):
if plug not in current_plugs:
bar = self.bars.pop(plug)
try:
bar.window.destroy()
except Exception as e:
logging.warning(
"Error destroying bar for %s: %s", plug, e
)
logging.info(
"Removed bar for disconnected monitor %s", plug
)
if added > 0:
self._schedule_reload()
def draw_bar(self, monitor):
""" Draw a bar on a monitor """
# Validate monitor is still valid
if monitor and hasattr(monitor, 'is_valid') and not monitor.is_valid():
logging.warning(f"Monitor is invalid, skipping: {monitor}")
return
try_count = 0
plug = None
while try_count < 3:
try:
# Check if monitor is in our list
if monitor not in self.monitors:
logging.warning(f"Monitor not in active monitors list: {monitor}")
return
index = self.monitors.index(monitor)
plug = self.plugs[index]
break
except (IndexError, ValueError) as e:
logging.warning(f"Failed to find monitor index (attempt {try_count}): {e}")
try_count += 1
if try_count >= 3:
logging.error("Max retries reached for monitor lookup")
return
time.sleep(1)
if plug is None:
logging.error("Failed to determine monitor plug name")
return
# Check against outputs filter
if 'outputs' in list(self.config):
if plug not in self.config['outputs']:
logging.debug(f"Skipping bar for output {plug} (not in config)")
return
try:
bar = Bar(self, monitor)
bar.populate()
# CSS is now handled globally by Display
bar.start()
self.bars[plug] = bar
logging.info(f"Successfully created bar on {plug}")
except Exception as e:
logging.error(f"Failed to create bar on {plug}: {e}", exc_info=True)
def draw_all(self):
""" Initialize all monitors """
for monitor in self.monitors:
self.draw_bar(monitor)
def reload(self):
""" Reload by replacing the process image """
import module
# Signal completion before exec so the settings window
# isn't left waiting for a response that will never come.
try:
with open(self.reload_done_file, 'w') as f:
f.write('done')
except Exception as e:
c.print_debug(
f"Failed to signal reload completion: {e}",
name='display', color='red'
)
# Stop workers and run cleanup() on all instances so that
# subprocesses (e.g. nmcli monitor) are terminated before
# the process image is replaced.
module.stop_all_workers()
module.clear_instances()
# Terminate known library-managed persistent child processes that
# we have no direct handle to (e.g. the glycin-image-rs sandbox
# worker kept alive by GdkPixbuf between image decode calls).
# We match by executable name rather than sweeping all children,
# so transient module subprocesses (nvtop, nmcli, etc.) that are
# mid-run are not killed prematurely.
_LIBRARY_WORKERS = {'glycin-image-rs', 'bwrap'}
import signal as _signal
our_pid = str(os.getpid())
try:
for entry in os.listdir('/proc'):
if not entry.isdigit():
continue
try:
with open(f'/proc/{entry}/stat', 'r') as _f:
_stat = _f.read().split()
# Index 3 is PPID; index 1 is comm wrapped in parens.
if _stat[3] != our_pid:
continue
comm = _stat[1].strip('()')
if comm in _LIBRARY_WORKERS:
os.kill(int(entry), _signal.SIGTERM)
except OSError:
pass
except OSError:
pass
# Mark that we want to exec on shutdown, then ask GTK to quit.
# This lets GTK/GLib run its full teardown before execv() fires.
self._reloading = True
self.app.quit()
def _check_reload_signal(self):
""" Check if settings window has signaled a reload """
if os.path.exists(self.reload_file):
try:
os.remove(self.reload_file)
GLib.idle_add(self.reload)
except Exception as e:
c.print_debug(
f"Failed to handle reload signal: {e}",
name='display', color='red'
)
# Log Widget instance count every 30s (debug mode only).
if c.state_manager.get('debug'):
self._reload_check_ticks = getattr(
self, '_reload_check_ticks', 0) + 1
if self._reload_check_ticks % 30 == 0:
from common.widgets import _widget_instance_count
from common.state import state_manager as _sm
# Count total subscribers across all keys
total_subs = sum(
len(v) for v in _sm.subscribers.values()
)
ws_subs = len(_sm.subscribers.get('workspaces', {}))
logging.debug(
f"Widget instances: {_widget_instance_count} "
f"total subs: {total_subs} "
f"workspaces subs: {ws_subs} "
f"state keys: {len(_sm.data)}"
)
return True # Continue checking
class Bar:
""" Bar class"""
def __init__(self, display, monitor):
self.window = Gtk.Window()
self.window.set_application(display.app)
self.display = display
self.config = display.config
self.spacing = self.config['spacing'] if 'spacing' in self.config \
else 5
try:
self.position = display.config['position']
except KeyError:
self.position = 'bottom'
self.bar = Gtk.CenterBox(orientation=Gtk.Orientation.HORIZONTAL)
self.bar.get_style_context().add_class('bar')
self.left = c.box('h', style='modules-left', spacing=self.spacing)
self.center = c.box('h', style='modules-center', spacing=self.spacing)
self.right = c.box('h', style='modules-right', spacing=self.spacing)
self.bar.set_start_widget(self.left)
self.bar.set_center_widget(self.center)
self.bar.set_end_widget(self.right)
self.window.set_child(self.bar)
self.monitor = monitor
# Widget registry for IPC lookups (name -> widget)
self.module_widgets = {}
# Add right-click handler for settings
right_click = Gtk.GestureClick()
right_click.set_button(3) # Right click
right_click.connect('pressed', self._on_right_click)
self.bar.add_controller(right_click)
def cleanup_modules(self):
""" Manually cleanup all modules to prevent leaks """
count = 0
widgets_to_cleanup = []
# First, collect all module widgets
for section in [self.left, self.center, self.right]:
child = section.get_first_child()
while child:
widgets_to_cleanup.append(child)
child = child.get_next_sibling()
# Now cleanup and remove them
for widget in widgets_to_cleanup:
# Call cleanup BEFORE removing from parent
if hasattr(widget, 'cleanup'):
widget.cleanup()
count += 1
# Find which section it's in and remove
parent = widget.get_parent()
if parent:
parent.remove(widget)
# Disconnect all signals to break reference cycles
try:
c.GObject.signal_handlers_destroy(widget)
except Exception:
pass
# Actually destroy the widget to free GTK resources
if hasattr(widget, 'unparent'):
widget.unparent()
# Run disposal if available
if hasattr(widget, 'run_dispose'):
widget.run_dispose()
c.print_debug(f"Cleaned up {count} modules")
def populate(self):
""" Populate bar with modules """
# Map config section keys to short names used by zone-snap.
section_names = {
"modules-left": "left",
"modules-center": "center",
"modules-right": "right",
}
for section_key, section in {
"modules-left": self.left,
"modules-center": self.center,
"modules-right": self.right,
}.items():
for name in self.config[section_key]:
loaded_module = module.module(self, name, self.config)
if loaded_module:
# Store section membership so popovers can zone-snap.
loaded_module.section = section_names[section_key]
section.append(loaded_module)
# Track widget by name for IPC lookups
self.module_widgets[name] = loaded_module
else:
logging.warning(
f"Module '{name}' could not be loaded and will "
"be skipped."
)
def _on_right_click(self, gesture, n_press, x, y):
""" Handle right-click on bar to show context menu """
# Check if the click is on a module widget (not blank bar area)
# Get the widget at the click coordinates
widget = self.bar.pick(x, y, Gtk.PickFlags.DEFAULT)
# Only show menu if clicking on the bar itself or section boxes
# (not on module widgets which have their own right-click handlers)
if widget is not None:
# Walk up the widget tree to check if we're on a module
current = widget
while current is not None:
style_context = current.get_style_context()
# Check if this is a module widget
if (style_context.has_class('module') or
style_context.has_class('workspaces') or
style_context.has_class('tray-module')):
# Click is on a module, don't show bar context menu
return
# Check if we've reached the bar/section level
if (current == self.bar or
current == self.left or
current == self.center or
current == self.right):
break
current = current.get_parent()
# Create popover menu
popover = Gtk.Popover()
popover.set_position(Gtk.PositionType.TOP)
popover.set_autohide(True)
popover.get_style_context().add_class('bar-context-menu')
menu_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
# Settings button
settings_btn = c.icon_button("", "Settings")
settings_btn.get_style_context().add_class('flat')
settings_btn.connect('clicked', self._open_settings, popover)
menu_box.append(settings_btn)
# Reload button
reload_btn = c.icon_button(' ', 'Reload')
reload_btn.get_style_context().add_class('flat')
reload_btn.connect('clicked', self._reload_bar, popover)
menu_box.append(reload_btn)
if c.state_manager.get('debug'):
# Screenshot button
screenshot_btn = c.icon_button(' ', 'Screenshot')
screenshot_btn.get_style_context().add_class('flat')
screenshot_btn.connect('clicked', self._take_screenshot, popover)
menu_box.append(screenshot_btn)
# Inspector button
inspector_btn = c.icon_button('', 'Inspector')
inspector_btn.get_style_context().add_class('flat')
inspector_btn.connect('clicked', self._open_inspector, popover)
menu_box.append(inspector_btn)
popover.set_child(menu_box)
# Position the popover at click location
rect = Gdk.Rectangle()
rect.x = int(x)
rect.y = int(y)
rect.width = 1
rect.height = 1
popover.set_pointing_to(rect)
popover.set_parent(self.bar)
popover.popup()
def _open_settings(self, btn, popover):
""" Open settings window """
popover.popdown()
from settings import launch_settings_window
config_path = self.display.app.config_path
launch_settings_window(config_path)
def _reload_bar(self, btn, popover):
""" Reload bar configuration in-process """
popover.popdown()
# Reload configuration and rebuild bars without spawning new process
GLib.idle_add(self.display.reload)
def _take_screenshot(self, btn, popover):
""" Take a screenshot of the bar """
popover.popdown()
# Small delay to ensure popover is gone
# take_screenshot returns False, stopping the timeout
GLib.timeout_add(500, lambda: c.take_screenshot(self.bar))
def _open_inspector(self, btn, popover):
""" Open GTK Inspector """
popover.popdown()
Gtk.Window.set_interactive_debugging(True)
def modules(self, modules):
""" Add modules to bar """
main = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
main.get_style_context().add_class("bar")
for index, position in enumerate(["left", "center", "right"]):
section = Gtk.Box(
orientation=Gtk.Orientation.HORIZONTAL, spacing=2)
section.get_style_context().add_class(position)
if position == "center":
section.set_hexpand(True)
for item in modules[index]:
section.append(item())
main.append(section)
self.window.set_child(main)
def start(self):
""" Start bar """
Gtk4LayerShell.init_for_window(self.window)
pos = {
"bottom": Gtk4LayerShell.Edge.BOTTOM,
"top": Gtk4LayerShell.Edge.TOP
}
try:
position = pos[self.position]
except KeyError:
position = pos['bottom']
# Anchor and stretch to bottom of the screen
Gtk4LayerShell.set_anchor(self.window, position, 1)
Gtk4LayerShell.set_anchor(self.window, Gtk4LayerShell.Edge.LEFT, 1)
Gtk4LayerShell.set_anchor(self.window, Gtk4LayerShell.Edge.RIGHT, 1)
# Set margin only when floating mode is enabled
floating_mode = self.config.get('floating-mode', False)
margin = self.config.get('margin', 10) if floating_mode else 0
Gtk4LayerShell.set_margin(
self.window, Gtk4LayerShell.Edge.LEFT, margin)
Gtk4LayerShell.set_margin(
self.window, Gtk4LayerShell.Edge.RIGHT, margin)
Gtk4LayerShell.set_margin(self.window, position, margin)
# Set namespace based on config
if 'namespace' in list(self.config):
Gtk4LayerShell.set_namespace(self.window, self.config['namespace'])
else:
Gtk4LayerShell.set_namespace(self.window, 'pybar')
Gtk4LayerShell.set_monitor(self.window, self.monitor)
# Reserve part of screen
Gtk4LayerShell.auto_exclusive_zone_enable(self.window)
self.window.present()