Repository navigation
Expand file tree
/
Copy pathMenuBarChooser.lua
More file actions
1370 lines (1193 loc) · 43.4 KB
/
Copy pathMenuBarChooser.lua
File metadata and controls
1370 lines (1193 loc) · 43.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
local axuielement = require("hs.axuielement")
local canvas = require("hs.canvas")
local perf = require("Helpers.Performance").init("MenuBarChooser", {
maxSlowEntries = 10,
fieldValueMaxLength = 80,
logToFile = true,
logDir = hs.configdir .. "/Logs",
logFileName = "MenuBarChooser.log",
summary = {
{ key = "scannedApps", label = "apps" },
{ key = "matchedApps", label = "matchedApps" },
{ key = "items", label = "items" }
},
slow = {
app = {
thresholdMs = 20,
label = "slow app",
fields = { "phase", "app", "bundle" }
},
item = {
thresholdMs = 10,
label = "slow item",
fields = { "phase", "app", "item" }
}
}
})
local chooser = nil
local scanTimer = nil
local progressHud = nil
local debugLoggedElementCount = 0
local completedScanCount = 0
local cachedSelectionMap = nil
local SCAN_CONFIG = {
intervalSeconds = 0.002,
appsPerScanTickCold = 10, -- first scan after Hammerspoon reload, no cached choices yet
appsPerScanTickWarm = 50, -- warm scan fallback when cached choices are unavailable
appsPerScanTickCachedRefresh = 10, -- background refresh while cached choices are shown
useCachedChoicesImmediately = true,
showChooserDuringScan = true,
deferChooserItemsUntilScanComplete = false,
choiceSortMode = "queryScore", -- discovery | score | queryScore
negativeAppCacheTtlSeconds = 3600
}
local CHOOSER_LAYOUT = {
widthPercent = 60,
maxWidth = 1400,
rows = 20,
hudOverlayOnChooser = false,
hudPlacement = "searchRight", -- above | searchRight
hudHeight = 48,
hudGap = 8,
topMarginLandscape = 120
}
local ICON_CONFIG = {
snapshotMode = "off", -- off | all
snapshotPadding = 2,
snapshotSize = 18,
snapshotWideAspectLimit = 2.2,
snapshotCornerRadius = 4
}
local DEBUG = {
verboseAxDumps = false,
cacheLogs = false,
scanSummaryLogs = false,
discoveredItemLogs = false,
axTreeLogs = false,
iconLogs = false
}
local PERF_TRACE = {
semanticThresholdMs = 20,
semanticMaxLabels = 12,
metadataThresholdMs = 30
}
local SEMANTIC_NAME_INFER_EXCLUDED_APPS = {
["com.apple.TextInputMenuAgent"] = true,
TextInputMenuAgent = true
}
local function newTTLCache(defaultTTLSeconds)
local store = {}
local function now()
return os.time()
end
return {
get = function(_, key)
local entry = store[key]
if not entry then
return nil
end
if entry.expiresAt and entry.expiresAt <= now() then
store[key] = nil
return nil
end
return entry.value
end,
set = function(_, key, value, ttlSeconds)
local ttl = ttlSeconds
if ttl == nil then
ttl = defaultTTLSeconds
end
store[key] = {
value = value,
expiresAt = ttl and (now() + ttl) or nil
}
return value
end,
delete = function(_, key)
store[key] = nil
end,
clear = function(_)
store = {}
end
}
end
local negativeAppCache = newTTLCache(SCAN_CONFIG.negativeAppCacheTtlSeconds)
local NEGATIVE_APP_CACHE_MISS = "__no_menu_extras__"
local function debugLog(flag, message, ...)
if flag then
hs.printf(message, ...)
end
end
local function logCache(message, ...)
debugLog(DEBUG.cacheLogs, message, ...)
end
local function logScan(message, ...)
debugLog(DEBUG.scanSummaryLogs, message, ...)
end
local function logDiscoveredItem(message, ...)
debugLog(DEBUG.discoveredItemLogs, message, ...)
end
local function logIcon(message, ...)
debugLog(DEBUG.iconLogs, message, ...)
end
perf.resetLogFile()
local function safeApplicationPath(app)
local ok, path = pcall(function()
return app:path()
end)
if ok then
return path
end
return nil
end
local function appCacheKey(app)
return app:bundleID() or safeApplicationPath(app) or app:name()
end
local function appIdentity(app)
return {
bundleID = app:bundleID() or "",
appName = app:name() or ""
}
end
local function perfAppFields(app)
local identity = appIdentity(app)
return {
app = identity.appName ~= "" and identity.appName or "<unknown>",
bundle = identity.bundleID
}
end
local function perfItemFields(app, label)
local fields = perfAppFields(app)
fields.item = label or "-"
return fields
end
local function shouldSkipNegativeAppCache(app)
local identity = appIdentity(app)
return identity.bundleID == "com.apple.controlcenter"
or identity.bundleID == "com.apple.systemuiserver"
or identity.bundleID == "com.apple.TextInputMenuAgent"
or identity.appName == "Kontrollzentrum"
or identity.appName == "Control Center"
or identity.appName == "SystemUIServer"
or identity.appName == "TextInputMenuAgent"
end
-- Legacy / exploratory debug helpers
local function printChildren(application, children, recursive)
if not DEBUG.axTreeLogs then
return
end
for _, child in ipairs(children) do
debugElement(child,"child")
print(application:name())
print(child.AXRoleDescription)
debugMenuItem(application, child, "child")
local role = child:attributeValue("AXRole")
local subrole = child:attributeValue("AXSubrole")
if role == "AXMenuBarItem" and subrole == "AXMenuExtra" then
print("Found NSAccessibilityMenuExtrasMenuBar for application:", application:name())
--return child
end
if recursive then
local childs = child:attributeValue("AXChildren")
debugTable(childs)
if childs then
printChildren(application, childs)
end
end
end
end
local function findMenuExtrasMenuBarForApplication(app)
local bundleID = app:bundleID()
if bundleID == "com.apple.WebKit.WebContent" then
return nil
end
local cacheKey = appCacheKey(app)
local canUseNegativeCache = cacheKey and not shouldSkipNegativeAppCache(app)
if canUseNegativeCache then
local cachedValue = negativeAppCache:get(cacheKey)
if cachedValue == NEGATIVE_APP_CACHE_MISS then
logCache("[MenuBarChooser][cache] HIT negative %s", cacheKey)
return nil
end
logCache("[MenuBarChooser][cache] MISS %s", cacheKey)
end
local appElement = axuielement.applicationElement(app)
--debugElement(appElement,"appElement")
if appElement then
-- Get the menu bar element
local menuBar = appElement:attributeValue("AXExtrasMenuBar")
--debugElement(menuBar,"menuBar")
if menuBar then
if canUseNegativeCache then
negativeAppCache:delete(cacheKey)
logCache("[MenuBarChooser][cache] DELETE negative %s", cacheKey)
end
return menuBar
--local children = menuBar:attributeValue("AXChildren")
--debugTable(children, "children")
--if children then
-- --printChildren(application, children)
--end
--return children
end
end
if canUseNegativeCache then
negativeAppCache:set(cacheKey, NEGATIVE_APP_CACHE_MISS)
logCache("[MenuBarChooser][cache] STORE negative %s", cacheKey)
end
return nil
end
local function printMenuItems(menuItems)
-- Iterate over bigTable and run the method for each item
for _, menu in ipairs(menuItems) do
for _, item in ipairs(menu.children) do
debugMenuItem(menu.app, item)
end
end
end
local FuzzyMatcher = require("Helpers.FuzzyMatcher")
local function stopScanTimer()
if scanTimer then
scanTimer:stop()
scanTimer = nil
end
end
local function hideProgressHud()
if progressHud then
progressHud:hide()
progressHud:delete()
progressHud = nil
end
end
local function chooserWidthPercentForScreen(screenFrame)
local cappedPercent = (CHOOSER_LAYOUT.maxWidth / screenFrame.w) * 100
return math.min(CHOOSER_LAYOUT.widthPercent, cappedPercent)
end
local function chooserWidthForScreen(screenFrame)
return math.min(
math.floor(screenFrame.w * (CHOOSER_LAYOUT.widthPercent / 100)),
CHOOSER_LAYOUT.maxWidth
)
end
local function chooserHeight()
return 88 + (CHOOSER_LAYOUT.rows * 22)
end
local function chooserYForScreen(screenFrame, currentChooserHeight)
if screenFrame.h > screenFrame.w then
return math.floor(screenFrame.y + (screenFrame.h - currentChooserHeight) / 2)
end
return math.floor(screenFrame.y + CHOOSER_LAYOUT.topMarginLandscape)
end
local function chooserFrameForScreen(screenFrame)
local width = chooserWidthForScreen(screenFrame)
local height = chooserHeight()
return {
x = math.floor(screenFrame.x + (screenFrame.w - width) / 2),
y = chooserYForScreen(screenFrame, height),
w = width,
h = height
}
end
local function progressHudFrame()
local screenFrame = hs.screen.mainScreen():frame()
local chooserFrame = chooserFrameForScreen(screenFrame)
local hudHeight = CHOOSER_LAYOUT.hudHeight
if CHOOSER_LAYOUT.hudPlacement == "searchRight" then
local inset = 18
local width = math.floor((chooserFrame.w / 2) - inset)
return {
x = math.floor(chooserFrame.x + chooserFrame.w - width - inset),
y = math.floor(chooserFrame.y + 14),
w = width,
h = hudHeight
}
end
local y = chooserFrame.y - hudHeight - CHOOSER_LAYOUT.hudGap
if y < screenFrame.y + 8 then
y = chooserFrame.y + chooserFrame.h + CHOOSER_LAYOUT.hudGap
end
return {
x = chooserFrame.x,
y = math.floor(y),
w = chooserFrame.w,
h = hudHeight
}
end
local function ensureProgressHud()
if progressHud then
return progressHud
end
local frame = progressHudFrame()
local innerWidth = frame.w - 24
local barY = frame.h - 8
progressHud = canvas.new(frame)
progressHud:level(hs.canvas.windowLevels.overlay)
progressHud[1] = {
type = "rectangle",
action = "fill",
roundedRectRadii = { xRadius = 10, yRadius = 10 },
fillColor = { alpha = 0.94, white = 0.96 },
strokeColor = { alpha = 0.18, white = 0.42 },
strokeWidth = 1
}
progressHud[2] = {
type = "rectangle",
action = "fill",
fillColor = { alpha = 0, white = 1 },
frame = { x = 0, y = 0, w = 0, h = 0 }
}
progressHud[3] = {
type = "text",
text = "",
textSize = 1,
textColor = { white = 0, alpha = 0 },
frame = { x = 0, y = 0, w = 0, h = 0 }
}
progressHud[4] = {
type = "rectangle",
action = "fill",
fillColor = { alpha = 0, white = 1 },
frame = { x = 0, y = 0, w = 0, h = 0 }
}
progressHud[5] = {
type = "text",
text = "",
textSize = 15,
textColor = { white = 0.10, alpha = 1 },
frame = { x = 10, y = 4, w = innerWidth - 64, h = 18 }
}
progressHud[6] = {
type = "text",
text = "0%",
textSize = 12,
textColor = { white = 0.36, alpha = 1 },
frame = { x = frame.w - 54, y = 6, w = 44, h = 16 }
}
progressHud[7] = {
type = "rectangle",
action = "fill",
fillColor = { alpha = 0, white = 1 },
frame = { x = 0, y = 0, w = 0, h = 0 }
}
progressHud[8] = {
type = "text",
text = "",
textSize = 1,
textColor = { white = 0, alpha = 0 },
frame = { x = 0, y = 0, w = 0, h = 0 }
}
progressHud[9] = {
type = "rectangle",
action = "fill",
roundedRectRadii = { xRadius = 5, yRadius = 5 },
fillColor = { white = 0.72, alpha = 0.20 },
frame = { x = 10, y = barY, w = frame.w - 20, h = 4 }
}
progressHud[10] = {
type = "rectangle",
action = "fill",
roundedRectRadii = { xRadius = 5, yRadius = 5 },
fillColor = { red = 0.24, green = 0.48, blue = 0.98, alpha = 0.92 },
frame = { x = 10, y = barY, w = 0, h = 4 }
}
progressHud[11] = {
type = "text",
text = "",
textSize = 12,
textColor = { white = 0.42, alpha = 1 },
frame = { x = 10, y = 23, w = innerWidth, h = 14 }
}
progressHud:show()
return progressHud
end
local function addMenuItem(selectionMap, value)
selectionMap.menuItemsCounter = selectionMap.menuItemsCounter + 1
local key = tostring(selectionMap.menuItemsCounter)
local menuItems = selectionMap.menuItems
menuItems[key] = value
return key
end
local function newSelectionMap()
return {
chooserItems = {},
menuItems = {},
menuItemsCounter = 0
}
end
local function selectionMapFromCache(cache)
if not cache then
return nil
end
return {
chooserItems = cache.chooserItems,
menuItems = cache.menuItems,
menuItemsCounter = cache.menuItemsCounter
}
end
local function cacheSelectionMap(selectionMap)
cachedSelectionMap = {
chooserItems = selectionMap.chooserItems,
menuItems = selectionMap.menuItems,
menuItemsCounter = selectionMap.menuItemsCounter
}
end
local function safeAttributeValue(item, attributeName)
local ok, value = pcall(function()
return item:attributeValue(attributeName)
end)
if ok then
return value
end
return nil
end
local function cleanValue(value)
if value == nil then
return nil
end
if type(value) == "string" then
local trimmed = value:match("^%s*(.-)%s*$")
if trimmed == "" then
return nil
end
return trimmed
end
if type(value) == "number" or type(value) == "boolean" then
return tostring(value)
end
return nil
end
local function itemMetadataValue(item, attributeName)
local shortcutValue = cleanValue(item[attributeName])
if shortcutValue then
return shortcutValue
end
return cleanValue(safeAttributeValue(item, attributeName))
end
local function firstNonEmptyAttributeValue(item, ...)
for i = 1, select("#", ...) do
local value = cleanValue(safeAttributeValue(item, select(i, ...)))
if value then
return value
end
end
return nil
end
local function sortActionNames(names)
if not names then
return {}
end
table.sort(names, function(a, b)
if a == "AXPress" then
return true
end
if b == "AXPress" then
return false
end
return a < b
end)
return names
end
local function joinedActionNames(names)
if not names or #names == 0 then
return "-"
end
return table.concat(names, ", ")
end
local function isControlCenterApp(app)
local identity = appIdentity(app)
return identity.bundleID == "com.apple.controlcenter"
or identity.appName == "Kontrollzentrum"
or identity.appName == "Control Center"
end
local function isGenericHostApp(app)
local identity = appIdentity(app)
return identity.bundleID == "com.apple.TextInputMenuAgent"
or identity.bundleID == "com.apple.systemuiserver"
or identity.appName == "TextInputMenuAgent"
or identity.appName == "SystemUIServer"
end
local function shouldInferSemanticName(app)
local identity = appIdentity(app)
if SEMANTIC_NAME_INFER_EXCLUDED_APPS[identity.bundleID]
or SEMANTIC_NAME_INFER_EXCLUDED_APPS[identity.appName] then
return false
end
return isGenericHostApp(app)
end
local function shouldDebugFullDump(app)
return DEBUG.verboseAxDumps and isControlCenterApp(app)
end
local function choosePrimaryAction(names)
local sortedNames = sortActionNames(names)
return sortedNames[1], sortedNames
end
local function isGenericDescription(value)
local cleaned = cleanValue(value)
if not cleaned then
return true
end
local normalized = string.lower(cleaned)
return normalized == "statusmenü"
or normalized == "status menu"
or normalized == "menu extra"
end
local function isWeakLabelValue(value)
local cleaned = cleanValue(value)
if not cleaned then
return true
end
local normalized = string.lower(cleaned)
if isGenericDescription(cleaned) then
return true
end
if normalized == "<none>" or normalized == "= <none>" then
return true
end
return false
end
local function preferredLabelValue(...)
for i = 1, select("#", ...) do
local value = cleanValue(select(i, ...))
if value and not isWeakLabelValue(value) then
return value
end
end
return nil
end
local function appendSummaryDetail(parts, value)
local cleaned = cleanValue(value)
if cleaned and not isGenericDescription(cleaned) then
table.insert(parts, cleaned)
end
end
local function stripTrailingDots(value)
local cleaned = cleanValue(value)
if not cleaned then
return nil
end
cleaned = cleaned:gsub("%s*[%.…]+$", "")
return cleanValue(cleaned)
end
local function deriveGenericNameFromMenuLabel(label)
local cleaned = stripTrailingDots(label)
if not cleaned then
return nil
end
local subject = cleaned:match("^[Oo]pen%s+(.+)%s+[Ss]ettings$")
or cleaned:match("^[Oo]pen%s+(.+)%s+[Pp]references$")
if not subject then
local lower = string.lower(cleaned)
local germanStart = lower:find("einstellungen öffnen", 1, true)
if germanStart and germanStart > 1 then
subject = cleaned:sub(1, germanStart - 1)
end
end
if not subject then
return nil
end
subject = subject:gsub("[%s%-%–%—%:%·]+$", "")
return cleanValue(subject)
end
local function fallbackDisplayAppName(app)
local identity = appIdentity(app)
if identity.bundleID == "com.apple.TextInputMenuAgent" or identity.appName == "TextInputMenuAgent" then
return "Tastatur"
end
if identity.bundleID == "com.apple.systemuiserver" or identity.appName == "SystemUIServer" then
return "Systemstatus"
end
return app:name()
end
local function inferSemanticNameFromMenu(item)
local details = {
menus = 0,
menuItems = 0,
labels = {}
}
local children = safeAttributeValue(item, "AXChildren")
if not children or #children == 0 then
return nil, details
end
for _, child in ipairs(children) do
if safeAttributeValue(child, "AXRole") == "AXMenu" then
details.menus = details.menus + 1
local menuItems = safeAttributeValue(child, "AXChildren")
if menuItems and #menuItems > 0 then
details.menuItems = details.menuItems + #menuItems
for index = #menuItems, 1, -1 do
local menuLabel = firstNonEmptyAttributeValue(menuItems[index], "AXTitle", "AXDescription", "AXValue")
if #details.labels < PERF_TRACE.semanticMaxLabels then
table.insert(details.labels, string.format("#%d=%s", index, menuLabel or "<empty>"))
end
local genericName = deriveGenericNameFromMenuLabel(menuLabel)
if genericName then
details.matched = genericName
return genericName, details
end
end
end
end
end
return nil, details
end
local function semanticPerfFields(app, itemLabel, details)
local fields = perfItemFields(app, itemLabel)
local labels = table.concat(details.labels or {}, " | ")
if details.menuItems and details.menuItems > #(details.labels or {}) then
labels = labels .. string.format(" | ... +%d more", details.menuItems - #details.labels)
end
fields.menus = details.menus or 0
fields.menuItems = details.menuItems or 0
fields.matched = details.matched or "-"
fields.labels = labels ~= "" and labels or "-"
return fields
end
local function metadataPerfFields(app, itemLabel)
local fields = perfItemFields(app, itemLabel)
fields.fields = perf.values("metadata")
return fields
end
local function isZeroSizedFrame(item)
local frame = safeAttributeValue(item, "AXFrame")
if type(frame) ~= "table" then
return false
end
return (frame.w or 0) == 0 or (frame.h or 0) == 0
end
local function shouldSkipMenuItem(app, item, names)
if not names or #names == 0 then
return true
end
if not isControlCenterApp(app) then
return false
end
local identifier = itemMetadataValue(item, "AXIdentifier")
local enabled = safeAttributeValue(item, "AXEnabled")
if identifier then
return false
end
if enabled == false then
return true
end
if isZeroSizedFrame(item) then
return true
end
return false
end
local function screenContainingFrame(frame)
if type(frame) ~= "table" then
return nil
end
local centerX = (frame.x or 0) + ((frame.w or 0) / 2)
local centerY = (frame.y or 0) + ((frame.h or 0) / 2)
for _, screen in ipairs(hs.screen.allScreens()) do
local fullFrame = screen:fullFrame()
if centerX >= fullFrame.x and centerX <= (fullFrame.x + fullFrame.w)
and centerY >= fullFrame.y and centerY <= (fullFrame.y + fullFrame.h) then
return screen, fullFrame
end
end
return nil
end
local backgroundColorForSnapshotImage
local function shouldUseSnapshotForApp(app)
return ICON_CONFIG.snapshotMode ~= "off" and (isControlCenterApp(app) or isGenericHostApp(app))
end
local function snapshotRectForMenuBarFrame(frame, screenFrame)
local padding = ICON_CONFIG.snapshotPadding
return {
x = math.max(0, math.floor((frame.x or 0) - screenFrame.x - padding)),
y = math.max(0, math.floor((frame.y or 0) - screenFrame.y - padding)),
w = math.floor((frame.w or 0) + (padding * 2)),
h = math.floor((frame.h or 0) + (padding * 2))
}
end
local function menuBarSnapshotImageForItem(item, debugLabel)
local frame = safeAttributeValue(item, "AXFrame")
if type(frame) ~= "table" or (frame.w or 0) <= 0 or (frame.h or 0) <= 0 then
logIcon("[MenuBarChooser][icon] snapshot skipped %s reason=invalid-frame", debugLabel or "-")
return nil
end
-- Skip wide textual menu bar items like the clock/date because they don't produce a usable icon.
if (frame.w or 0) > ((frame.h or 0) * ICON_CONFIG.snapshotWideAspectLimit) then
logIcon(
"[MenuBarChooser][icon] snapshot skipped %s reason=wide-frame frame=%dx%d",
debugLabel or "-",
math.floor(frame.w or 0),
math.floor(frame.h or 0)
)
return nil
end
local screen, screenFrame = screenContainingFrame(frame)
if not screen then
logIcon("[MenuBarChooser][icon] snapshot skipped %s reason=no-screen", debugLabel or "-")
return nil
end
local snapshotRect = snapshotRectForMenuBarFrame(frame, screenFrame)
local snapshot = screen:snapshot(snapshotRect)
if not snapshot then
logIcon("[MenuBarChooser][icon] snapshot failed %s rect=%dx%d", debugLabel or "-", snapshotRect.w, snapshotRect.h)
return nil
end
local sizedSnapshot = snapshot:setSize({ w = ICON_CONFIG.snapshotSize, h = ICON_CONFIG.snapshotSize }, false)
local snapshotSize = sizedSnapshot:size()
local rawSnapshotSize = snapshot:size()
logIcon(
"[MenuBarChooser][icon] snapshot ok %s frame=%dx%d rect=%dx%d raw=%dx%d sized=%dx%d",
debugLabel or "-",
math.floor(frame.w or 0),
math.floor(frame.h or 0),
snapshotRect.w,
snapshotRect.h,
math.floor(rawSnapshotSize.w or 0),
math.floor(rawSnapshotSize.h or 0),
math.floor(snapshotSize.w or 0),
math.floor(snapshotSize.h or 0)
)
return {
image = sizedSnapshot,
backgroundColor = backgroundColorForSnapshotImage(snapshot)
}
end
local function averageColorForImagePoints(image, points)
local redSum = 0
local greenSum = 0
local blueSum = 0
local alphaSum = 0
local measuredCount = 0
for _, point in ipairs(points) do
local color = image:colorAt(point)
if color then
redSum = redSum + (color.red or color.white or 0)
greenSum = greenSum + (color.green or color.white or 0)
blueSum = blueSum + (color.blue or color.white or 0)
alphaSum = alphaSum + (color.alpha or 1)
measuredCount = measuredCount + 1
end
end
if measuredCount == 0 then
return { white = 1, alpha = 1 }
end
return {
red = redSum / measuredCount,
green = greenSum / measuredCount,
blue = blueSum / measuredCount,
alpha = alphaSum / measuredCount
}
end
backgroundColorForSnapshotImage = function(image)
local size = image:size()
local samplePoints = {
{ x = 1, y = 1 },
{ x = math.max(1, math.floor(size.w / 2)), y = 1 },
{ x = math.max(1, math.floor(size.w - 2)), y = 1 },
{ x = 1, y = math.max(1, math.floor(size.h - 2)) },
{ x = math.max(1, math.floor(size.w - 2)), y = math.max(1, math.floor(size.h - 2)) }
}
return averageColorForImagePoints(image, samplePoints)
end
local function roundedChoiceImage(image, backgroundColor)
local iconCanvas = canvas.new({ x = 0, y = 0, w = ICON_CONFIG.snapshotSize, h = ICON_CONFIG.snapshotSize })
iconCanvas[1] = {
type = "rectangle",
action = "clip",
roundedRectRadii = { xRadius = ICON_CONFIG.snapshotCornerRadius, yRadius = ICON_CONFIG.snapshotCornerRadius },
frame = { x = 0, y = 0, w = ICON_CONFIG.snapshotSize, h = ICON_CONFIG.snapshotSize }
}
iconCanvas[2] = {
type = "rectangle",
action = "fill",
fillColor = backgroundColor,
frame = { x = 0, y = 0, w = ICON_CONFIG.snapshotSize, h = ICON_CONFIG.snapshotSize }
}
iconCanvas[3] = {
type = "image",
image = image,
frame = { x = 0, y = 0, w = ICON_CONFIG.snapshotSize, h = ICON_CONFIG.snapshotSize },
imageScaling = "scaleProportionally"
}
local roundedImage = iconCanvas:imageFromCanvas()
iconCanvas:delete()
return roundedImage
end
local function snapshotChoiceImageForHostApp(app, item, debugLabel)
if not shouldUseSnapshotForApp(app) then
return nil
end
local snapshotInfo = menuBarSnapshotImageForItem(item, debugLabel)
if snapshotInfo then
logIcon("[MenuBarChooser][icon] using snapshot %s", debugLabel or "-")
return roundedChoiceImage(snapshotInfo.image, snapshotInfo.backgroundColor)
end
return nil
end
local function fallbackChoiceImageForApp(app, debugLabel)
local bundleID = app:bundleID()
if bundleID then
logIcon("[MenuBarChooser][icon] using bundle fallback %s bundle=%s", debugLabel or "-", bundleID)
return hs.image.imageFromAppBundle(bundleID)
end
local path = safeApplicationPath(app)
if path then
logIcon("[MenuBarChooser][icon] using file fallback %s path=%s", debugLabel or "-", path)
return hs.image.iconForFile(path)
end
logIcon("[MenuBarChooser][icon] no image %s", debugLabel or "-")
return nil
end
local function preferredChoiceImage(app, item, debugLabel)
return snapshotChoiceImageForHostApp(app, item, debugLabel) or fallbackChoiceImageForApp(app, debugLabel)
end
local function collectMenuItemMetadata(item)
local function readMetadata(name, attributeName)
return perf.value("metadata", name, function()
return itemMetadataValue(item, attributeName)
end)
end
local metadata = {
identifier = readMetadata("identifier", "AXIdentifier"),
description = readMetadata("description", "AXDescription"),
value = readMetadata("value", "AXValue")
}
metadata.label = preferredLabelValue(metadata.description)
if not metadata.label then
metadata.title = readMetadata("title", "AXTitle")
metadata.label = preferredLabelValue(metadata.title)
end
if not metadata.label then
metadata.valueDescription = readMetadata("valueDescription", "AXValueDescription")
metadata.label = preferredLabelValue(metadata.valueDescription)
end
if not metadata.label then
metadata.help = readMetadata("help", "AXHelp")
metadata.label = preferredLabelValue(metadata.help)
end
metadata.derivedLabel = deriveGenericNameFromMenuLabel(metadata.label)
return metadata