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
@@ -71,6 +71,10 @@ static NSDictionary *UsageByRemovingInactiveQuotaWindows(NSDictionary *usage) {
71
71
  return result ?: usage;
72
72
  }
73
73
 
74
+ NSDictionary *UsageByRemovingExpiredQuotaWindows(NSDictionary *usage) {
75
+ return UsageByRemovingInactiveQuotaWindows(usage);
76
+ }
77
+
74
78
  // 同一个账号下的每个 Claude 会话都会把自己那次响应里的 rate_limits 抄到同一个文件上,
75
79
  // 而"响应更早、落盘更晚"在并发会话下完全正常。无条件覆盖时旧快照会盖掉新快照,面板上
76
80
  // 的剩余额度于是来回跳(实测 99% → 94% → 又回 99%)。同一窗口内官方用量只增不减,
@@ -81,20 +85,37 @@ static NSDictionary *UsageByRemovingInactiveQuotaWindows(NSDictionary *usage) {
81
85
  // 滚动、无条件接受归零"于是对 7 天窗口几乎每次都成立,这道防线等同于从未生效——
82
86
  // 2026-08-19 实测面板被一份 used=2% 的旧快照顶成剩余 98%,就是从这条分支进来的。
83
87
  // 真正的窗口滚动只可能发生在旧窗口到期之后,拿 now 和 storedReset 判断就够了。
88
+ //
89
+ // 用量真的下降(官方口径调整、临时提额)时单调性不成立,只能靠"这份快照来自更新的响应"
90
+ // 放行。freshSince / storedSince 就是两份快照各自对应响应的时刻(见 QuotaValueSince)。
91
+ // 原先这里是"上次接受已过 10 分钟就无条件放行",但 statusline 配了 refreshInterval 时,
92
+ // 每个开着的空闲会话每分钟都会把自己最后一次响应里的旧额度重报一遍:活跃会话一关,
93
+ // 10 分钟后面板就被某个空闲会话的旧值顶掉(2026-09-29 实测剩余 18% → 跳回 70%)。
84
94
  static BOOL ShouldAcceptQuotaWindow(id storedValue, NSDictionary *fresh, double windowMinutes,
85
- BOOL stale, NSTimeInterval now) {
95
+ NSTimeInterval freshSince, NSTimeInterval storedSince, NSTimeInterval now) {
86
96
  if (!QuotaWindowLooksCurrent(fresh, windowMinutes, now)) return NO;
87
97
  NSDictionary *stored = [storedValue isKindOfClass:NSDictionary.class] ? storedValue : nil;
88
98
  if (!stored) return YES;
89
99
  // 旧窗口确实到期了:新周期里用量归零是真的。
90
100
  if (now >= [stored[@"resets_at"] doubleValue]) return YES;
91
- if (stale) return YES;
92
- return [fresh[@"used_percentage"] doubleValue] >= [stored[@"used_percentage"] doubleValue];
101
+ if ([fresh[@"used_percentage"] doubleValue] >= [stored[@"used_percentage"] doubleValue]) return YES;
102
+ return freshSince > storedSince;
93
103
  }
94
104
 
95
- // 单调性判据只在旧快照还新鲜时成立。官方口径调整(例如临时提额)会让用量真的掉下去,
96
- // 这时旧值必须能被顶掉,否则面板会被永久钉在一个偏高的数字上。
97
- static const NSTimeInterval StaleQuotaSnapshotSeconds = 600.0;
105
+ // 一份快照对应的响应是什么时候拿到的。statusline 的 payload 不带这个时刻,只能按会话推断:
106
+ // 同一个会话重报的值和它上次一模一样,说明它没有拿到新响应,时刻沿用上次记下的;值变了
107
+ // 才是新响应,记为现在。第一次见到的会话记 0(未知)——它可能是早就开着的空闲会话,
108
+ // 不能凭"刚被看到"就当成最新;它下一次真的变了自然会拿到时刻。
109
+ static NSTimeInterval QuotaValueSince(NSDictionary *previous, NSDictionary *fresh, NSTimeInterval now) {
110
+ if (![previous isKindOfClass:NSDictionary.class]) return 0;
111
+ BOOL unchanged = [previous[@"used_percentage"] isEqual:fresh[@"used_percentage"]] &&
112
+ [previous[@"resets_at"] isEqual:fresh[@"resets_at"]];
113
+ return unchanged ? [previous[@"since"] doubleValue] : now;
114
+ }
115
+
116
+ // 会话记录只为判断"值有没有变",一天没再上报的会话早就关了;上限防止异常情况下无限增长。
117
+ static const NSTimeInterval QuotaSessionRecordTTL = 24 * 60 * 60;
118
+ static const NSUInteger QuotaSessionRecordLimit = 64;
98
119
 
99
120
  // 拿锁的重试上限。拿不到就放弃这次写入:并发写者手里的数据同样新鲜,跳过一次不丢信息,
100
121
  // 而无锁写入正是要避免的读改写交错。阻塞版 flock 没有超时,一个被 SIGSTOP 或卡在慢速
@@ -130,27 +151,55 @@ int RecordClaudeUsage(void) {
130
151
  ? [NSJSONSerialization JSONObjectWithData:existing options:0 error:nil] : nil;
131
152
  NSDictionary *stored = [storedValue isKindOfClass:NSDictionary.class] ? storedValue : nil;
132
153
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
133
- // 过期判据必须逐窗口记"上一次被接受的时刻"。用整个文件的写盘时间会让逃生阀失效:
134
- // 快照被判倒退而拒绝时文件照样被写,只要还有会话在持续上报,就永远到不了 10 分钟,
135
- // 于是官方真的下调用量时面板被永久钉住——正是这个阀门要防的情况。
136
- id acceptedValue = stored[@"accepted_at"];
137
- NSDictionary *accepted = [acceptedValue isKindOfClass:NSDictionary.class] ? acceptedValue : nil;
154
+ NSDictionary *storedSinceValue = [stored[@"value_since"] isKindOfClass:NSDictionary.class]
155
+ ? stored[@"value_since"] : @{};
156
+ NSMutableDictionary *sessions = [stored[@"sessions"] isKindOfClass:NSDictionary.class]
157
+ ? [stored[@"sessions"] mutableCopy] : [NSMutableDictionary dictionary];
158
+ // 没有 session_id 的 payload 无法区分"空闲重报"和"新响应",只按单调性判。
159
+ NSString *sessionID = [payload[@"session_id"] isKindOfClass:NSString.class] &&
160
+ [payload[@"session_id"] length] > 0 ? payload[@"session_id"] : nil;
161
+ NSDictionary *previousRecord = [sessions[sessionID] isKindOfClass:NSDictionary.class]
162
+ ? sessions[sessionID] : nil;
163
+ NSMutableDictionary *sessionRecord = [@{@"seen_at": @(now)} mutableCopy];
138
164
 
139
165
  NSMutableDictionary *merged = stored ? [stored mutableCopy] : [NSMutableDictionary dictionary];
140
- NSMutableDictionary *mergedAccepted = accepted ? [accepted mutableCopy] : [NSMutableDictionary dictionary];
166
+ [merged removeObjectForKey:@"accepted_at"]; // 上一版的逃生阀字段,已不再使用。
167
+ NSMutableDictionary *mergedSince = [storedSinceValue mutableCopy];
141
168
  NSDictionary *windowMinutes = @{@"five_hour": @(FiveHourWindowMinutes),
142
169
  @"seven_day": @(SevenDayWindowMinutes)};
143
170
  for (NSString *key in @[@"five_hour", @"seven_day"]) {
144
171
  NSDictionary *fresh = [limits[key] isKindOfClass:NSDictionary.class] ? limits[key] : nil;
145
172
  if (!fresh) continue; // 这次响应没带某个窗口时保留旧的:整体覆盖会让面板凭空少掉一个窗口。
146
- // accepted_at 缺失的是上一版写的文件,当过期处理,一次就能迁移过来。
147
- BOOL stale = now - [accepted[key] doubleValue] > StaleQuotaSnapshotSeconds;
173
+ NSTimeInterval freshSince = sessionID ? QuotaValueSince(previousRecord[key], fresh, now) : 0;
174
+ if (sessionID) {
175
+ sessionRecord[key] = @{@"used_percentage": fresh[@"used_percentage"] ?: NSNull.null,
176
+ @"resets_at": fresh[@"resets_at"] ?: NSNull.null,
177
+ @"since": @(freshSince)};
178
+ }
179
+ NSTimeInterval storedSince = [storedSinceValue[key] doubleValue];
148
180
  if (!ShouldAcceptQuotaWindow(stored[key], fresh, [windowMinutes[key] doubleValue],
149
- stale, now)) continue;
181
+ freshSince, storedSince, now)) continue;
150
182
  merged[key] = fresh;
151
- mergedAccepted[key] = @(now);
183
+ // 按单调性收下的旧响应不能把时刻往回拨,否则更旧的快照就能借它反超。
184
+ mergedSince[key] = @(fmax(freshSince, storedSince));
185
+ }
186
+ merged[@"value_since"] = mergedSince;
187
+
188
+ if (sessionID) sessions[sessionID] = sessionRecord;
189
+ for (NSString *key in sessions.allKeys) {
190
+ NSDictionary *record = [sessions[key] isKindOfClass:NSDictionary.class] ? sessions[key] : nil;
191
+ if (!record || now - [record[@"seen_at"] doubleValue] > QuotaSessionRecordTTL) {
192
+ [sessions removeObjectForKey:key];
193
+ }
194
+ }
195
+ if (sessions.count > QuotaSessionRecordLimit) {
196
+ NSArray *oldestFirst = [sessions keysSortedByValueUsingComparator:^NSComparisonResult(id left, id right) {
197
+ return [left[@"seen_at"] compare:right[@"seen_at"]];
198
+ }];
199
+ [sessions removeObjectsForKeys:[oldestFirst subarrayWithRange:
200
+ NSMakeRange(0, sessions.count - QuotaSessionRecordLimit)]];
152
201
  }
153
- merged[@"accepted_at"] = mergedAccepted;
202
+ merged[@"sessions"] = sessions;
154
203
  // 最后一次写盘时间。不再参与任何判据,只留给排查用。
155
204
  merged[@"written_at"] = @(now);
156
205
 
@@ -172,7 +221,9 @@ NSDictionary *ClaudeRateLimits(void) {
172
221
  if (![limits isKindOfClass:NSDictionary.class]) return nil;
173
222
  id fiveHour = [limits[@"five_hour"] isKindOfClass:NSDictionary.class] ? limits[@"five_hour"] : NSNull.null;
174
223
  id week = [limits[@"seven_day"] isKindOfClass:NSDictionary.class] ? limits[@"seven_day"] : NSNull.null;
175
- return @{@"fiveHour": fiveHour, @"week": week};
224
+ // 快照只在有会话上报时更新。窗口到期后没人再报,旧百分比会一直挂着(实测 5 小时窗口
225
+ // 重置后面板仍显示剩余 0%),与 Codex 同样按 resets_at 清掉已经翻篇的窗口。
226
+ return UsageByRemovingInactiveQuotaWindows(@{@"fiveHour": fiveHour, @"week": week});
176
227
  }
177
228
 
178
229
  NSDictionary *LatestClaudeUsage(void) {
@@ -5,6 +5,7 @@
5
5
  #import <CoreServices/CoreServices.h>
6
6
  #import <fcntl.h>
7
7
  #import <unistd.h>
8
+ #import <sys/stat.h>
8
9
 
9
10
  // 读取与聚合全部跑在这条串行队列上,主线程只收结果。两个 reader 都不加锁,线程安全完全
10
11
  // 依赖“只有这条队列碰它们”这一条约束:FSEvents 流、Claude 的 vnode source、定时刷新、
@@ -31,10 +32,37 @@
31
32
  - (NSDictionary *)usageByApplyingLiveCodexUsage:(NSDictionary *)sessionUsage;
32
33
  @end
33
34
 
34
- // App Server 是服务端当前额度的权威源;会话日志只在成功响应落盘时才更新。短暂失败时
35
- // 留出一小段缓存寿命,既不因一次网络抖动闪回旧日志,也不会把实时值永久钉在界面上。
35
+ // App Server 是服务端当前额度的权威源;会话日志只在成功响应落盘时才更新。实时值的窗口
36
+ // 百分比不设寿命:它和会话快照按 sampledAt 比新旧(见 CodexUsageByApplyingLiveUsage),
37
+ // 窗口翻篇由 resets_at 兜底。只有"额度受限"标记有寿命——它没有窗口归属,实时查询连续
38
+ // 失败时不能让一次旧的受限结论一直挂着。
36
39
  static const NSTimeInterval CodexLiveUsageTTL = 5 * 60.0;
37
40
 
41
+ static NSDictionary *LoadCodexLiveUsage(void) {
42
+ NSData *data = [NSData dataWithContentsOfFile:CodexLiveUsagePath()];
43
+ id value = data.length > 0 ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
44
+ if (![value isKindOfClass:NSDictionary.class]) return nil;
45
+ NSDictionary *usage = value;
46
+ if (![usage[@"sampledAt"] isKindOfClass:NSNumber.class]) return nil;
47
+ for (NSString *key in @[@"fiveHour", @"week"]) {
48
+ id quota = usage[key];
49
+ if (quota && quota != NSNull.null && ![quota isKindOfClass:NSDictionary.class]) return nil;
50
+ }
51
+ return usage;
52
+ }
53
+
54
+ static void SaveCodexLiveUsage(NSDictionary *usage) {
55
+ NSData *json = [NSJSONSerialization isValidJSONObject:usage]
56
+ ? [NSJSONSerialization dataWithJSONObject:usage options:0 error:nil] : nil;
57
+ if (!json) return;
58
+ NSString *path = CodexLiveUsagePath();
59
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
60
+ withIntermediateDirectories:YES attributes:nil error:nil];
61
+ if ([json writeToFile:path options:NSDataWritingAtomic error:nil]) {
62
+ chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
63
+ }
64
+ }
65
+
38
66
  static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
39
67
  void *clientCallBackInfo, size_t numEvents, void *eventPaths,
40
68
  const FSEventStreamEventFlags eventFlags[],
@@ -86,6 +114,10 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
86
114
  // 桌宠是唯一的常驻读取者,摘要缓存由它维护并落盘。
87
115
  _codexReader.persistsCache = YES;
88
116
  _claudeReader.persistsCache = YES;
117
+ // 桌宠随最后一个客户端退出,下次启动时 App Server 要几秒才回话。这段时间先用上次
118
+ // 存下的实时值,否则面板会先显示会话日志里可能已经过时十几个小时的快照。
119
+ _codexLiveUsage = LoadCodexLiveUsage();
120
+ _codexLiveUsageUpdatedAt = [_codexLiveUsage[@"sampledAt"] doubleValue];
89
121
  __weak typeof(self) weakSelf = self;
90
122
  _codexRateLimitsReader.liveUsageHandler = ^(NSDictionary *liveUsage) {
91
123
  dispatch_async(weakSelf.queue, ^{
@@ -93,6 +125,7 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
93
125
  if (!strongSelf || !strongSelf.started) return;
94
126
  strongSelf.codexLiveUsage = liveUsage;
95
127
  strongSelf.codexLiveUsageUpdatedAt = NSDate.date.timeIntervalSince1970;
128
+ SaveCodexLiveUsage(liveUsage);
96
129
  strongSelf.codexUsage = [strongSelf usageByApplyingLiveCodexUsage:
97
130
  strongSelf.codexReader.usage ?: strongSelf.codexUsage];
98
131
  [strongSelf publishChange];
@@ -103,14 +136,16 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
103
136
  }
104
137
 
105
138
  - (NSDictionary *)usageByApplyingLiveCodexUsage:(NSDictionary *)sessionUsage {
106
- if (self.codexLiveUsage && NSDate.date.timeIntervalSince1970 -
139
+ NSDictionary *live = self.codexLiveUsage;
140
+ if (!live) return sessionUsage;
141
+ if (live[@"exhaustedAt"] && NSDate.date.timeIntervalSince1970 -
107
142
  self.codexLiveUsageUpdatedAt > CodexLiveUsageTTL) {
108
- self.codexLiveUsage = nil;
109
- self.codexLiveUsageUpdatedAt = 0;
143
+ NSMutableDictionary *withoutExhaustion = [live mutableCopy];
144
+ [withoutExhaustion removeObjectForKey:@"exhaustedAt"];
145
+ live = withoutExhaustion;
110
146
  }
111
- return self.codexLiveUsage
112
- ? CodexUsageByApplyingLiveUsage(sessionUsage, self.codexLiveUsage)
113
- : sessionUsage;
147
+ // 存下来的实时值可能是好几个小时前的,窗口早已翻篇,合并后要再按 resets_at 过一遍。
148
+ return UsageByRemovingExpiredQuotaWindows(CodexUsageByApplyingLiveUsage(sessionUsage, live));
114
149
  }
115
150
  // 回调交给主线程:下游全是 UI(面板重排、气泡定位、系统通知)。
116
151
  - (void)publishChange {
@@ -0,0 +1,19 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // 菜单里的单选行。普通 NSMenuItem 点完菜单就收起,想连着对比几个档位就得反复右键;
4
+ // 自绘行视图收到点击时菜单不会关闭。同一 group 的行互斥勾选,点击后同一菜单里所有行
5
+ // 重新计算 enabledHandler,让「切到经典主题后压暗档位置灰」这类联动当场生效。
6
+ @interface MenuChoiceRowView : NSView
7
+ @property(nonatomic, copy) NSString *title;
8
+ @property(nonatomic, copy) NSString *group;
9
+ @property(nonatomic) BOOL checked;
10
+ @property(nonatomic) BOOL enabled;
11
+ @property(nonatomic) CGFloat indentation;
12
+ @property(nonatomic, strong) id representedObject;
13
+ @property(nonatomic, weak) id target;
14
+ @property(nonatomic) SEL action;
15
+ @property(nonatomic, copy) BOOL (^enabledHandler)(void);
16
+ + (NSMenuItem *)addToMenu:(NSMenu *)menu title:(NSString *)title group:(NSString *)group
17
+ representedObject:(id)representedObject checked:(BOOL)checked
18
+ target:(id)target action:(SEL)action width:(CGFloat)width;
19
+ @end
@@ -0,0 +1,96 @@
1
+ #import "MenuChoiceRow.h"
2
+
3
+ @implementation MenuChoiceRowView
4
+ + (NSMenuItem *)addToMenu:(NSMenu *)menu title:(NSString *)title group:(NSString *)group
5
+ representedObject:(id)representedObject checked:(BOOL)checked
6
+ target:(id)target action:(SEL)action width:(CGFloat)width {
7
+ // item 要有 action 才会被菜单高亮。鼠标点击由行视图自己处理(菜单不关);
8
+ // 用键盘选中后按回车走的是这个 action,行为与点击一致,菜单照常关闭。
9
+ NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title action:@selector(chooseFromMenuItem:)
10
+ keyEquivalent:@""];
11
+ MenuChoiceRowView *row = [[MenuChoiceRowView alloc] initWithFrame:NSMakeRect(0, 0, width, 24)];
12
+ row.autoresizingMask = NSViewWidthSizable;
13
+ row.title = title;
14
+ row.group = group;
15
+ row.representedObject = representedObject;
16
+ row.checked = checked;
17
+ row.enabled = YES;
18
+ row.target = target;
19
+ row.action = action;
20
+ [row setAccessibilityRole:NSAccessibilityRadioButtonRole];
21
+ [row setAccessibilityLabel:title];
22
+ item.target = row;
23
+ item.view = row;
24
+ [menu addItem:item];
25
+ return item;
26
+ }
27
+ - (void)chooseFromMenuItem:(id)sender { [self choose]; }
28
+ // 手绘行不是 NSButton,VoiceOver 的"按下"要自己接到 choose 上。
29
+ - (BOOL)accessibilityPerformPress {
30
+ if (!self.enabled) return NO;
31
+ [self choose];
32
+ return YES;
33
+ }
34
+ // 置灰的行不让菜单高亮,和系统禁用项一致。
35
+ - (BOOL)validateMenuItem:(NSMenuItem *)menuItem { return self.enabled; }
36
+ - (void)setChecked:(BOOL)checked {
37
+ _checked = checked;
38
+ [self setAccessibilityValue:@(checked)];
39
+ self.needsDisplay = YES;
40
+ }
41
+ - (void)setEnabled:(BOOL)enabled {
42
+ _enabled = enabled;
43
+ [self setAccessibilityEnabled:enabled];
44
+ self.needsDisplay = YES;
45
+ }
46
+ // 不实现 mouseDown: 的话按下事件会沿响应链交给菜单,菜单会当作一次普通选择然后收起。
47
+ - (void)mouseDown:(NSEvent *)event {}
48
+ - (void)mouseUp:(NSEvent *)event {
49
+ NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
50
+ if (NSPointInRect(point, self.bounds)) [self choose];
51
+ }
52
+ - (void)choose {
53
+ if (!self.enabled || self.checked) return;
54
+ [NSApp sendAction:self.action to:self.target from:self];
55
+ for (NSMenuItem *item in self.enclosingMenuItem.menu.itemArray) {
56
+ if (![item.view isKindOfClass:MenuChoiceRowView.class]) continue;
57
+ MenuChoiceRowView *row = (MenuChoiceRowView *)item.view;
58
+ if ([row.group isEqualToString:self.group]) row.checked = row == self;
59
+ if (row.enabledHandler) row.enabled = row.enabledHandler();
60
+ }
61
+ [self.enclosingMenuItem.menu update];
62
+ }
63
+ - (void)drawRect:(NSRect)dirtyRect {
64
+ // 高亮跟随菜单自己的高亮项,而不是自己跟踪鼠标进出:菜单跟踪期间 mouseExited 经常
65
+ // 收不到,自己跟踪会让划过的每一行都停在高亮。菜单同一时刻只高亮一项,切换时会重绘视图。
66
+ BOOL highlighted = self.enclosingMenuItem.isHighlighted && self.enabled;
67
+ if (highlighted) {
68
+ [NSColor.selectedContentBackgroundColor setFill];
69
+ [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds, 5, 0)
70
+ xRadius:6 yRadius:6] fill];
71
+ }
72
+ NSColor *textColor = !self.enabled ? NSColor.tertiaryLabelColor
73
+ : (highlighted ? NSColor.selectedMenuItemTextColor : NSColor.labelColor);
74
+ CGFloat x = 12 + self.indentation;
75
+ if (self.checked) {
76
+ NSImageSymbolConfiguration *configuration = [NSImageSymbolConfiguration
77
+ configurationWithPointSize:11 weight:NSFontWeightSemibold];
78
+ NSImage *mark = [[NSImage imageWithSystemSymbolName:@"checkmark"
79
+ accessibilityDescription:nil] imageWithSymbolConfiguration:configuration];
80
+ NSImage *tinted = [NSImage imageWithSize:mark.size flipped:NO
81
+ drawingHandler:^BOOL(NSRect rect) {
82
+ [mark drawInRect:rect];
83
+ [textColor set];
84
+ NSRectFillUsingOperation(rect, NSCompositingOperationSourceAtop);
85
+ return YES;
86
+ }];
87
+ [tinted drawInRect:NSMakeRect(x, (NSHeight(self.bounds) - mark.size.height) / 2.0,
88
+ mark.size.width, mark.size.height)];
89
+ }
90
+ NSDictionary *attributes = @{NSFontAttributeName: [NSFont menuFontOfSize:13],
91
+ NSForegroundColorAttributeName: textColor};
92
+ NSSize size = [self.title sizeWithAttributes:attributes];
93
+ [self.title drawAtPoint:NSMakePoint(x + 18, (NSHeight(self.bounds) - size.height) / 2.0)
94
+ withAttributes:attributes];
95
+ }
96
+ @end
@@ -0,0 +1,15 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // 菜单里的悬停说明。系统 toolTip 只在 App 处于激活状态时显示,而桌宠窗口是
4
+ // NonactivatingPanel,右键弹菜单时前台通常还是终端,于是说明时有时无。这里自己画一个
5
+ // 浮窗,不依赖激活状态。
6
+ @interface MenuHint : NSObject
7
+ // 悬停一段时间后在 rect(屏幕坐标)下方显示 text;刚显示过别的说明时立即显示。
8
+ + (void)scheduleText:(NSString *)text belowScreenRect:(NSRect)rect;
9
+ + (void)cancel;
10
+ @end
11
+
12
+ // 菜单自绘行。设置 hint 后,鼠标停在行内任意位置(包括其中的开关)都会显示说明。
13
+ @interface MenuHintRowView : NSView
14
+ @property(nonatomic, copy) NSString *hint;
15
+ @end
@@ -0,0 +1,128 @@
1
+ #import "MenuHintView.h"
2
+
3
+ // 与系统 toolTip 的节奏接近:首次悬停要停稳一会儿,刚看过一条再移到相邻行时立即显示。
4
+ static const NSTimeInterval MenuHintInitialDelay = 0.8;
5
+ static const NSTimeInterval MenuHintFollowupWindow = 0.5;
6
+ static const CGFloat MenuHintMaxTextWidth = 260.0;
7
+ static const CGFloat MenuHintPadding = 7.0;
8
+
9
+ static NSPanel *HintPanel;
10
+ static NSTextField *HintLabel;
11
+ static NSTimer *HintTimer;
12
+ static NSTimeInterval HintHiddenAt;
13
+
14
+ @implementation MenuHint
15
+ + (void)preparePanel {
16
+ if (HintPanel) return;
17
+ HintPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, 10, 10)
18
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
19
+ backing:NSBackingStoreBuffered defer:YES];
20
+ HintPanel.opaque = NO;
21
+ HintPanel.backgroundColor = NSColor.clearColor;
22
+ HintPanel.hasShadow = YES;
23
+ HintPanel.ignoresMouseEvents = YES;
24
+ // 菜单窗口在 NSPopUpMenuWindowLevel,低于它会被菜单挡住。
25
+ HintPanel.level = NSPopUpMenuWindowLevel + 1;
26
+ HintPanel.collectionBehavior = NSWindowCollectionBehaviorTransient |
27
+ NSWindowCollectionBehaviorMoveToActiveSpace;
28
+
29
+ NSVisualEffectView *background = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(0, 0, 10, 10)];
30
+ background.material = NSVisualEffectMaterialToolTip;
31
+ background.blendingMode = NSVisualEffectBlendingModeBehindWindow;
32
+ background.state = NSVisualEffectStateActive;
33
+ background.wantsLayer = YES;
34
+ background.layer.cornerRadius = 6.0;
35
+ background.layer.masksToBounds = YES;
36
+ background.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
37
+
38
+ HintLabel = [NSTextField wrappingLabelWithString:@""];
39
+ HintLabel.font = [NSFont toolTipsFontOfSize:0];
40
+ HintLabel.textColor = NSColor.labelColor;
41
+ HintLabel.selectable = NO;
42
+ [background addSubview:HintLabel];
43
+ HintPanel.contentView = background;
44
+ }
45
+ + (void)scheduleText:(NSString *)text belowScreenRect:(NSRect)rect {
46
+ [HintTimer invalidate];
47
+ HintTimer = nil;
48
+ if (text.length == 0) {
49
+ [self cancel];
50
+ return;
51
+ }
52
+ BOOL followup = HintPanel.isVisible ||
53
+ NSDate.date.timeIntervalSince1970 - HintHiddenAt < MenuHintFollowupWindow;
54
+ // 菜单打开期间主线程跑在 event tracking 模式,默认模式的定时器不会触发。
55
+ HintTimer = [NSTimer timerWithTimeInterval:followup ? 0.05 : MenuHintInitialDelay repeats:NO
56
+ block:^(NSTimer *timer) {
57
+ HintTimer = nil;
58
+ [self showText:text belowScreenRect:rect];
59
+ }];
60
+ [NSRunLoop.mainRunLoop addTimer:HintTimer forMode:NSRunLoopCommonModes];
61
+ }
62
+ + (void)showText:(NSString *)text belowScreenRect:(NSRect)rect {
63
+ [self preparePanel];
64
+ HintLabel.stringValue = text;
65
+ NSSize textSize = [HintLabel.cell cellSizeForBounds:
66
+ NSMakeRect(0, 0, MenuHintMaxTextWidth, CGFLOAT_MAX)];
67
+ textSize.width = ceil(MIN(textSize.width, MenuHintMaxTextWidth));
68
+ textSize.height = ceil(textSize.height);
69
+ HintLabel.frame = NSMakeRect(MenuHintPadding, MenuHintPadding - 2, textSize.width, textSize.height);
70
+ NSSize panelSize = NSMakeSize(textSize.width + MenuHintPadding * 2,
71
+ textSize.height + MenuHintPadding * 2 - 4);
72
+
73
+ NSPoint mouse = NSEvent.mouseLocation;
74
+ NSScreen *screen = NSScreen.mainScreen ?: NSScreen.screens.firstObject;
75
+ for (NSScreen *candidate in NSScreen.screens) {
76
+ if (NSPointInRect(mouse, candidate.frame)) {
77
+ screen = candidate;
78
+ break;
79
+ }
80
+ }
81
+ NSRect visible = screen.visibleFrame;
82
+ // 贴着行的下沿、从鼠标所在位置起,与系统 toolTip 的位置习惯一致;下方放不下就放到行上方。
83
+ CGFloat x = MIN(MAX(mouse.x, NSMinX(visible)), NSMaxX(visible) - panelSize.width);
84
+ CGFloat y = NSMinY(rect) - panelSize.height - 2;
85
+ if (y < NSMinY(visible)) y = NSMaxY(rect) + 2;
86
+ [HintPanel setFrame:NSMakeRect(x, y, panelSize.width, panelSize.height) display:YES];
87
+ [HintPanel orderFront:nil];
88
+ }
89
+ + (void)cancel {
90
+ [HintTimer invalidate];
91
+ HintTimer = nil;
92
+ if (HintPanel.isVisible) {
93
+ HintHiddenAt = NSDate.date.timeIntervalSince1970;
94
+ [HintPanel orderOut:nil];
95
+ }
96
+ }
97
+ @end
98
+
99
+ @implementation MenuHintRowView {
100
+ NSTrackingArea *_hintTrackingArea;
101
+ }
102
+ - (void)setHint:(NSString *)hint {
103
+ _hint = [hint copy];
104
+ [self setAccessibilityHelp:hint];
105
+ }
106
+ // 菜单属于前台之外的 App 时也要收到进出事件,所以用 ActiveAlways。
107
+ - (void)updateTrackingAreas {
108
+ [super updateTrackingAreas];
109
+ if (_hintTrackingArea) [self removeTrackingArea:_hintTrackingArea];
110
+ _hintTrackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect
111
+ options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect
112
+ owner:self userInfo:nil];
113
+ [self addTrackingArea:_hintTrackingArea];
114
+ }
115
+ - (void)mouseEntered:(NSEvent *)event {
116
+ if (self.hint.length == 0 || !self.window) return;
117
+ NSRect rect = [self.window convertRectToScreen:[self convertRect:self.bounds toView:nil]];
118
+ [MenuHint scheduleText:self.hint belowScreenRect:rect];
119
+ }
120
+ - (void)mouseExited:(NSEvent *)event {
121
+ [MenuHint cancel];
122
+ }
123
+ // 菜单关闭时行视图会被移出窗口,此时不一定还能收到 mouseExited。
124
+ - (void)viewWillMoveToWindow:(NSWindow *)newWindow {
125
+ [super viewWillMoveToWindow:newWindow];
126
+ if (!newWindow && self.hint.length > 0) [MenuHint cancel];
127
+ }
128
+ @end