-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmenuet.m
More file actions
1246 lines (1153 loc) · 45.9 KB
/
Copy pathmenuet.m
File metadata and controls
1246 lines (1153 loc) · 45.9 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
#import <Cocoa/Cocoa.h>
#import <UserNotifications/UserNotifications.h>
#import <Carbon/Carbon.h>
#import <ServiceManagement/ServiceManagement.h>
#import <CommonCrypto/CommonDigest.h>
#import "NSImage+Resize.h"
#import "menuet.h"
void hotkeyFired(uint32_t id);
// SMAppService is macOS 13+. The wrapper functions return:
// -1 = API unavailable on this macOS
// 0 = success / not registered
// 1 = registered / requires user approval
// 2 = registration error (e.g. unsigned bundle — caller should fall back)
// 3 = not found (status only)
int menuetSMAppServiceRegister(void) {
if (@available(macOS 13.0, *)) {
SMAppService *service = [SMAppService mainAppService];
NSError *err = nil;
BOOL ok = [service registerAndReturnError:&err];
if (ok) return 0;
if (err) {
NSLog(@"menuet: SMAppService register failed: %@", err);
}
return 2;
}
return -1;
}
int menuetSMAppServiceUnregister(void) {
if (@available(macOS 13.0, *)) {
SMAppService *service = [SMAppService mainAppService];
NSError *err = nil;
BOOL ok = [service unregisterAndReturnError:&err];
if (ok) return 0;
if (err) {
NSLog(@"menuet: SMAppService unregister failed: %@", err);
}
return 2;
}
return -1;
}
int menuetSMAppServiceStatus(void) {
if (@available(macOS 13.0, *)) {
SMAppService *service = [SMAppService mainAppService];
switch (service.status) {
case SMAppServiceStatusEnabled: return 1;
case SMAppServiceStatusRequiresApproval: return 1;
case SMAppServiceStatusNotRegistered: return 0;
case SMAppServiceStatusNotFound: return 3;
}
return 0;
}
return -1;
}
void itemClicked(const char *);
void notificationRespond(const char *, const char *);
const char *children(const char *);
const char *searchResults(const char *, const char *);
void menuClosed(const char *);
bool hideStartup();
char *startAtLoginLabel();
char *quitLabel();
bool runningAtStartup();
void toggleStartup();
void shutdownWait();
void initNotifications(void);
bool hasTopLevelClicked();
void topLevelClicked();
// Tag applied to dynamically-inserted search result NSMenuItems. populate:
// clears items with this tag before rebuilding so a menu refresh doesn't
// confuse search results with user-supplied items.
#define MENUET_SEARCH_RESULT_TAG 31337
// Global-hotkey Carbon plumbing. Each Shortcut registered from Go gets an
// EventHotKeyRef stored here keyed by the Go-assigned uint32 ID, so we can
// unregister on demand. The shared event handler dispatches incoming
// kEventHotKeyPressed events back into Go via hotkeyFired().
static NSMutableDictionary<NSNumber *, NSValue *> *MenuetHotkeyRefs;
static EventHandlerRef MenuetHotkeyHandler;
static OSStatus MenuetHotkeyEventCallback(EventHandlerCallRef handler,
EventRef event,
void *userData) {
EventHotKeyID id;
OSStatus status = GetEventParameter(event, kEventParamDirectObject,
typeEventHotKeyID, NULL,
sizeof(id), NULL, &id);
if (status != noErr) return status;
hotkeyFired(id.id);
return noErr;
}
static void MenuetEnsureHotkeyHandler(void) {
if (MenuetHotkeyHandler) return;
MenuetHotkeyRefs = [NSMutableDictionary new];
EventTypeSpec evt = { kEventClassKeyboard, kEventHotKeyPressed };
InstallApplicationEventHandler(MenuetHotkeyEventCallback, 1, &evt,
NULL, &MenuetHotkeyHandler);
}
void registerHotkey(uint32_t goID, uint32_t keyCode, uint32_t modifiers) {
dispatch_async(dispatch_get_main_queue(), ^{
MenuetEnsureHotkeyHandler();
EventHotKeyID hkID = { .signature = 'menu', .id = goID };
EventHotKeyRef ref = NULL;
OSStatus status = RegisterEventHotKey(keyCode, modifiers, hkID,
GetApplicationEventTarget(),
0, &ref);
if (status != noErr) {
NSLog(@"menuet: RegisterEventHotKey failed (status=%d) for id=%u",
(int)status, goID);
return;
}
MenuetHotkeyRefs[@(goID)] = [NSValue valueWithPointer:ref];
});
}
void unregisterHotkey(uint32_t goID) {
dispatch_async(dispatch_get_main_queue(), ^{
NSValue *boxed = MenuetHotkeyRefs[@(goID)];
if (!boxed) return;
EventHotKeyRef ref = (EventHotKeyRef)boxed.pointerValue;
UnregisterEventHotKey(ref);
[MenuetHotkeyRefs removeObjectForKey:@(goID)];
});
}
@class MenuetMenu;
NSStatusItem *_statusItem;
MenuetMenu *_rootMenu;
@interface MenuetSearchView : NSView <NSSearchFieldDelegate>
@property(nonatomic, strong) NSSearchField *field;
@property(nonatomic, copy) NSString *searchUnique;
@property(nonatomic, copy) NSString *savedQuery;
@property(nonatomic, assign) NSMenu *trackingMenu;
- (instancetype)initWithPlaceholder:(NSString *)placeholder
searchUnique:(NSString *)searchUnique;
- (void)updatePlaceholder:(NSString *)placeholder searchUnique:(NSString *)unique;
- (void)applyQuery:(NSString *)query;
@end
@interface MenuetMenu : NSMenu <NSMenuDelegate>
@property(nonatomic, copy) NSString *unique;
@property(nonatomic, assign) BOOL root;
@property(nonatomic, assign) BOOL open;
@end
// Convert one of Apple's virtual key codes (the same KeyCode values our
// Go-side Key constants use) to the NSString form NSMenuItem.keyEquivalent
// expects. Returns @"" for codes we don't have a printable mapping for.
static NSString *MenuetKeyEquivalentStringForCode(int keyCode) {
// Letter keys, layout-independent — match the Go-side constants.
switch (keyCode) {
case 0: return @"a";
case 11: return @"b";
case 8: return @"c";
case 2: return @"d";
case 14: return @"e";
case 3: return @"f";
case 5: return @"g";
case 4: return @"h";
case 34: return @"i";
case 38: return @"j";
case 40: return @"k";
case 37: return @"l";
case 46: return @"m";
case 45: return @"n";
case 31: return @"o";
case 35: return @"p";
case 12: return @"q";
case 15: return @"r";
case 1: return @"s";
case 17: return @"t";
case 32: return @"u";
case 9: return @"v";
case 13: return @"w";
case 7: return @"x";
case 16: return @"y";
case 6: return @"z";
case 29: return @"0";
case 18: return @"1";
case 19: return @"2";
case 20: return @"3";
case 21: return @"4";
case 23: return @"5";
case 22: return @"6";
case 26: return @"7";
case 28: return @"8";
case 25: return @"9";
case 49: return @" "; // space
case 36: return [NSString stringWithFormat:@"%C", (unichar)NSCarriageReturnCharacter];
case 48: return @"\t";
case 53: return [NSString stringWithFormat:@"%C", (unichar)0x1B]; // escape
case 122: return [NSString stringWithFormat:@"%C", (unichar)NSF1FunctionKey];
case 120: return [NSString stringWithFormat:@"%C", (unichar)NSF2FunctionKey];
case 99: return [NSString stringWithFormat:@"%C", (unichar)NSF3FunctionKey];
case 118: return [NSString stringWithFormat:@"%C", (unichar)NSF4FunctionKey];
case 96: return [NSString stringWithFormat:@"%C", (unichar)NSF5FunctionKey];
case 97: return [NSString stringWithFormat:@"%C", (unichar)NSF6FunctionKey];
case 98: return [NSString stringWithFormat:@"%C", (unichar)NSF7FunctionKey];
case 100: return [NSString stringWithFormat:@"%C", (unichar)NSF8FunctionKey];
case 101: return [NSString stringWithFormat:@"%C", (unichar)NSF9FunctionKey];
case 109: return [NSString stringWithFormat:@"%C", (unichar)NSF10FunctionKey];
case 103: return [NSString stringWithFormat:@"%C", (unichar)NSF11FunctionKey];
case 111: return [NSString stringWithFormat:@"%C", (unichar)NSF12FunctionKey];
case 123: return [NSString stringWithFormat:@"%C", (unichar)NSLeftArrowFunctionKey];
case 124: return [NSString stringWithFormat:@"%C", (unichar)NSRightArrowFunctionKey];
case 125: return [NSString stringWithFormat:@"%C", (unichar)NSDownArrowFunctionKey];
case 126: return [NSString stringWithFormat:@"%C", (unichar)NSUpArrowFunctionKey];
}
return @"";
}
// Convert the Carbon-bit modifier mask we use in Go to the AppKit
// NSEventModifierFlag bits NSMenuItem.keyEquivalentModifierMask expects.
static NSEventModifierFlags MenuetModifierMaskFromCarbon(uint32_t carbon) {
NSEventModifierFlags mask = 0;
if (carbon & cmdKey) mask |= NSEventModifierFlagCommand;
if (carbon & shiftKey) mask |= NSEventModifierFlagShift;
if (carbon & optionKey) mask |= NSEventModifierFlagOption;
if (carbon & controlKey) mask |= NSEventModifierFlagControl;
return mask;
}
// Build an NSAttributedString for a menu item's title. If runs is non-nil
// and non-empty, each run is appended with its own per-segment attributes
// (color, font size, weight, monospace). Otherwise the whole title is
// styled with the item-level attributes.
//
// A run's zero-value Color/FontSize/FontWeight means "inherit from the
// item-level value" so callers can change just one attribute per run
// without re-specifying the rest.
// Map a Color.Semantic string to an AppKit dynamic NSColor that re-
// resolves per appearance. Returns nil for unknown names so callers
// fall through to the RGBA path.
static NSColor *MenuetColorFromSemantic(NSString *name) {
if (name.length == 0) return nil;
if ([name isEqualToString:@"labelColor"]) return [NSColor labelColor];
if ([name isEqualToString:@"secondaryLabelColor"]) return [NSColor secondaryLabelColor];
if ([name isEqualToString:@"tertiaryLabelColor"]) return [NSColor tertiaryLabelColor];
if ([name isEqualToString:@"quaternaryLabelColor"]) return [NSColor quaternaryLabelColor];
if ([name isEqualToString:@"systemRedColor"]) return [NSColor systemRedColor];
if ([name isEqualToString:@"systemGreenColor"]) return [NSColor systemGreenColor];
if ([name isEqualToString:@"systemYellowColor"]) return [NSColor systemYellowColor];
if ([name isEqualToString:@"systemBlueColor"]) return [NSColor systemBlueColor];
if ([name isEqualToString:@"systemOrangeColor"]) return [NSColor systemOrangeColor];
if ([name isEqualToString:@"systemPurpleColor"]) return [NSColor systemPurpleColor];
if ([name isEqualToString:@"systemPinkColor"]) return [NSColor systemPinkColor];
if ([name isEqualToString:@"systemGrayColor"]) return [NSColor systemGrayColor];
if ([name isEqualToString:@"systemBrownColor"]) return [NSColor systemBrownColor];
if ([name isEqualToString:@"systemTealColor"]) return [NSColor systemTealColor];
if ([name isEqualToString:@"systemIndigoColor"]) return [NSColor systemIndigoColor];
if ([name isEqualToString:@"systemMintColor"]) {
if (@available(macOS 12.0, *)) return [NSColor systemMintColor];
}
if ([name isEqualToString:@"systemCyanColor"]) {
if (@available(macOS 12.0, *)) return [NSColor systemCyanColor];
}
return nil;
}
static NSColor *MenuetColorFromDict(NSDictionary *dict) {
if (!dict) return nil;
NSColor *semantic = MenuetColorFromSemantic(dict[@"Semantic"]);
if (semantic) return semantic;
NSNumber *r = dict[@"R"];
NSNumber *g = dict[@"G"];
NSNumber *b = dict[@"B"];
NSNumber *a = dict[@"A"];
if (!r || !g || !b || !a) return nil;
if (r.intValue == 0 && g.intValue == 0 && b.intValue == 0 && a.intValue == 0) {
return nil;
}
return [NSColor colorWithRed:r.floatValue / 255.0
green:g.floatValue / 255.0
blue:b.floatValue / 255.0
alpha:a.floatValue / 255.0];
}
// Pre-render a rounded-pill badge for a TextRun{Badge: true}: rounded
// rectangle filled with fillColor, with the text drawn in white-on-fill
// at 9pt bold uppercase. The image's size matches the badge geometry
// from the design handoff (h14, padX5, radius7).
// ---------------------------------------------------------------------------
// Image menu rows (the "image" item type).
//
// Decoding and rescaling a full-size screenshot on every menu open is the
// expensive part, so results are cached. The cache key must change when the
// picture does: for Data that's a digest of the bytes, for Path it's the
// path plus its modification time (a screenshot rewritten to the same path
// must not serve the stale image).
// ---------------------------------------------------------------------------
static const CGFloat kMenuetImagePadX = 20; // roughly the menu's text inset
static const CGFloat kMenuetImagePadY = 5;
static NSCache *MenuetImageCache(void) {
static NSCache *cache;
static dispatch_once_t once;
dispatch_once(&once, ^{
cache = [[NSCache alloc] init];
cache.countLimit = 32;
});
return cache;
}
static NSString *MenuetSHA256Hex(NSData *data) {
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.bytes, (CC_LONG)data.length, digest);
NSMutableString *hex = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[hex appendFormat:@"%02x", digest[i]];
}
return hex;
}
// Scale to fit inside maxW x maxH, preserving aspect ratio. Never upscales —
// a 32pt avatar in a 480pt box stays 32pt rather than turning to mush.
static NSImage *MenuetScaledImage(NSImage *src, CGFloat maxW, CGFloat maxH) {
if (!src || !src.isValid) {
return nil;
}
NSSize size = src.size;
if (size.width <= 0 || size.height <= 0) {
return nil;
}
CGFloat scale = 1.0;
if (maxW > 0 && size.width > maxW) {
scale = MIN(scale, maxW / size.width);
}
if (maxH > 0 && size.height > maxH) {
scale = MIN(scale, maxH / size.height);
}
if (scale >= 1.0) {
return src;
}
NSSize newSize = NSMakeSize(floor(size.width * scale), floor(size.height * scale));
NSImage *out = [[NSImage alloc] initWithSize:newSize];
[out lockFocus];
[[NSGraphicsContext currentContext]
setImageInterpolation:NSImageInterpolationHigh];
[src drawInRect:NSMakeRect(0, 0, newSize.width, newSize.height)
fromRect:NSZeroRect
operation:NSCompositingOperationSourceOver
fraction:1.0];
[out unlockFocus];
return out;
}
// MenuetImageForRow returns the decoded, scaled image for a row, cached.
// b64 is the still-encoded ImageData payload: hashing it directly (rather
// than the decoded bytes) has identical uniqueness but defers the ~1MB
// base64 decode to the cache-miss path, keeping repeat menu opens cheap.
// Failures are cached too (as NSNull), so a broken source is decoded — and
// logged — once, not on every open.
static NSImage *MenuetImageForRow(NSString *b64, NSString *path, CGFloat maxW, CGFloat maxH) {
NSString *key = nil;
if (b64.length > 0) {
NSData *keyBytes = [b64 dataUsingEncoding:NSUTF8StringEncoding];
key = [NSString stringWithFormat:@"d:%@/%.0fx%.0f",
MenuetSHA256Hex(keyBytes), maxW, maxH];
} else if (path.length > 0) {
NSDictionary *attrs =
[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
NSDate *mtime = attrs[NSFileModificationDate];
key = [NSString stringWithFormat:@"p:%@/%f/%.0fx%.0f", path,
mtime.timeIntervalSince1970, maxW, maxH];
} else {
return nil;
}
id cached = [MenuetImageCache() objectForKey:key];
if (cached) {
return cached == [NSNull null] ? nil : cached;
}
NSImage *scaled = nil;
NSData *data = b64.length > 0
? [[NSData alloc] initWithBase64EncodedString:b64 options:0]
: nil;
NSImage *src = data
? [[NSImage alloc] initWithData:data]
: [[NSImage alloc] initWithContentsOfFile:path];
if (src) {
scaled = MenuetScaledImage(src, maxW, maxH);
}
if (scaled) {
[MenuetImageCache() setObject:scaled forKey:key];
} else {
NSLog(@"menuet: could not decode image (%@)",
b64.length > 0 ? @"Data" : path);
[MenuetImageCache() setObject:[NSNull null] forKey:key];
}
return scaled;
}
// MenuetImageView is an NSMenuItem.view that draws a picture as the row. Same
// mechanism as the search field. A custom view gets none of NSMenuItem's
// highlight or click behavior for free, so when the row is clickable we track
// the pointer ourselves, draw the selection background, and on mouseUp fire
// the item's action and dismiss the menu.
@interface MenuetImageView : NSView
@property(nonatomic, strong) NSImage *image;
@property(nonatomic, assign) BOOL clickable;
@property(nonatomic, assign) BOOL hovered;
@property(nonatomic, strong) NSTrackingArea *tracking;
- (instancetype)initWithImage:(NSImage *)image clickable:(BOOL)clickable;
- (void)updateImage:(NSImage *)image clickable:(BOOL)clickable;
@end
@implementation MenuetImageView
- (instancetype)initWithImage:(NSImage *)image clickable:(BOOL)clickable {
self = [super initWithFrame:NSZeroRect];
if (self) {
[self updateImage:image clickable:clickable];
}
return self;
}
- (void)updateImage:(NSImage *)image clickable:(BOOL)clickable {
self.image = image;
self.clickable = clickable;
// The menu can be dismissed (cancelTracking) with the pointer still over
// this row, in which case mouseExited never arrives — reset here so a
// reused view doesn't draw a phantom highlight on the next open.
self.hovered = NO;
NSSize size = image ? image.size : NSMakeSize(120, 60);
NSRect frame = self.frame;
frame.size = NSMakeSize(size.width + 2 * kMenuetImagePadX,
size.height + 2 * kMenuetImagePadY);
self.frame = frame;
[self setNeedsDisplay:YES];
}
- (void)updateTrackingAreas {
[super updateTrackingAreas];
if (self.tracking) {
[self removeTrackingArea:self.tracking];
}
// ActiveAlways, not ActiveInActiveApp: menuet apps are accessory-policy
// apps whose status-item menu opens without activating the app, so
// ActiveInActiveApp would never deliver enter/exit while another app is
// frontmost — i.e. in the normal menubar usage.
self.tracking = [[NSTrackingArea alloc]
initWithRect:self.bounds
options:NSTrackingMouseEnteredAndExited |
NSTrackingActiveAlways
owner:self
userInfo:nil];
[self addTrackingArea:self.tracking];
}
- (void)mouseEntered:(NSEvent *)event {
if (self.clickable && !self.hovered) {
self.hovered = YES;
[self setNeedsDisplay:YES];
}
}
- (void)mouseExited:(NSEvent *)event {
if (self.hovered) {
self.hovered = NO;
[self setNeedsDisplay:YES];
}
}
- (void)mouseUp:(NSEvent *)event {
if (!self.clickable) {
return;
}
NSMenuItem *item = self.enclosingMenuItem;
if (item.action) {
[NSApp sendAction:item.action to:item.target from:item];
}
[item.menu cancelTracking];
}
- (void)drawRect:(NSRect)dirtyRect {
if (self.clickable && self.hovered) {
[[NSColor selectedContentBackgroundColor] setFill];
NSRect r = NSInsetRect(self.bounds, 5, 1);
[[NSBezierPath bezierPathWithRoundedRect:r xRadius:5 yRadius:5] fill];
}
if (!self.image) {
return;
}
[self.image drawInRect:NSMakeRect(kMenuetImagePadX, kMenuetImagePadY,
self.image.size.width,
self.image.size.height)
fromRect:NSZeroRect
operation:NSCompositingOperationSourceOver
fraction:1.0];
}
@end
static NSImage *MenuetBadgeImage(NSString *text, NSColor *fillColor) {
NSString *upper = [text uppercaseString];
NSDictionary *attrs = @{
NSFontAttributeName: [NSFont boldSystemFontOfSize:9],
NSForegroundColorAttributeName: [NSColor whiteColor],
NSKernAttributeName: @(0.4),
};
NSSize textSize = [upper sizeWithAttributes:attrs];
CGFloat width = ceil(textSize.width) + 10; // 5pt padding each side
CGFloat height = 14;
NSImage *img = [[NSImage alloc] initWithSize:NSMakeSize(width, height)];
[img lockFocus];
NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:NSMakeRect(0, 0, width, height)
xRadius:7
yRadius:7];
[(fillColor ?: [NSColor tertiaryLabelColor]) setFill];
[path fill];
[upper drawAtPoint:NSMakePoint(5, (height - textSize.height) / 2.0)
withAttributes:attrs];
[img unlockFocus];
return img;
}
static NSFont *MenuetFont(CGFloat size, CGFloat weight, BOOL mono) {
if (size <= 0) size = 14;
if (mono) {
return [NSFont monospacedSystemFontOfSize:size weight:weight];
}
return [NSFont monospacedDigitSystemFontOfSize:size weight:weight];
}
static NSAttributedString *MenuetBuildAttributedTitle(NSString *text,
NSArray *runs,
CGFloat itemFontSize,
CGFloat itemFontWeight,
NSDictionary *itemColorDict,
BOOL itemMono) {
NSColor *itemColor = MenuetColorFromDict(itemColorDict);
if (![runs isKindOfClass:[NSArray class]] || runs.count == 0) {
NSMutableDictionary *attrs = [NSMutableDictionary new];
attrs[NSFontAttributeName] = MenuetFont(itemFontSize, itemFontWeight, itemMono);
if (itemColor) attrs[NSForegroundColorAttributeName] = itemColor;
return [[NSAttributedString alloc] initWithString:(text ?: @"") attributes:attrs];
}
NSMutableAttributedString *result = [NSMutableAttributedString new];
for (NSDictionary *run in runs) {
if (![run isKindOfClass:[NSDictionary class]]) continue;
NSString *segText = run[@"Text"] ?: @"";
if (segText.length == 0) continue;
// Badge: render as a rounded-pill image attachment in line.
if ([run[@"Badge"] boolValue]) {
NSColor *fill = MenuetColorFromDict(run[@"Color"]) ?: [NSColor tertiaryLabelColor];
NSTextAttachment *attachment = [NSTextAttachment new];
attachment.image = MenuetBadgeImage(segText, fill);
[result appendAttributedString:
[NSAttributedString attributedStringWithAttachment:attachment]];
continue;
}
NSNumber *fsNum = run[@"FontSize"];
NSNumber *fwNum = run[@"FontWeight"];
BOOL runMono = [run[@"Monospaced"] boolValue] || itemMono;
CGFloat fs = fsNum.intValue > 0 ? fsNum.floatValue : itemFontSize;
CGFloat fw = fwNum.floatValue != 0 ? fwNum.floatValue : itemFontWeight;
NSColor *runColor = MenuetColorFromDict(run[@"Color"]) ?: itemColor;
NSMutableDictionary *attrs = [NSMutableDictionary new];
attrs[NSFontAttributeName] = MenuetFont(fs, fw, runMono);
if (runColor) attrs[NSForegroundColorAttributeName] = runColor;
if ([run[@"Underline"] boolValue]) {
attrs[NSUnderlineStyleAttributeName] = @(NSUnderlineStyleSingle);
NSColor *uc = MenuetColorFromDict(run[@"UnderlineColor"]);
if (uc) attrs[NSUnderlineColorAttributeName] = uc;
}
if ([run[@"Strikethrough"] boolValue]) {
attrs[NSStrikethroughStyleAttributeName] = @(NSUnderlineStyleSingle);
NSColor *sc = MenuetColorFromDict(run[@"StrikethroughColor"]);
if (sc) attrs[NSStrikethroughColorAttributeName] = sc;
}
NSColor *bg = MenuetColorFromDict(run[@"Background"]);
if (bg) attrs[NSBackgroundColorAttributeName] = bg;
NSDictionary *shadowDict = run[@"Shadow"];
if ([shadowDict isKindOfClass:[NSDictionary class]]) {
NSShadow *shadow = [NSShadow new];
NSColor *shadowColor = MenuetColorFromDict(shadowDict[@"Color"]);
shadow.shadowColor = shadowColor ?: [NSColor colorWithWhite:0 alpha:0.6];
shadow.shadowBlurRadius = [shadowDict[@"Blur"] doubleValue];
shadow.shadowOffset = NSMakeSize([shadowDict[@"OffsetX"] doubleValue],
[shadowDict[@"OffsetY"] doubleValue]);
attrs[NSShadowAttributeName] = shadow;
}
[result appendAttributedString:[[NSAttributedString alloc] initWithString:segText
attributes:attrs]];
}
return result;
}
// Concatenate just the text content of a Runs array — useful when the
// platform's native subtitle slot only accepts a plain string.
static NSString *MenuetPlainTextFromRuns(NSArray *runs) {
if (![runs isKindOfClass:[NSArray class]] || runs.count == 0) return nil;
NSMutableString *out = [NSMutableString new];
for (NSDictionary *run in runs) {
if (![run isKindOfClass:[NSDictionary class]]) continue;
NSString *t = run[@"Text"] ?: @"";
[out appendString:t];
}
return out;
}
@implementation MenuetMenu
- (id)init {
self = [super init];
if (self) {
self.delegate = self;
self.autoenablesItems = false;
}
return self;
}
- (void)refreshVisibleMenus {
if (!self.open) {
return;
}
[self menuWillOpen:self];
for (NSMenuItem *item in self.itemArray) {
MenuetMenu *menu = (MenuetMenu *)item.submenu;
if (menu != NULL) {
[menu refreshVisibleMenus];
}
}
}
- (void)populate:(NSArray *)items {
// Search-result items are inserted dynamically by MenuetSearchView and
// aren't part of the user's children() output. Pull them out first so
// the index-keyed reuse below doesn't confuse them with user items.
NSMutableArray<NSMenuItem *> *staleResults = [NSMutableArray new];
for (NSMenuItem *existing in self.itemArray) {
if (existing.tag == MENUET_SEARCH_RESULT_TAG) {
[staleResults addObject:existing];
}
}
for (NSMenuItem *r in staleResults) {
[self removeItem:r];
}
for (int i = 0; i < items.count; i++) {
NSMenuItem *item = nil;
if (i < self.numberOfItems) {
item = [self itemAtIndex:i];
}
NSDictionary *dict = [items objectAtIndex:i];
NSString *type = dict[@"Type"];
if ([type isEqualTo:@"separator"]) {
if (!item || !item.isSeparatorItem) {
[self insertItem:[NSMenuItem separatorItem] atIndex:i];
}
continue;
}
if ([type isEqualTo:@"image"]) {
// encoding/json base64s a Go []byte, so ImageData arrives as a
// string; MenuetImageForRow decodes it only on a cache miss.
// MaxWidth/MaxHeight arrive with defaults already substituted by
// buildInternalItem — Go owns the boundary, this side trusts it.
NSString *b64 = [dict[@"ImageData"] isKindOfClass:[NSString class]]
? dict[@"ImageData"] : @"";
NSString *imagePath = dict[@"ImagePath"] ?: @"";
CGFloat maxW = [dict[@"MaxWidth"] doubleValue];
CGFloat maxH = [dict[@"MaxHeight"] doubleValue];
NSImage *picture = MenuetImageForRow(b64, imagePath, maxW, maxH);
BOOL imageClickable = [dict[@"Clickable"] boolValue];
NSString *imageUnique = dict[@"Unique"];
BOOL reuseImage = item && [item.view isKindOfClass:NSClassFromString(@"MenuetImageView")];
if (!reuseImage) {
if (item) [self removeItemAtIndex:i];
item = [self insertItemWithTitle:@"" action:nil keyEquivalent:@"" atIndex:i];
item.view = [[MenuetImageView alloc] initWithImage:picture
clickable:imageClickable];
} else {
[(MenuetImageView *)item.view updateImage:picture
clickable:imageClickable];
}
item.target = self;
if (imageClickable) {
item.action = @selector(press:);
item.representedObject = imageUnique;
} else {
item.action = nil;
item.representedObject = nil;
}
item.enabled = imageClickable;
continue;
}
if ([type isEqualTo:@"search"]) {
NSString *placeholder = dict[@"Text"] ?: @"";
NSString *searchUnique = dict[@"Unique"] ?: @"";
BOOL reuse = item && [item.view isKindOfClass:NSClassFromString(@"MenuetSearchView")];
if (!reuse) {
if (item) [self removeItemAtIndex:i];
item = [self insertItemWithTitle:@"" action:nil keyEquivalent:@"" atIndex:i];
MenuetSearchView *searchView = [[MenuetSearchView alloc]
initWithPlaceholder:placeholder
searchUnique:searchUnique];
item.view = searchView;
} else {
MenuetSearchView *searchView = (MenuetSearchView *)item.view;
[searchView updatePlaceholder:placeholder searchUnique:searchUnique];
}
// Defer the actual applyQuery to AFTER the while-loop trim
// below — otherwise the trim wipes any results we'd insert
// here (items.count == 1 for "[Search]"; the loop would trim
// every search result back out).
continue;
}
NSString *unique = dict[@"Unique"];
NSString *text = dict[@"Text"];
NSArray *runs = dict[@"Runs"];
NSString *imageName = dict[@"Image"];
NSNumber *fontSize = dict[@"FontSize"];
NSNumber *fontWeight = dict[@"FontWeight"];
NSDictionary *itemColor = dict[@"Color"];
BOOL itemMono = [dict[@"Monospaced"] boolValue];
BOOL state = [dict[@"State"] boolValue];
BOOL hasChildren = [dict[@"HasChildren"] boolValue];
BOOL clickable = [dict[@"Clickable"] boolValue];
// A leftover custom view (image or search row that changed type at
// this index) would supersede the title we set below —
// NSMenuItem.view wins over attributedTitle — so those items can't
// be reused for a regular row.
if (!item || item.isSeparatorItem || item.view) {
if (item) {
[self removeItemAtIndex:i];
}
item =
[self insertItemWithTitle:@"" action:nil keyEquivalent:@"" atIndex:i];
}
item.attributedTitle = MenuetBuildAttributedTitle(
text, runs, fontSize.floatValue, fontWeight.floatValue,
itemColor, itemMono);
// Two-line layout (macOS 14+ only). On older systems
// NSMenuItem.subtitle doesn't exist and the second line is
// silently dropped — see Subtitle's doc comment.
NSArray *subtitleRuns = dict[@"Subtitle"];
if (@available(macOS 14.0, *)) {
NSString *subtitleText = MenuetPlainTextFromRuns(subtitleRuns);
item.subtitle = subtitleText ?: @"";
}
// Shortcut display in the menu (⌘N etc.). The global hotkey
// registration happens Go-side in buildInternalItem.
NSDictionary *shortcut = dict[@"Shortcut"];
if ([shortcut isKindOfClass:[NSDictionary class]]) {
int kc = [shortcut[@"KeyCode"] intValue];
uint32_t mods = [shortcut[@"Modifiers"] unsignedIntValue];
item.keyEquivalent = MenuetKeyEquivalentStringForCode(kc);
item.keyEquivalentModifierMask = MenuetModifierMaskFromCarbon(mods);
} else {
item.keyEquivalent = @"";
item.keyEquivalentModifierMask = 0;
}
item.target = self;
if (clickable) {
item.action = @selector(press:);
item.representedObject = unique;
} else {
item.action = nil;
item.representedObject = nil;
}
if (state) {
item.state = NSControlStateValueOn;
} else {
item.state = NSControlStateValueOff;
}
if (hasChildren) {
if (!item.submenu) {
item.submenu = [MenuetMenu new];
}
MenuetMenu *menu = (MenuetMenu *)item.submenu;
menu.unique = unique;
} else if (item.submenu) {
item.submenu = nil;
}
item.enabled = clickable || hasChildren;
item.image = [NSImage imageFromName:imageName withHeight:16];
}
while (self.numberOfItems > items.count) {
[self removeItemAtIndex:self.numberOfItems - 1];
}
// Search results live OUTSIDE the user's items array — they're driven
// dynamically by the field's query. Apply each search view's saved (or
// empty) query here, after the trim, so the inserted results survive.
for (NSMenuItem *it in [self.itemArray copy]) {
if ([it.view isKindOfClass:NSClassFromString(@"MenuetSearchView")]) {
MenuetSearchView *sv = (MenuetSearchView *)it.view;
sv.field.stringValue = sv.savedQuery ?: @"";
[sv applyQuery:sv.field.stringValue];
}
}
}
// The documentation says not to make changes here, but it seems to work.
// submenuAction does not appear to be called, and menuNeedsUpdate is only
// called once per tracking session.
- (void)menuWillOpen:(MenuetMenu *)menu {
if (self.root) {
// For the root menu, we generate a new unique every time it's opened. Go
// handles all other unique generation.
self.unique = [[[[NSProcessInfo processInfo] globallyUniqueString]
substringFromIndex:51] stringByAppendingString:@":root"];
}
const char *str = children(self.unique.UTF8String);
NSArray *items = @[];
if (str != NULL) {
items = [NSJSONSerialization
JSONObjectWithData:[[NSString stringWithUTF8String:str]
dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:nil];
free((char *)str);
}
if (self.root) {
items = [items arrayByAddingObjectsFromArray:@[
@{@"Type" : @"separator",
@"Clickable" : @YES},
]];
if (!hideStartup()) {
char *startLabel = startAtLoginLabel();
items = [items arrayByAddingObjectsFromArray:@[
@{@"Text" : [NSString stringWithUTF8String:startLabel],
@"Clickable" : @YES},
]];
free(startLabel);
}
char *qLabel = quitLabel();
items = [items arrayByAddingObjectsFromArray:@[
@{@"Text" : [NSString stringWithUTF8String:qLabel],
@"Clickable" : @YES},
]];
free(qLabel);
}
[self populate:items];
if (self.root) {
NSMenuItem *item = nil;
if (!hideStartup()) {
item = [self itemAtIndex:items.count - 2];
item.action = @selector(toggleStartup:);
if (runningAtStartup()) {
item.state = NSControlStateValueOn;
} else {
item.state = NSControlStateValueOff;
}
}
item = [self itemAtIndex:items.count - 1];
item.action = @selector(prepareShutdown:);
}
self.open = YES;
}
- (void)menuDidClose:(MenuetMenu *)menu {
self.open = NO;
menuClosed(self.unique.UTF8String);
}
- (void)press:(id)sender {
NSString *callback = [sender representedObject];
itemClicked(callback.UTF8String);
}
- (void)toggleStartup:(id)sender {
toggleStartup();
}
- (void)prepareShutdown:(id)sender {
shutdownWait();
[NSApp terminate: nil];
}
@end
// MenuetSearchView hosts an NSSearchField inside an NSMenuItem.
//
// AppKit's menu subsystem runs its own event-tracking loop that swallows
// keystrokes before NSResponder routing has a chance to deliver them to
// any embedded NSTextField. The accepted workaround (since 2017) is to
// install a Carbon event handler on the application's event dispatcher:
// keystrokes still flow through Carbon, even inside menu tracking, so
// we can intercept them and write into the NSSearchField ourselves.
//
// Carbon UI APIs are deprecated, but the Carbon Event Manager subset we
// use here (InstallEventHandler, GetEventDispatcherTarget, EventRef ->
// NSEvent via +eventWithEventRef:) is what AppKit itself relies on for
// NSMenu and remains unmarked-deprecated.
//
// Approach and key-passthrough list adapted from
// Interface declared up at top of file so MenuetMenu's populate: can
// touch it during menuWillOpen.
@implementation MenuetSearchView
- (instancetype)initWithPlaceholder:(NSString *)placeholder
searchUnique:(NSString *)searchUnique {
self = [super initWithFrame:NSMakeRect(0, 0, 240, 28)];
if (self) {
_searchUnique = [searchUnique copy];
_savedQuery = @"";
_field = [[NSSearchField alloc] initWithFrame:NSMakeRect(6, 2, 228, 24)];
_field.placeholderString = placeholder;
_field.delegate = self;
_field.autoresizingMask = NSViewWidthSizable;
[self addSubview:_field];
}
return self;
}
- (void)updatePlaceholder:(NSString *)placeholder searchUnique:(NSString *)unique {
if (![self.field.placeholderString isEqualToString:placeholder]) {
self.field.placeholderString = placeholder;
}
// searchUnique changes every menu open (fresh uuid). Don't clobber the
// field — savedQuery is what should persist.
self.searchUnique = [unique copy];
}
- (void)dealloc {
if (_trackingMenu) {
[[NSNotificationCenter defaultCenter] removeObserver:self];
_trackingMenu = nil;
}
[_field release];
[_searchUnique release];
[_savedQuery release];
[super dealloc];
}
- (void)viewDidMoveToWindow {
[super viewDidMoveToWindow];
if (self.window == nil) {
// Submenu closed (either user moved off to another parent-menu
// item or the whole tracking session ended). Snapshot the field
// so the query persists across re-opens. Safe to run on AppKit's
// open-time view-window cycles too — the field's value at that
// point is whatever populate: just set it to (either the prior
// savedQuery or "").
self.savedQuery = self.field.stringValue;
return;
}
// Subscribe once to end-tracking so we can persist the field's text
// across menu opens. The notification is posted by the *root* menu
// (not individual submenus), so we don't filter by object.
if (!self.trackingMenu) {
self.trackingMenu = self.enclosingMenuItem.menu;
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(menuDidEndTracking:)
name:NSMenuDidEndTrackingNotification
object:nil];
}
[self.window makeFirstResponder:self.field];
// NSPopupMenuWindow refuses regular makeKeyWindow during menu tracking,
// so the text field's input context never engages — no cursor blink,
// no edit state. Calling the window's private -setKeyOverride:YES
// flips its key-state override and lets the field's editor become
// active. This is the first of two private hooks the Search type
// relies on; documented as an App Store-incompatible caveat.
SEL setKeyOverride = NSSelectorFromString(@"setKeyOverride:");
if ([self.window respondsToSelector:setKeyOverride]) {
NSMethodSignature *sig = [self.window methodSignatureForSelector:setKeyOverride];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];
inv.selector = setKeyOverride;
BOOL yes = YES;
[inv setArgument:&yes atIndex:2];
[inv invokeWithTarget:self.window];
}
// Begin an editing session on the field via -selectWithFrame:...
// (the non-modal partner of -editWithFrame:...:event:, which spins a
// modal event loop and freezes the menu). This gives us a visible text
// cursor immediately, plus a selected range so any remembered query
// is replaced when the user starts typing.
NSText *editor = [self.window fieldEditor:YES forObject:self.field];
NSUInteger len = self.field.stringValue.length;
[self.field.cell selectWithFrame:self.field.bounds
inView:self.field
editor:editor
delegate:self.field