Repository navigation
Expand file tree
/
Copy pathclickbuffet
More file actions
executable file
·1003 lines (829 loc) · 32.4 KB
/
Copy pathclickbuffet
File metadata and controls
executable file
·1003 lines (829 loc) · 32.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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""ClickBuffet - A configurable popup launcher menu for Wayland."""
import argparse
import atexit
import os
import signal
import sys
import cairo
import gi
gi.require_version("Gdk", "3.0")
gi.require_version("Gtk", "3.0")
gi.require_version("PangoCairo", "1.0")
gi.require_version("GtkLayerShell", "0.1")
from gi.repository import Gdk, GLib, Gtk, GtkLayerShell, Pango, PangoCairo
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
CONFIG_DIR = os.path.expanduser("~/.config/clickbuffet")
CONFIG_FILE = os.path.join(CONFIG_DIR, "menu.conf")
LOCK_FILE = f"/tmp/clickbuffet-{os.getuid()}.lock"
# Style (overridden by settings file at startup)
ICON_FONT = "JetBrainsMono Nerd Font 11"
LABEL_FONT = "Sans 11"
# Defaults (overridden by GTK theme at startup)
MENU_BG = (0.10, 0.11, 0.15, 0.95)
MENU_BORDER = (0.20, 0.22, 0.28, 1.0)
ITEM_FG = (0.78, 0.80, 0.84, 1.0)
ITEM_ACTIVE_BG = (0.22, 0.24, 0.32, 1.0)
ITEM_ACTIVE_FG = (0.90, 0.92, 0.96, 1.0)
SEPARATOR_FG = (0.30, 0.32, 0.38, 1.0)
ITEM_HEIGHT = 32
ITEM_PADDING_X = 14
SEPARATOR_HEIGHT = 9
BORDER_WIDTH = 1
BORDER_RADIUS = 6
SUBMENU_OVERLAP = 4
SUBMENU_DELAY_MS = 150
MIN_MENU_WIDTH = 180
SUBMENU_ARROW = "›"
# Animation
ANIM_ENABLED = True
ANIM_FADE_DURATION_MS = 80
ANIM_CASCADE_DELAY_MS = 20
ANIM_FRAME_INTERVAL_MS = 16 # ~60fps
# ---------------------------------------------------------------------------
# Data model
# ---------------------------------------------------------------------------
class MenuItem:
def __init__(self, icon="", label="", command="", children=None, is_separator=False, color=None):
self.icon = icon
self.label = label
self.command = command
self.children = children or []
self.is_separator = is_separator
self.color = color # optional (r, g, b, a) tuple
self.box = (0, 0, 0, 0) # x, y, w, h
self.hover = False
self.submenu_visible = False
self.submenu_timer = None
self._submenu_box = (0, 0, 0, 0)
self.anim_alpha = 1.0 # per-item opacity for cascade
class Menu:
def __init__(self, items=None):
self.items = items or []
self.box = (0, 0, 0, 0)
self.visible = False
self.right_aligned = False
self.bottom_aligned = False
self.anim_progress = 1.0 # 0→1 overall fade
self.anim_timer = None
self.anim_start_time = 0
# ---------------------------------------------------------------------------
# Config parser
# ---------------------------------------------------------------------------
def _parse_color(text):
"""Parse a color from hex (#rrggbb) or CSS name (e.g. 'coral'). Returns (r,g,b,a) or None."""
text = text.strip()
if not text:
return None
rgba = Gdk.RGBA()
if rgba.parse(text):
return (rgba.red, rgba.green, rgba.blue, rgba.alpha)
return None
def _is_nerd_icon(ch):
"""Check if a character is likely a Nerd Font glyph (Private Use Area)."""
cp = ord(ch)
return (
0xE000 <= cp <= 0xF8FF
or 0xF0000 <= cp <= 0x10FFFF
or 0x2300 <= cp <= 0x27BF # misc symbols
or 0xE700 <= cp <= 0xE7FF
)
def _parse_icon_label(text):
"""Split 'icon label' or just 'label' from a stripped string."""
text = text.strip()
if not text:
return "", ""
# Check if first character is a Nerd Font icon
first = text[0]
if _is_nerd_icon(first):
rest = text[1:].strip()
return first, rest
return "", text
def parse_config(filepath):
"""Parse menu.conf into a Menu tree."""
if not os.path.isfile(filepath):
return Menu()
with open(filepath, "r", encoding="utf-8") as f:
lines = f.readlines()
root = Menu()
# Stack of (menu, indent_level)
stack = [(root, -1)]
for raw_line in lines:
# Strip trailing whitespace only; leading whitespace is significant
line = raw_line.rstrip()
if not line or line.lstrip().startswith("#"):
continue
# Determine indentation
stripped = line.lstrip()
indent = len(line) - len(stripped)
# Pop stack to find correct parent
while len(stack) > 1 and indent <= stack[-1][1]:
stack.pop()
parent_menu = stack[-1][0]
# Separator
if stripped == "---":
parent_menu.items.append(MenuItem(is_separator=True))
continue
# Submenu parent: ends with > (optionally: label | #color >)
if stripped.rstrip().endswith(">"):
left = stripped.rstrip()[:-1].rstrip()
color = None
if "|" in left:
parts = left.split("|")
left = parts[0].strip()
color = _parse_color(parts[1]) if len(parts) > 1 else None
icon, label = _parse_icon_label(left)
submenu = Menu()
item = MenuItem(icon=icon, label=label, children=[], color=color)
item._submenu = submenu
parent_menu.items.append(item)
stack.append((submenu, indent))
continue
# Regular item: icon label | command | #color
if "|" in stripped:
parts = stripped.split("|")
left = parts[0].strip()
command = parts[1].strip() if len(parts) > 1 else ""
color = _parse_color(parts[2]) if len(parts) > 2 else None
icon, label = _parse_icon_label(left)
parent_menu.items.append(
MenuItem(icon=icon, label=label, command=command, color=color)
)
else:
# No command, just a label
icon, label = _parse_icon_label(stripped)
parent_menu.items.append(MenuItem(icon=icon, label=label))
# Convert submenu items from Menu objects to children lists
_flatten_submenus(root)
return root
def _flatten_submenus(menu):
"""Move items from _submenu Menu objects into item.children."""
for item in menu.items:
if hasattr(item, "_submenu"):
submenu = item._submenu
item.children = submenu.items
del item._submenu
_flatten_submenus_list(item.children)
def _flatten_submenus_list(items):
for item in items:
if hasattr(item, "_submenu"):
submenu = item._submenu
item.children = submenu.items
del item._submenu
_flatten_submenus_list(item.children)
# ---------------------------------------------------------------------------
# Single instance lock
# ---------------------------------------------------------------------------
def acquire_lock():
if os.path.isfile(LOCK_FILE):
try:
with open(LOCK_FILE, "r") as f:
pid = int(f.read().strip())
os.kill(pid, 0)
# Process alive -> exit
sys.exit(0)
except (ValueError, ProcessLookupError, PermissionError):
pass # Stale lock
with open(LOCK_FILE, "w") as f:
f.write(str(os.getpid()))
atexit.register(release_lock)
def release_lock():
try:
os.unlink(LOCK_FILE)
except OSError:
pass
# ---------------------------------------------------------------------------
# Menu layout
# ---------------------------------------------------------------------------
def _icon_col_width(menu, pango_ctx):
"""Compute a fixed icon column width for a menu (widest icon + spacing)."""
has_icons = any(item.icon for item in menu.items if not item.is_separator)
if not has_icons:
return 0
layout = Pango.Layout.new(pango_ctx)
layout.set_font_description(Pango.FontDescription.from_string(ICON_FONT))
max_iw = 0
for item in menu.items:
if item.is_separator or not item.icon:
continue
layout.set_text(item.icon + " ", -1)
iw, _ = layout.get_pixel_size()
max_iw = max(max_iw, iw)
return max_iw
def measure_menu(menu, pango_ctx):
"""Calculate menu width and item heights. Returns (width, height)."""
max_text_w = 0
total_h = 0
has_submenu = any(item.children for item in menu.items if not item.is_separator)
icon_w = _icon_col_width(menu, pango_ctx)
layout = Pango.Layout.new(pango_ctx)
layout.set_font_description(Pango.FontDescription.from_string(LABEL_FONT))
for item in menu.items:
if item.is_separator:
total_h += SEPARATOR_HEIGHT
continue
layout.set_text(item.label, -1)
tw, _ = layout.get_pixel_size()
tw += icon_w
if has_submenu:
layout.set_text(f" {SUBMENU_ARROW}", -1)
aw, _ = layout.get_pixel_size()
tw += aw
max_text_w = max(max_text_w, tw)
total_h += ITEM_HEIGHT
width = max(max_text_w + ITEM_PADDING_X * 2, MIN_MENU_WIDTH)
height = total_h
return width, height
def configure_menu(menu, screen_w, screen_h, ref_x, ref_y, ref_w, ref_h, pango_ctx):
"""Position a menu relative to a reference box, with edge flipping."""
mw, mh = measure_menu(menu, pango_ctx)
# Horizontal positioning
if not menu.right_aligned:
x = ref_x + ref_w
if x + mw > screen_w:
menu.right_aligned = True
x = ref_x - mw + SUBMENU_OVERLAP
else:
x = ref_x - mw + SUBMENU_OVERLAP
if x < 0:
menu.right_aligned = False
x = ref_x + ref_w
# Vertical positioning
if not menu.bottom_aligned:
y = ref_y
if y + mh > screen_h:
menu.bottom_aligned = True
y = ref_y + ref_h - mh
else:
y = ref_y + ref_h - mh
if y < 0:
menu.bottom_aligned = False
y = ref_y
# Clamp to screen
x = max(0, min(x, screen_w - mw))
y = max(0, min(y, screen_h - mh))
menu.box = (x, y, mw, mh)
# Position items within menu
offset_y = 0
for item in menu.items:
if item.is_separator:
item.box = (x, y + offset_y, mw, SEPARATOR_HEIGHT)
offset_y += SEPARATOR_HEIGHT
else:
item.box = (x, y + offset_y, mw, ITEM_HEIGHT)
offset_y += ITEM_HEIGHT
menu.visible = True
def configure_submenu(item, screen_w, screen_h, pango_ctx, parent_right_aligned, parent_bottom_aligned):
"""Configure a submenu, building a temporary Menu wrapper."""
if not item.children:
return None
submenu = Menu(items=item.children)
submenu.right_aligned = parent_right_aligned
submenu.bottom_aligned = parent_bottom_aligned
ix, iy, iw, ih = item.box
configure_menu(submenu, screen_w, screen_h, ix, iy, iw, ih, pango_ctx)
return submenu
# ---------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------
def draw_rounded_rect(cr, x, y, w, h, r):
"""Draw a rounded rectangle path."""
if r <= 0:
cr.rectangle(x, y, w, h)
return
cr.new_sub_path()
cr.arc(x + w - r, y + r, r, -0.5 * 3.14159, 0)
cr.arc(x + w - r, y + h - r, r, 0, 0.5 * 3.14159)
cr.arc(x + r, y + h - r, r, 0.5 * 3.14159, 3.14159)
cr.arc(x + r, y + r, r, 3.14159, 1.5 * 3.14159)
cr.close_path()
def _rgba_with_alpha(color, alpha):
"""Apply an alpha multiplier to an RGBA tuple."""
return (color[0], color[1], color[2], color[3] * alpha)
def draw_menu(cr, menu, pango_ctx, hover_item):
"""Draw a menu and its visible submenus."""
if not menu.visible:
return
mx, my, mw, mh = menu.box
menu_alpha = menu.anim_progress if ANIM_ENABLED else 1.0
# Background
draw_rounded_rect(cr, mx, my, mw, mh, BORDER_RADIUS)
cr.set_source_rgba(*_rgba_with_alpha(MENU_BG, menu_alpha))
cr.fill_preserve()
cr.set_source_rgba(*_rgba_with_alpha(MENU_BORDER, menu_alpha))
cr.set_line_width(BORDER_WIDTH)
cr.stroke()
# Clip to menu bounds for items
cr.save()
draw_rounded_rect(cr, mx, my, mw, mh, BORDER_RADIUS)
cr.clip()
has_submenu = any(item.children for item in menu.items if not item.is_separator)
icon_w = _icon_col_width(menu, pango_ctx)
for item in menu.items:
ix, iy, iw, ih = item.box
# Per-item alpha: menu fade * item cascade
item_alpha = menu_alpha * item.anim_alpha if ANIM_ENABLED else 1.0
if item.is_separator:
sep_y = iy + ih // 2
cr.set_source_rgba(*_rgba_with_alpha(SEPARATOR_FG, item_alpha))
cr.set_line_width(1)
cr.move_to(ix + 8, sep_y + 0.5)
cr.line_to(ix + iw - 8, sep_y + 0.5)
cr.stroke()
continue
# Highlight (inset by border width to avoid overlapping the border)
is_active = (item is hover_item) or item.submenu_visible
if is_active:
cr.set_source_rgba(*_rgba_with_alpha(ITEM_ACTIVE_BG, item_alpha))
inset = BORDER_WIDTH
cr.rectangle(ix + inset, iy, iw - 2 * inset, ih)
cr.fill()
fg = ITEM_ACTIVE_FG if is_active else ITEM_FG
# Text – single layout with tab stop for fixed icon column
layout = Pango.Layout.new(pango_ctx)
layout.set_font_description(Pango.FontDescription.from_string(LABEL_FONT))
icon_len = 0
if icon_w:
tabs = Pango.TabArray.new(1, True)
tabs.set_tab(0, Pango.TabAlign.LEFT, icon_w)
layout.set_tabs(tabs)
if item.icon:
text = item.icon + "\t" + item.label
icon_len = len((item.icon + "\t").encode("utf-8"))
else:
text = "\t" + item.label
else:
text = item.label
layout.set_text(text, -1)
_, text_h = layout.get_pixel_size()
text_y = iy + (ih - text_h) // 2
# Icon portion keeps the mono icon font (and its custom color, if any)
if icon_len:
attr_list = Pango.AttrList.new()
font_attr = Pango.attr_font_desc_new(
Pango.FontDescription.from_string(ICON_FONT)
)
font_attr.start_index = 0
font_attr.end_index = icon_len
attr_list.insert(font_attr)
if item.color and not is_active:
ic = item.color
r, g, b = int(ic[0] * 65535), int(ic[1] * 65535), int(ic[2] * 65535)
color_attr = Pango.attr_foreground_new(r, g, b)
color_attr.start_index = 0
color_attr.end_index = icon_len
attr_list.insert(color_attr)
layout.set_attributes(attr_list)
cr.set_source_rgba(*_rgba_with_alpha(fg, item_alpha))
cr.move_to(ix + ITEM_PADDING_X, text_y)
PangoCairo.show_layout(cr, layout)
# Submenu arrow
if item.children:
layout.set_attributes(Pango.AttrList.new())
layout.set_text(SUBMENU_ARROW, -1)
aw, _ = layout.get_pixel_size()
cr.move_to(ix + iw - ITEM_PADDING_X - aw, text_y)
PangoCairo.show_layout(cr, layout)
cr.restore()
# Draw visible submenus
for item in menu.items:
if item.submenu_visible and item.children:
submenu = Menu(items=item.children)
submenu.box = item._submenu_box
submenu.visible = True
draw_menu(cr, submenu, pango_ctx, hover_item)
# ---------------------------------------------------------------------------
# Hit testing
# ---------------------------------------------------------------------------
def find_item_at(menu, x, y):
"""Find the menu item under (x, y). Checks submenus first (depth-first)."""
if not menu.visible:
return None
# Check submenus first (they render on top)
for item in menu.items:
if item.submenu_visible and item.children:
submenu = Menu(items=item.children)
submenu.box = item._submenu_box
submenu.visible = True
found = find_item_at(submenu, x, y)
if found is not None:
return found
# Check this menu's items
mx, my, mw, mh = menu.box
if not (mx <= x < mx + mw and my <= y < my + mh):
return None
for item in menu.items:
if item.is_separator:
continue
ix, iy, iw, ih = item.box
if ix <= x < ix + iw and iy <= y < iy + ih:
return item
return None
def point_in_any_menu(menu, x, y):
"""Check if (x, y) is inside any visible menu."""
if not menu.visible:
return False
mx, my, mw, mh = menu.box
if mx <= x < mx + mw and my <= y < my + mh:
return True
for item in menu.items:
if item.submenu_visible and item.children:
submenu = Menu(items=item.children)
submenu.box = item._submenu_box
submenu.visible = True
if point_in_any_menu(submenu, x, y):
return True
return False
# ---------------------------------------------------------------------------
# Command execution
# ---------------------------------------------------------------------------
def spawn_command(command):
"""Double-fork to spawn a detached process."""
pid = os.fork()
if pid == 0:
os.setsid()
grandchild = os.fork()
if grandchild == 0:
os.execvp("/bin/sh", ["/bin/sh", "-c", command])
os._exit(0)
os.waitpid(pid, 0)
# ---------------------------------------------------------------------------
# Main application
# ---------------------------------------------------------------------------
class ClickBuffet:
def __init__(self, menu):
self.root_menu = menu
self.hover_item = None
self.positioned = False
self.screen_w = 0
self.screen_h = 0
self.pango_ctx = None
self._setup_window()
def _setup_window(self):
self.window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL)
# Layer shell setup
GtkLayerShell.init_for_window(self.window)
GtkLayerShell.set_layer(self.window, GtkLayerShell.Layer.TOP)
GtkLayerShell.set_keyboard_mode(
self.window, GtkLayerShell.KeyboardMode.ON_DEMAND
)
for edge in (
GtkLayerShell.Edge.TOP,
GtkLayerShell.Edge.BOTTOM,
GtkLayerShell.Edge.LEFT,
GtkLayerShell.Edge.RIGHT,
):
GtkLayerShell.set_anchor(self.window, edge, True)
GtkLayerShell.set_exclusive_zone(self.window, -1)
GtkLayerShell.set_namespace(self.window, "clickbuffet")
# Transparent
screen = self.window.get_screen()
visual = screen.get_rgba_visual()
if visual:
self.window.set_visual(visual)
self.window.set_app_paintable(True)
# Drawing area
self.da = Gtk.DrawingArea()
self.da.add_events(
Gdk.EventMask.POINTER_MOTION_MASK
| Gdk.EventMask.ENTER_NOTIFY_MASK
| Gdk.EventMask.BUTTON_PRESS_MASK
| Gdk.EventMask.BUTTON_RELEASE_MASK
)
self.window.add(self.da)
# Signals
self.da.connect("draw", self._on_draw)
self.da.connect("enter-notify-event", self._on_motion)
self.da.connect("motion-notify-event", self._on_motion)
self.da.connect("button-release-event", self._on_button_release)
self.window.connect("key-press-event", self._on_key_press)
self.window.connect("destroy", Gtk.main_quit)
self.window.show_all()
def _get_pango_ctx(self):
if self.pango_ctx is None:
self.pango_ctx = self.da.get_pango_context()
return self.pango_ctx
def _start_animation(self, menu):
"""Start fade-in + cascade animation for a menu."""
if not ANIM_ENABLED:
return
import time
menu.anim_progress = 0.0
menu.anim_start_time = time.monotonic()
# Reset all item alphas
for item in menu.items:
item.anim_alpha = 0.0
# Start animation tick
if menu.anim_timer:
GLib.source_remove(menu.anim_timer)
menu.anim_timer = GLib.timeout_add(ANIM_FRAME_INTERVAL_MS, self._anim_tick, menu)
def _anim_tick(self, menu):
"""Update animation state each frame."""
import time
elapsed_ms = (time.monotonic() - menu.anim_start_time) * 1000
# Overall menu fade: 0→1 over ANIM_FADE_DURATION_MS
menu.anim_progress = min(1.0, elapsed_ms / ANIM_FADE_DURATION_MS)
# Per-item cascade: each item fades in with a stagger
for i, item in enumerate(menu.items):
item_start = i * ANIM_CASCADE_DELAY_MS
item_elapsed = elapsed_ms - item_start
if item_elapsed <= 0:
item.anim_alpha = 0.0
else:
item.anim_alpha = min(1.0, item_elapsed / ANIM_FADE_DURATION_MS)
self.da.queue_draw()
# Check if animation is complete
last_item_end = len(menu.items) * ANIM_CASCADE_DELAY_MS + ANIM_FADE_DURATION_MS
if elapsed_ms >= last_item_end:
menu.anim_progress = 1.0
for item in menu.items:
item.anim_alpha = 1.0
menu.anim_timer = None
self.da.queue_draw()
return False # Stop timer
return True # Continue
def _start_animation_children(self, parent_item):
"""Animate children of a submenu parent item."""
if not ANIM_ENABLED:
return
import time
start = time.monotonic()
for child in parent_item.children:
child.anim_alpha = 0.0
def tick():
elapsed_ms = (time.monotonic() - start) * 1000
done = True
for i, child in enumerate(parent_item.children):
item_start = i * ANIM_CASCADE_DELAY_MS
item_elapsed = elapsed_ms - item_start
if item_elapsed <= 0:
child.anim_alpha = 0.0
done = False
else:
child.anim_alpha = min(1.0, item_elapsed / ANIM_FADE_DURATION_MS)
if child.anim_alpha < 1.0:
done = False
self.da.queue_draw()
if done:
for child in parent_item.children:
child.anim_alpha = 1.0
return False
return True
GLib.timeout_add(ANIM_FRAME_INTERVAL_MS, tick)
def _on_draw(self, widget, cr):
# Clear to transparent
cr.set_operator(cairo.OPERATOR_SOURCE)
cr.set_source_rgba(0, 0, 0, 0)
cr.paint()
cr.set_operator(cairo.OPERATOR_OVER)
if self.root_menu.visible:
draw_menu(cr, self.root_menu, self._get_pango_ctx(), self.hover_item)
def _on_motion(self, widget, event):
if not self.positioned:
alloc = self.da.get_allocation()
self.screen_w = alloc.width
self.screen_h = alloc.height
configure_menu(
self.root_menu,
self.screen_w,
self.screen_h,
int(event.x),
int(event.y),
0, 0,
self._get_pango_ctx(),
)
self.positioned = True
self._start_animation(self.root_menu)
self.da.queue_draw()
return
old_hover = self.hover_item
self.hover_item = find_item_at(self.root_menu, event.x, event.y)
if self.hover_item is not old_hover:
# Cancel pending submenu timers
if old_hover and old_hover.submenu_timer:
GLib.source_remove(old_hover.submenu_timer)
old_hover.submenu_timer = None
# If hovering a non-submenu item, close sibling submenus
if self.hover_item and not self.hover_item.children:
self._close_sibling_submenus(self.root_menu, self.hover_item)
# Start submenu open timer
if self.hover_item and self.hover_item.children and not self.hover_item.submenu_visible:
item = self.hover_item
item.submenu_timer = GLib.timeout_add(
SUBMENU_DELAY_MS,
self._open_submenu,
item,
)
self.da.queue_draw()
def _close_sibling_submenus(self, menu, target_item):
"""Close submenus of items that are siblings of the target."""
for item in menu.items:
if item.submenu_visible and item.children:
# Check if target is in this submenu
if self._item_in_list(item.children, target_item):
self._close_sibling_submenus(
Menu(items=item.children), target_item
)
return
# Close this submenu if target is a sibling
if target_item in menu.items:
self._close_submenu_recursive(item)
def _close_submenu_recursive(self, item):
"""Close a submenu and all its children."""
item.submenu_visible = False
if item.submenu_timer:
GLib.source_remove(item.submenu_timer)
item.submenu_timer = None
for child in item.children:
if child.submenu_visible:
self._close_submenu_recursive(child)
def _item_in_list(self, items, target):
for item in items:
if item is target:
return True
if item.children and self._item_in_list(item.children, target):
return True
return False
def _open_submenu(self, item):
"""Open a submenu for the given item."""
item.submenu_timer = None
# Close sibling submenus at the same level
parent_menu = self._find_parent_menu(self.root_menu, item)
if parent_menu:
for sibling in parent_menu.items:
if sibling is not item and sibling.submenu_visible:
self._close_submenu_recursive(sibling)
submenu = configure_submenu(
item,
self.screen_w,
self.screen_h,
self._get_pango_ctx(),
self.root_menu.right_aligned,
self.root_menu.bottom_aligned,
)
if submenu:
item.submenu_visible = True
item._submenu_box = submenu.box
# Animate the submenu
sub_menu_obj = Menu(items=item.children)
sub_menu_obj.box = submenu.box
sub_menu_obj.visible = True
self._start_animation(sub_menu_obj)
# Store animation state on children
for child in item.children:
child.anim_alpha = 0.0
self._start_animation_children(item)
self.da.queue_draw()
return False # Don't repeat timer
def _find_parent_menu(self, menu, target):
"""Find the Menu that contains the target item."""
for item in menu.items:
if item is target:
return menu
if item.children:
child_menu = Menu(items=item.children)
result = self._find_parent_menu(child_menu, target)
if result:
return result
return None
def _on_button_release(self, widget, event):
if not self.root_menu.visible:
return
item = find_item_at(self.root_menu, event.x, event.y)
if item is None:
# Clicked outside
if not point_in_any_menu(self.root_menu, event.x, event.y):
Gtk.main_quit()
return
if item.children:
# Toggle submenu on click
if item.submenu_visible:
self._close_submenu_recursive(item)
else:
self._open_submenu(item)
self.da.queue_draw()
elif item.command:
spawn_command(item.command)
Gtk.main_quit()
def _on_key_press(self, widget, event):
if event.keyval == Gdk.KEY_Escape:
Gtk.main_quit()
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description="ClickBuffet - A configurable popup launcher menu for Wayland.")
parser.add_argument("-m", "--menu-file", metavar="FILE", help="path to a menu configuration file")
parser.add_argument("--no-anim", action="store_true", help="disable animations")
parser.add_argument("config", nargs="?", help=argparse.SUPPRESS) # legacy positional arg
return parser.parse_args()
def find_config(args):
"""Find config file: --menu-file > positional arg > ~/.config/clickbuffet/menu.conf > bundled."""
for path in (args.menu_file, args.config):
if path:
path = os.path.expanduser(path)
if os.path.isfile(path):
return path
print(f"Config file not found: {path}", file=sys.stderr)
sys.exit(1)
if os.path.isfile(CONFIG_FILE):
return CONFIG_FILE
# Fallback to bundled example
for bundled in (
os.path.join(os.path.dirname(os.path.abspath(__file__)), "menu.conf"),
"/usr/share/clickbuffet/menu.conf",
):
if os.path.isfile(bundled):
return bundled
print("No config file found. Create ~/.config/clickbuffet/menu.conf", file=sys.stderr)
sys.exit(1)
def _load_anim_setting():
"""Read animation preference from settings file."""
path = os.path.join(CONFIG_DIR, "settings")
if os.path.isfile(path):
with open(path, "r") as f:
for line in f:
if line.strip().startswith("animations"):
return "true" in line.lower()
return True
def _load_str_setting(key, default):
"""Read a `key = value` string setting from the settings file."""
path = os.path.join(CONFIG_DIR, "settings")
if os.path.isfile(path):
with open(path, "r") as f:
for line in f:
if line.strip().startswith(key):
return line.split("=", 1)[1].strip()
return default
def _rgba_to_tuple(rgba, alpha_override=None):
"""Convert a Gdk.RGBA to a plain (r, g, b, a) tuple."""
a = alpha_override if alpha_override is not None else rgba.alpha
return (rgba.red, rgba.green, rgba.blue, a)
def _blend(base, overlay, t):
"""Blend two RGBA tuples: base*(1-t) + overlay*t, keeping overlay alpha."""
return (
base[0] * (1 - t) + overlay[0] * t,
base[1] * (1 - t) + overlay[1] * t,
base[2] * (1 - t) + overlay[2] * t,
overlay[3],
)
def _load_theme_colors():
"""Query the current GTK theme and set style globals accordingly."""
global MENU_BG, MENU_BORDER, ITEM_FG, ITEM_ACTIVE_BG, ITEM_ACTIVE_FG, SEPARATOR_FG
try:
# Build a hidden widget tree so we can query its StyleContext
win = Gtk.Window()
menu_bar = Gtk.MenuBar()
menu_item = Gtk.MenuItem(label="x")
menu_shell = Gtk.Menu()
menu_bar.append(menu_item)
menu_item.set_submenu(menu_shell)
win.add(menu_bar)
win.show_all()
win.hide()
ctx = menu_shell.get_style_context()
ctx.add_class("menu")
flags = Gtk.StateFlags.NORMAL
# Background
bg = ctx.get_background_color(flags)
MENU_BG = _rgba_to_tuple(bg, alpha_override=0.95)
# Foreground (text)
fg = ctx.get_color(flags)
ITEM_FG = _rgba_to_tuple(fg)
# Border: blend fg into bg at ~20%
MENU_BORDER = _blend(MENU_BG, ITEM_FG, 0.2)
# Selected / active state
ctx.set_state(Gtk.StateFlags.PRELIGHT)
sel_bg = ctx.get_background_color(Gtk.StateFlags.PRELIGHT)
sel_fg = ctx.get_color(Gtk.StateFlags.PRELIGHT)
ITEM_ACTIVE_BG = _rgba_to_tuple(sel_bg)
ITEM_ACTIVE_FG = _rgba_to_tuple(sel_fg)
# Separator: blend fg into bg at ~30%
SEPARATOR_FG = _blend(MENU_BG, ITEM_FG, 0.3)
win.destroy()
except Exception:
pass # Keep hardcoded fallbacks
def main():
global ANIM_ENABLED, ICON_FONT, LABEL_FONT
signal.signal(signal.SIGINT, signal.SIG_DFL)
args = parse_args()
if args.no_anim:
ANIM_ENABLED = False
else:
ANIM_ENABLED = _load_anim_setting()
ICON_FONT = _load_str_setting("icon_font", ICON_FONT)
LABEL_FONT = _load_str_setting("label_font", LABEL_FONT)
_load_theme_colors()
acquire_lock()
config_path = find_config(args)
menu = parse_config(config_path)
if not menu.items:
print("Menu is empty.", file=sys.stderr)
sys.exit(1)
app = ClickBuffet(menu)
Gtk.main()