cc-pets 2.0.3 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CC_BRIDGE.md +239 -0
  2. package/CC_BRIDGE.zh-CN.md +210 -0
  3. package/CHANGELOG.md +49 -0
  4. package/CHANGELOG.zh-CN.md +49 -0
  5. package/PROVIDER_PROTOCOL.md +6 -0
  6. package/PROVIDER_PROTOCOL.zh-CN.md +5 -0
  7. package/README.md +17 -1
  8. package/README.zh-CN.md +18 -2
  9. package/Sources/CCPets/CCPetsAppDelegate.h +17 -2
  10. package/Sources/CCPets/CCPetsAppDelegate.m +478 -56
  11. package/Sources/CCPets/CCPetsBridge.h +43 -0
  12. package/Sources/CCPets/CCPetsBridge.m +198 -0
  13. package/Sources/CCPets/CCPetsCleanup.m +3 -1
  14. package/Sources/CCPets/CCPetsCodexRateLimits.h +1 -0
  15. package/Sources/CCPets/CCPetsCodexRateLimits.m +7 -0
  16. package/Sources/CCPets/CCPetsEvents.m +1 -1
  17. package/Sources/CCPets/CCPetsGlassMenu.h +10 -0
  18. package/Sources/CCPets/CCPetsGlassMenu.m +196 -0
  19. package/Sources/CCPets/CCPetsGlassView.h +31 -0
  20. package/Sources/CCPets/CCPetsGlassView.m +246 -0
  21. package/Sources/CCPets/CCPetsPaths.h +7 -0
  22. package/Sources/CCPets/CCPetsPaths.m +14 -0
  23. package/Sources/CCPets/CCPetsTerminalFocus.h +15 -0
  24. package/Sources/CCPets/CCPetsTerminalFocus.m +306 -15
  25. package/Sources/CCPets/CCPetsUsage.h +2 -0
  26. package/Sources/CCPets/CCPetsUsage.m +69 -18
  27. package/Sources/CCPets/CCPetsUsageMonitor.m +43 -8
  28. package/Sources/CCPets/MenuChoiceRow.h +19 -0
  29. package/Sources/CCPets/MenuChoiceRow.m +96 -0
  30. package/Sources/CCPets/MenuHintView.h +15 -0
  31. package/Sources/CCPets/MenuHintView.m +128 -0
  32. package/Sources/CCPets/PetView.m +143 -3
  33. package/Sources/CCPets/QuotaDashboardView.h +3 -4
  34. package/Sources/CCPets/QuotaDashboardView.m +222 -143
  35. package/Sources/CCPets/main.m +16 -0
  36. package/bin/cc-pets +38 -1
  37. package/bin/codex-with-pet +2 -0
  38. package/package.json +3 -1
  39. package/scripts/bridge/cli.mjs +229 -0
  40. package/scripts/bridge/core.mjs +227 -0
  41. package/scripts/bridge/hook.mjs +149 -0
  42. package/scripts/bridge/install.mjs +288 -0
  43. package/scripts/bridge/mcp-server.mjs +300 -0
  44. package/scripts/bridge/options.mjs +86 -0
  45. package/scripts/bridge/process.mjs +129 -0
  46. package/scripts/bridge/reservations.mjs +247 -0
  47. package/scripts/bridge/store.mjs +432 -0
  48. package/scripts/bridge/watch.mjs +69 -0
  49. package/scripts/install-shell-integration.sh +3 -0
  50. package/scripts/uninstall-integrations.mjs +10 -0
@@ -0,0 +1,43 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // CC Bridge(scripts/bridge/)状态的只读视图,供桌宠显示角标、在会话列表里标出
4
+ // 会话名、以及点击跳回收件会话的终端。
5
+ //
6
+ // 只读元数据:会话名 / tty、谁发给谁、何时送达、信箱积压条数。回执文件里虽然带着
7
+ // 消息正文,这里解析后立即丢弃,不返回、不缓存——桌宠界面不显示正文。
8
+
9
+ // 桌宠侧的偏好:消息角标(默认开)、新消息系统通知(默认关)。
10
+ extern NSString *const BridgeBadgeEnabledKey;
11
+ extern NSString *const BridgeNotificationKey;
12
+
13
+ // <PetStateDirectory>/cc-bridge-<uid>,与 scripts/bridge/store.mjs 的 bridgeDirectory 一致。
14
+ NSString *CCBridgeStateDirectory(void);
15
+
16
+ // ~/.cc-pets/bridge-enabled(可用 CC_PETS_HOME 覆盖)存在即视为开启。
17
+ BOOL CCBridgeEnabled(void);
18
+
19
+ // 开关文件里保存的选项(与 scripts/bridge/options.mjs 一致),未开启或缺项时取默认值:
20
+ // @{ @"codexApprove": NSArray, @"claudeAllow": NSArray, @"wake": @YES, @"editGuard": @YES }
21
+ NSDictionary *CCBridgeOptions(void);
22
+
23
+ // 免审批分组:view / send / reserve / name → 工具名。必须与 options.mjs 的 TOOL_GROUPS 一致。
24
+ NSArray<NSString *> *CCBridgeToolGroupNames(void);
25
+ NSArray<NSString *> *CCBridgeToolGroup(NSString *group);
26
+
27
+ // CLI 定位(~/.cc-pets/bridge-cli.json,由 cc-pets bridge refresh / enable / configure 写入):
28
+ // @{ @"node", @"cli" },两者都必须是存在的绝对路径,否则返回 nil。
29
+ NSDictionary<NSString *, NSString *> *CCBridgeCLILocator(void);
30
+
31
+ // 仍有效(未过期、持有者在给定会话集合内)的文件预留条数。
32
+ NSUInteger CCBridgeActiveReservationCount(NSSet<NSString *> *sessionIds);
33
+
34
+ // 在线会话:session id → @{ @"name", @"ref", @"provider", @"tty" }(tty 可能缺省)。
35
+ // 记录了 pid 而进程已不在的会话不返回。
36
+ NSDictionary<NSString *, NSDictionary *> *CCBridgeSessions(void);
37
+
38
+ // 最近送达的跨会话消息,不含 cc-bridge 自己发的系统通知(空闲通知等),按送达时间倒序。
39
+ // 每项:@{ @"id", @"from", @"to", @"toSession", @"at" },at 为秒级时间戳。
40
+ NSArray<NSDictionary *> *CCBridgeRecentDeliveries(NSTimeInterval since, NSUInteger limit);
41
+
42
+ // session id → 信箱里仍未投递的条数(只含 > 0 的会话)。
43
+ NSDictionary<NSString *, NSNumber *> *CCBridgePendingCounts(void);
@@ -0,0 +1,198 @@
1
+ #import "CCPetsBridge.h"
2
+ #import "CCPetsPaths.h"
3
+ #import <errno.h>
4
+ #import <signal.h>
5
+ #import <unistd.h>
6
+
7
+ NSString *const BridgeBadgeEnabledKey = @"CCPetsBridgeBadgeEnabled";
8
+ NSString *const BridgeNotificationKey = @"CCPetsBridgeNotification";
9
+
10
+ // 目录里文件数的上限。回执保留 48 小时,正常使用远到不了这个量;
11
+ // 真到了说明有东西在刷消息,宁可少显示几条也不让桌宠主线程卡在读盘上。
12
+ static const NSUInteger BridgeFileScanLimit = 500;
13
+
14
+ NSString *CCBridgeStateDirectory(void) {
15
+ NSString *name = [NSString stringWithFormat:@"cc-bridge-%u", getuid()];
16
+ return [PetStateDirectory() stringByAppendingPathComponent:name];
17
+ }
18
+
19
+ static NSString *BridgeHomeDirectory(void) {
20
+ NSString *home = NSProcessInfo.processInfo.environment[@"CC_PETS_HOME"];
21
+ if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".cc-pets"];
22
+ return home.stringByStandardizingPath;
23
+ }
24
+
25
+ BOOL CCBridgeEnabled(void) {
26
+ return [NSFileManager.defaultManager fileExistsAtPath:
27
+ [BridgeHomeDirectory() stringByAppendingPathComponent:@"bridge-enabled"]];
28
+ }
29
+
30
+ NSArray<NSString *> *CCBridgeToolGroupNames(void) {
31
+ return @[@"view", @"send", @"reserve", @"name"];
32
+ }
33
+
34
+ NSArray<NSString *> *CCBridgeToolGroup(NSString *group) {
35
+ static NSDictionary<NSString *, NSArray<NSString *> *> *groups;
36
+ static dispatch_once_t once;
37
+ dispatch_once(&once, ^{
38
+ groups = @{
39
+ @"view": @[@"list_agents", @"list_reservations", @"check_inbox"],
40
+ @"send": @[@"send_message"],
41
+ @"reserve": @[@"reserve_files", @"release_files"],
42
+ @"name": @[@"set_name"]
43
+ };
44
+ });
45
+ return groups[group] ?: @[];
46
+ }
47
+
48
+ static NSArray<NSString *> *KnownTools(id value) {
49
+ if (![value isKindOfClass:NSArray.class]) return @[];
50
+ NSMutableArray<NSString *> *tools = [NSMutableArray array];
51
+ for (NSString *group in CCBridgeToolGroupNames()) {
52
+ for (NSString *tool in CCBridgeToolGroup(group)) {
53
+ if ([value containsObject:tool]) [tools addObject:tool];
54
+ }
55
+ }
56
+ return tools;
57
+ }
58
+
59
+ // 名字、ref、tty 都会进菜单标题。bridge 端已经约束过格式,这里再按同一字符集收一遍,
60
+ // 防止被手改的状态文件往菜单里塞奇怪的东西。
61
+ static NSString *BridgeSafeString(id value, NSUInteger maximumLength) {
62
+ if (![value isKindOfClass:NSString.class]) return @"";
63
+ NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:
64
+ @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"];
65
+ NSMutableString *safe = [NSMutableString string];
66
+ NSString *text = value;
67
+ for (NSUInteger index = 0; index < text.length && safe.length < maximumLength; index++) {
68
+ unichar character = [text characterAtIndex:index];
69
+ if ([allowed characterIsMember:character]) [safe appendFormat:@"%C", character];
70
+ }
71
+ return safe;
72
+ }
73
+
74
+ static NSArray<NSString *> *JSONFilesInDirectory(NSString *directory) {
75
+ NSArray<NSString *> *names = [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil];
76
+ NSMutableArray<NSString *> *files = [NSMutableArray array];
77
+ for (NSString *name in names) {
78
+ if (![name hasSuffix:@".json"]) continue;
79
+ [files addObject:[directory stringByAppendingPathComponent:name]];
80
+ if (files.count >= BridgeFileScanLimit) break;
81
+ }
82
+ return files;
83
+ }
84
+
85
+ static NSDictionary *ReadJSONObject(NSString *path) {
86
+ NSData *data = [NSData dataWithContentsOfFile:path];
87
+ if (data.length == 0) return nil;
88
+ id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
89
+ return [object isKindOfClass:NSDictionary.class] ? object : nil;
90
+ }
91
+
92
+ NSDictionary *CCBridgeOptions(void) {
93
+ NSDictionary *raw = nil;
94
+ if (CCBridgeEnabled()) {
95
+ raw = ReadJSONObject([BridgeHomeDirectory() stringByAppendingPathComponent:@"bridge-enabled"]);
96
+ }
97
+ return @{
98
+ @"codexApprove": KnownTools(raw[@"codexApprove"]),
99
+ @"claudeAllow": KnownTools(raw[@"claudeAllow"]),
100
+ @"wake": @(![raw[@"wake"] isEqual:@NO]),
101
+ @"editGuard": @(![raw[@"editGuard"] isEqual:@NO])
102
+ };
103
+ }
104
+
105
+ NSDictionary<NSString *, NSString *> *CCBridgeCLILocator(void) {
106
+ NSDictionary *raw = ReadJSONObject([BridgeHomeDirectory() stringByAppendingPathComponent:@"bridge-cli.json"]);
107
+ NSString *node = [raw[@"node"] isKindOfClass:NSString.class] ? [raw[@"node"] stringByStandardizingPath] : nil;
108
+ NSString *cli = [raw[@"cli"] isKindOfClass:NSString.class] ? [raw[@"cli"] stringByStandardizingPath] : nil;
109
+ NSFileManager *files = NSFileManager.defaultManager;
110
+ if (!node.isAbsolutePath || !cli.isAbsolutePath) return nil;
111
+ if (![files isExecutableFileAtPath:node] || ![files isReadableFileAtPath:cli]) return nil;
112
+ return @{@"node": node, @"cli": cli};
113
+ }
114
+
115
+ NSUInteger CCBridgeActiveReservationCount(NSSet<NSString *> *sessionIds) {
116
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"reservations"];
117
+ double now = NSDate.date.timeIntervalSince1970 * 1000.0;
118
+ NSUInteger count = 0;
119
+ for (NSString *path in JSONFilesInDirectory(directory)) {
120
+ NSDictionary *reservation = ReadJSONObject(path);
121
+ if ([reservation[@"expiresAt"] doubleValue] <= now) continue;
122
+ NSString *session = [reservation[@"session"] isKindOfClass:NSString.class] ? reservation[@"session"] : nil;
123
+ if (session && [sessionIds containsObject:session]) count++;
124
+ }
125
+ return count;
126
+ }
127
+
128
+ static BOOL ProcessAlive(id pidValue) {
129
+ if (![pidValue isKindOfClass:NSNumber.class]) return YES; // 没记 pid 的会话交给 bridge 端判定
130
+ pid_t pid = [pidValue intValue];
131
+ if (pid <= 1) return YES;
132
+ return kill(pid, 0) == 0 || errno == EPERM;
133
+ }
134
+
135
+ NSDictionary<NSString *, NSDictionary *> *CCBridgeSessions(void) {
136
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"sessions"];
137
+ NSMutableDictionary<NSString *, NSDictionary *> *sessions = [NSMutableDictionary dictionary];
138
+ for (NSString *path in JSONFilesInDirectory(directory)) {
139
+ NSDictionary *record = ReadJSONObject(path);
140
+ NSString *session = BridgeSafeString(record[@"session"], 128);
141
+ NSString *name = BridgeSafeString(record[@"name"], 40);
142
+ if (session.length == 0 || name.length == 0 || !ProcessAlive(record[@"pid"])) continue;
143
+ NSMutableDictionary *entry = [@{
144
+ @"name": name,
145
+ @"ref": BridgeSafeString(record[@"ref"], 6),
146
+ @"provider": BridgeSafeString(record[@"provider"], 16)
147
+ } mutableCopy];
148
+ NSString *tty = BridgeSafeString(record[@"tty"], 32);
149
+ if (tty.length > 0) entry[@"tty"] = tty;
150
+ sessions[session] = entry;
151
+ }
152
+ return sessions;
153
+ }
154
+
155
+ NSArray<NSDictionary *> *CCBridgeRecentDeliveries(NSTimeInterval since, NSUInteger limit) {
156
+ NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"sent"];
157
+ NSMutableArray<NSDictionary *> *deliveries = [NSMutableArray array];
158
+ for (NSString *path in JSONFilesInDirectory(directory)) {
159
+ NSDictionary *receipt = ReadJSONObject(path);
160
+ if (![receipt[@"status"] isEqual:@"delivered"]) continue;
161
+ NSDictionary *from = [receipt[@"from"] isKindOfClass:NSDictionary.class] ? receipt[@"from"] : nil;
162
+ NSDictionary *to = [receipt[@"to"] isKindOfClass:NSDictionary.class] ? receipt[@"to"] : nil;
163
+ if (!from || !to || [from[@"system"] boolValue]) continue;
164
+ id stamp = receipt[@"updatedAt"] ?: receipt[@"createdAt"];
165
+ if (![stamp isKindOfClass:NSNumber.class]) continue;
166
+ NSTimeInterval at = [stamp doubleValue] / 1000.0;
167
+ if (at < since) continue;
168
+ NSString *fromName = BridgeSafeString(from[@"name"], 40);
169
+ NSString *toName = BridgeSafeString(to[@"name"], 40);
170
+ NSString *toSession = BridgeSafeString(to[@"session"], 128);
171
+ if (fromName.length == 0 || toName.length == 0 || toSession.length == 0) continue;
172
+ // 只取元数据:receipt[@"body"] 不进入返回值。
173
+ [deliveries addObject:@{
174
+ @"id": BridgeSafeString(receipt[@"id"], 64),
175
+ @"from": fromName,
176
+ @"to": toName,
177
+ @"toSession": toSession,
178
+ @"at": @(at)
179
+ }];
180
+ }
181
+ [deliveries sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
182
+ return [right[@"at"] compare:left[@"at"]];
183
+ }];
184
+ if (deliveries.count > limit) return [deliveries subarrayWithRange:NSMakeRange(0, limit)];
185
+ return deliveries;
186
+ }
187
+
188
+ NSDictionary<NSString *, NSNumber *> *CCBridgePendingCounts(void) {
189
+ NSString *inbox = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"inbox"];
190
+ NSMutableDictionary<NSString *, NSNumber *> *counts = [NSMutableDictionary dictionary];
191
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:inbox error:nil]) {
192
+ NSString *session = BridgeSafeString(name, 128);
193
+ if (session.length == 0 || ![session isEqualToString:name]) continue;
194
+ NSUInteger count = JSONFilesInDirectory([inbox stringByAppendingPathComponent:name]).count;
195
+ if (count > 0) counts[session] = @(count);
196
+ }
197
+ return counts;
198
+ }
@@ -126,6 +126,8 @@ void PruneStaleRuntimeState(void) {
126
126
  NSTimeInterval cutoff = NSDate.date.timeIntervalSince1970 - RuntimeStateTTL;
127
127
  RemoveExpiredFile(AgentEventPath(), cutoff);
128
128
  RemoveExpiredFile(ClaudeUsagePath(), cutoff);
129
+ RemoveExpiredFile(CodexLiveUsagePath(), cutoff);
130
+ RemoveExpiredFile(CodexLaunchRegistryPath(), cutoff);
129
131
  RemoveDeadClientRecords();
130
132
  }
131
133
 
@@ -148,7 +150,7 @@ int CleanCCPetsData(BOOL purge) {
148
150
  }
149
151
  NSUInteger removed = 0;
150
152
  if (RemoveClaudeUsageIfUnlocked()) removed += 1;
151
- for (NSString *path in @[AgentEventPath(), RuntimeLockPath(),
153
+ for (NSString *path in @[AgentEventPath(), CodexLiveUsagePath(), CodexLaunchRegistryPath(), RuntimeLockPath(),
152
154
  ClientStateDirectory(), buildCache ?: @""]) {
153
155
  if (RemoveIfPresent(path)) removed += 1;
154
156
  }
@@ -9,5 +9,6 @@
9
9
  @end
10
10
 
11
11
  // 把实时额度覆盖到会话读取器产出的用量上;本机 Token 聚合等非官方字段会被保留。
12
+ // 会话快照的 sampledAt 更晚时原样返回会话快照。
12
13
  NSDictionary *CodexUsageByApplyingLiveUsage(NSDictionary *sessionUsage,
13
14
  NSDictionary *liveUsage);
@@ -367,6 +367,13 @@ static NSDictionary<NSString *, NSString *> *CodexAppServerEnvironment(NSString
367
367
  NSDictionary *CodexUsageByApplyingLiveUsage(NSDictionary *sessionUsage,
368
368
  NSDictionary *liveUsage) {
369
369
  if (![liveUsage isKindOfClass:NSDictionary.class]) return sessionUsage;
370
+ // 两边都是同一账号的快照,谁采样得晚用谁。实时值不再到期就丢:它丢了以后退回的会话快照
371
+ // 往往更旧(在 Codex App、其他设备上用掉的额度不会写进本机会话日志),面板会先跳回
372
+ // 旧值、等下一次实时查询再跳回来。本机会话拿到更新的响应时自然会胜出。
373
+ if ([sessionUsage isKindOfClass:NSDictionary.class] &&
374
+ [sessionUsage[@"sampledAt"] doubleValue] > [liveUsage[@"sampledAt"] doubleValue]) {
375
+ return sessionUsage;
376
+ }
370
377
  NSMutableDictionary *merged = [sessionUsage isKindOfClass:NSDictionary.class]
371
378
  ? [sessionUsage mutableCopy] : [NSMutableDictionary dictionary];
372
379
  for (NSString *key in @[@"fiveHour", @"week"]) {
@@ -197,7 +197,7 @@ int RecordHookEvent(void) {
197
197
  @"timestamp": @([NSDate.date timeIntervalSince1970])
198
198
  } mutableCopy];
199
199
  if (session.length > 0) record[@"session"] = session;
200
- NSDictionary *terminal = TerminalFocusTargetFromEnvironment();
200
+ NSDictionary *terminal = TerminalFocusTargetForHook(payload, provider);
201
201
  if (terminal.count > 0) record[@"terminal"] = terminal;
202
202
  AppendAgentEventRecord(record);
203
203
  return EXIT_SUCCESS;
@@ -0,0 +1,10 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // 用原生玻璃面板展示一个已经构建好的 NSMenu。系统菜单的材质不能换,Liquid Glass 主题下
4
+ // 消息列表会和旁边的玻璃状态卡风格割裂;这里只读菜单项的标题、启用、勾选、分隔线和
5
+ // target/action,调用方的菜单构建代码不用改。只支持平铺菜单(没有子菜单、自定义视图)。
6
+ @interface CCPetsGlassMenu : NSObject
7
+ // anchor 是玻璃状态卡;面板贴在它下方、右边与 alignView 右边对齐,屏幕下方放不下时放到上方。
8
+ + (void)showMenu:(NSMenu *)menu belowView:(NSView *)anchor alignRightTo:(NSView *)alignView;
9
+ + (void)dismiss;
10
+ @end
@@ -0,0 +1,196 @@
1
+ #import "CCPetsGlassMenu.h"
2
+ #import "CCPetsGlassView.h"
3
+
4
+ static const CGFloat GlassMenuRowHeight = 24;
5
+ static const CGFloat GlassMenuSeparatorHeight = 11;
6
+ static const CGFloat GlassMenuPadding = 6;
7
+ static const CGFloat GlassMenuTextInset = 30;
8
+
9
+ static NSShadow *GlassMenuTextShadow(void) {
10
+ NSShadow *shadow = [NSShadow new];
11
+ shadow.shadowColor = [NSColor colorWithWhite:0 alpha:0.45];
12
+ shadow.shadowBlurRadius = 2;
13
+ shadow.shadowOffset = NSMakeSize(0, -0.5);
14
+ return shadow;
15
+ }
16
+
17
+ @interface CCPetsGlassMenuRow : NSView
18
+ @property(nonatomic, strong) NSMenuItem *item;
19
+ @end
20
+
21
+ @implementation CCPetsGlassMenuRow {
22
+ NSTrackingArea *_trackingArea;
23
+ BOOL _hovered;
24
+ }
25
+ - (BOOL)selectable { return self.item.isEnabled && self.item.action != nil; }
26
+ - (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
27
+ // 这是独立的面板窗口,不在菜单跟踪循环里,进出事件是可靠的。
28
+ - (void)updateTrackingAreas {
29
+ [super updateTrackingAreas];
30
+ if (_trackingArea) [self removeTrackingArea:_trackingArea];
31
+ _trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect
32
+ options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect
33
+ owner:self userInfo:nil];
34
+ [self addTrackingArea:_trackingArea];
35
+ }
36
+ - (void)mouseEntered:(NSEvent *)event { _hovered = YES; self.needsDisplay = YES; }
37
+ - (void)mouseExited:(NSEvent *)event { _hovered = NO; self.needsDisplay = YES; }
38
+ - (void)mouseDown:(NSEvent *)event {}
39
+ - (void)mouseUp:(NSEvent *)event {
40
+ if (![self selectable]) return;
41
+ NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
42
+ if (!NSPointInRect(point, self.bounds)) return;
43
+ NSMenuItem *item = self.item;
44
+ [CCPetsGlassMenu dismiss];
45
+ [NSApp sendAction:item.action to:item.target from:item];
46
+ }
47
+ - (void)drawRect:(NSRect)dirtyRect {
48
+ NSMenuItem *item = self.item;
49
+ if (item.isSeparatorItem) {
50
+ [[NSColor colorWithWhite:1 alpha:0.18] setFill];
51
+ NSRectFill(NSMakeRect(12, floor(NSMidY(self.bounds)), NSWidth(self.bounds) - 24, 1));
52
+ return;
53
+ }
54
+ BOOL highlighted = _hovered && [self selectable];
55
+ if (highlighted) {
56
+ [NSColor.selectedContentBackgroundColor setFill];
57
+ [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds, 5, 0)
58
+ xRadius:6 yRadius:6] fill];
59
+ }
60
+ // 标题行(不可点)用浅一档的白,和系统菜单的分组标题一致。
61
+ NSColor *color = [self selectable] ? [NSColor colorWithWhite:1 alpha:0.96]
62
+ : [NSColor colorWithWhite:1 alpha:0.72];
63
+ NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
64
+ style.lineBreakMode = NSLineBreakByTruncatingTail;
65
+ NSDictionary *attributes = @{NSFontAttributeName: [NSFont menuFontOfSize:13],
66
+ NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: style,
67
+ NSShadowAttributeName: highlighted ? [NSShadow new] : GlassMenuTextShadow()};
68
+ CGFloat textHeight = ceil([item.title sizeWithAttributes:attributes].height);
69
+ NSRect textRect = NSMakeRect(GlassMenuTextInset, (NSHeight(self.bounds) - textHeight) / 2.0,
70
+ NSWidth(self.bounds) - GlassMenuTextInset - 14, textHeight);
71
+ [item.title drawInRect:textRect withAttributes:attributes];
72
+ if (item.state == NSControlStateValueOn) {
73
+ [@"✓" drawAtPoint:NSMakePoint(13, NSMinY(textRect)) withAttributes:attributes];
74
+ }
75
+ }
76
+ @end
77
+
78
+ // 翻转坐标,行从上往下排,滚动视图默认停在顶部。
79
+ @interface CCPetsGlassMenuDocument : NSView
80
+ @end
81
+ @implementation CCPetsGlassMenuDocument
82
+ - (BOOL)isFlipped { return YES; }
83
+ @end
84
+
85
+ @interface CCPetsGlassMenuPanel : NSPanel
86
+ @end
87
+ @implementation CCPetsGlassMenuPanel
88
+ - (BOOL)canBecomeKeyWindow { return NO; }
89
+ @end
90
+
91
+ static CCPetsGlassMenuPanel *ActivePanel;
92
+ static id LocalMonitor;
93
+ static id GlobalMonitor;
94
+
95
+ @implementation CCPetsGlassMenu
96
+ + (void)dismiss {
97
+ if (LocalMonitor) [NSEvent removeMonitor:LocalMonitor];
98
+ if (GlobalMonitor) [NSEvent removeMonitor:GlobalMonitor];
99
+ LocalMonitor = nil;
100
+ GlobalMonitor = nil;
101
+ [ActivePanel orderOut:nil];
102
+ ActivePanel = nil;
103
+ }
104
+
105
+ + (void)showMenu:(NSMenu *)menu belowView:(NSView *)anchor alignRightTo:(NSView *)alignView {
106
+ [self dismiss];
107
+ NSWindow *anchorWindow = anchor.window;
108
+ if (!anchorWindow) return;
109
+ NSDictionary *measure = @{NSFontAttributeName: [NSFont menuFontOfSize:13]};
110
+ CGFloat textWidth = 0, contentHeight = 0;
111
+ for (NSMenuItem *item in menu.itemArray) {
112
+ if (item.isHidden) continue;
113
+ contentHeight += item.isSeparatorItem ? GlassMenuSeparatorHeight : GlassMenuRowHeight;
114
+ textWidth = MAX(textWidth, ceil([item.title sizeWithAttributes:measure].width));
115
+ }
116
+ CGFloat width = MIN(MAX(textWidth + GlassMenuTextInset + 20, 220), 560);
117
+
118
+ NSRect anchorRect = [anchorWindow convertRectToScreen:[anchor convertRect:anchor.bounds toView:nil]];
119
+ NSRect alignRect = [anchorWindow convertRectToScreen:[alignView convertRect:alignView.bounds toView:nil]];
120
+ NSRect visible = NSInsetRect((anchorWindow.screen ?: NSScreen.mainScreen).visibleFrame, 4, 4);
121
+ // 会话、消息多的时候不能无限长:限高,超出部分在面板内滚动。
122
+ CGFloat height = MIN(contentHeight + GlassMenuPadding * 2, MIN(420, NSHeight(visible)));
123
+ CGFloat x = NSMaxX(alignRect) - width;
124
+ x = MIN(MAX(x, NSMinX(visible)), NSMaxX(visible) - width);
125
+ // 优先放在状态卡下方,放不下再放上方;两边都放不下时夹在屏幕可见区域内(会盖住状态卡)。
126
+ CGFloat below = NSMinY(anchorRect) - 6 - height;
127
+ CGFloat above = NSMaxY(anchorRect) + 6;
128
+ CGFloat y = below >= NSMinY(visible) ? below
129
+ : (above + height <= NSMaxY(visible) ? above : below);
130
+ y = MIN(MAX(y, NSMinY(visible)), NSMaxY(visible) - height);
131
+
132
+ CCPetsGlassMenuPanel *panel = [[CCPetsGlassMenuPanel alloc]
133
+ initWithContentRect:NSMakeRect(x, y, width, height)
134
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
135
+ backing:NSBackingStoreBuffered defer:NO];
136
+ panel.opaque = NO;
137
+ panel.backgroundColor = NSColor.clearColor;
138
+ panel.hasShadow = NO;
139
+ panel.level = anchorWindow.level + 1;
140
+ panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
141
+ NSWindowCollectionBehaviorFullScreenAuxiliary;
142
+ panel.hidesOnDeactivate = NO;
143
+ panel.acceptsMouseMovedEvents = YES;
144
+
145
+ CCPetsGlassView *glass = [[CCPetsGlassView alloc] initWithFrame:NSMakeRect(0, 0, width, height)
146
+ material:NSVisualEffectMaterialMenu appearance:NSAppearanceNameDarkAqua cornerRadius:12];
147
+ glass.edgeShadeHeight = 10;
148
+ glass.edgeShadeAlpha = 0.6;
149
+ glass.usesWidgetGlass = YES;
150
+ CCPetsGlassMenuDocument *document = [[CCPetsGlassMenuDocument alloc]
151
+ initWithFrame:NSMakeRect(0, 0, width, contentHeight)];
152
+ CGFloat rowY = 0;
153
+ for (NSMenuItem *item in menu.itemArray) {
154
+ if (item.isHidden) continue;
155
+ CGFloat rowHeight = item.isSeparatorItem ? GlassMenuSeparatorHeight : GlassMenuRowHeight;
156
+ CCPetsGlassMenuRow *row = [[CCPetsGlassMenuRow alloc]
157
+ initWithFrame:NSMakeRect(0, rowY, width, rowHeight)];
158
+ row.item = item;
159
+ if (item.toolTip.length > 0) row.toolTip = item.toolTip;
160
+ [document addSubview:row];
161
+ rowY += rowHeight;
162
+ }
163
+ NSScrollView *scroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, GlassMenuPadding,
164
+ width, height - GlassMenuPadding * 2)];
165
+ scroll.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
166
+ scroll.drawsBackground = NO;
167
+ scroll.contentView.drawsBackground = NO;
168
+ scroll.borderType = NSNoBorder;
169
+ scroll.hasVerticalScroller = contentHeight > NSHeight(scroll.frame);
170
+ scroll.autohidesScrollers = YES;
171
+ scroll.scrollerStyle = NSScrollerStyleOverlay;
172
+ scroll.documentView = document;
173
+ [glass.contentView addSubview:scroll];
174
+ panel.contentView = glass;
175
+ [panel orderFrontRegardless];
176
+ ActivePanel = panel;
177
+
178
+ // 点面板以外的任何地方就收起,和系统菜单一致。桌宠是非激活 App,大部分点击落在别的
179
+ // App 上,要靠全局监听;落在本 App 其他窗口(宠物、状态卡)上的走本地监听。
180
+ NSEventMask mask = NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown;
181
+ GlobalMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:mask handler:^(NSEvent *event) {
182
+ [CCPetsGlassMenu dismiss];
183
+ }];
184
+ // 键盘:面板刻意不抢焦点(抢了会把前台终端的焦点夺走),所以只有本 App 恰好在前台时
185
+ // Esc 才生效,也不支持方向键选择。这是替代系统菜单的已知取舍,不用全局键盘监听来补。
186
+ LocalMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:mask | NSEventMaskKeyDown
187
+ handler:^NSEvent *(NSEvent *event) {
188
+ if (event.type == NSEventTypeKeyDown) {
189
+ if (event.keyCode == 53) { [CCPetsGlassMenu dismiss]; return nil; }
190
+ return event;
191
+ }
192
+ if (event.window != ActivePanel) [CCPetsGlassMenu dismiss];
193
+ return event;
194
+ }];
195
+ }
196
+ @end
@@ -0,0 +1,31 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ extern NSString *const CCPetsPanelThemeKey;
4
+ NSString *CCPetsPanelTheme(void);
5
+ // 桌面小组件式玻璃背后压暗层的档位:0 / 15 / 25 / 45(百分比),默认 25。
6
+ extern NSString *const CCPetsGlassDimKey;
7
+ NSInteger CCPetsGlassDimLevel(void);
8
+ NSArray<NSNumber *> *CCPetsGlassDimLevels(void);
9
+ // 额度卡片衬底的不透明度,跟随压暗档位:卡片区域同时受背后压暗和衬底两层影响,
10
+ // 衬底固定的话选「通透」时卡片仍然很深。
11
+ CGFloat CCPetsGlassCardScrimAlpha(void);
12
+ // 运行系统和构建 SDK 都支持 NSGlassEffectView 时才为 YES。
13
+ BOOL CCPetsLiquidGlassAvailable(void);
14
+
15
+ // 固定的内容容器使主题切换不影响文字、按钮和悬停状态。
16
+ @interface CCPetsGlassView : NSView
17
+ @property(nonatomic, readonly) NSView *contentView;
18
+ @property(nonatomic, readonly) BOOL usesLiquidGlass;
19
+ @property(nonatomic) CGFloat cornerRadius;
20
+ // 桌面小组件式玻璃:背景清晰、边缘折射,并在玻璃背后垫一层压暗托住白字。只适合白字面板。
21
+ @property(nonatomic) BOOL usesWidgetGlass;
22
+ // 上下沿压高光暗带的高度和最深处不透明度,默认 12pt / 0.6(额度面板实测值)。
23
+ // 胶囊形的状态卡、气泡比较矮,要在设置 usesWidgetGlass 之前调小。
24
+ @property(nonatomic) CGFloat edgeShadeHeight;
25
+ @property(nonatomic) CGFloat edgeShadeAlpha;
26
+ - (instancetype)initWithFrame:(NSRect)frame material:(NSVisualEffectMaterial)material
27
+ appearance:(NSAppearanceName)appearance cornerRadius:(CGFloat)cornerRadius;
28
+ - (void)applyTheme;
29
+ // 只按当前档位更新压暗层透明度,不重建玻璃。
30
+ - (void)applyDimLevel;
31
+ @end