cc-pets 2.2.0 → 2.3.0

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 (173) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +85 -0
  4. package/CHANGELOG.zh-CN.md +85 -0
  5. package/CONTRIBUTING.md +28 -11
  6. package/CONTRIBUTING.zh-CN.md +23 -11
  7. package/README.md +127 -27
  8. package/README.zh-CN.md +104 -30
  9. package/Resources/zh-Hans.lproj/Localizable.strings +573 -17
  10. package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
  11. package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +89 -31
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +18 -4
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +90 -21
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
  16. package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +269 -0
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +13 -7
  19. package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +71 -47
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +16 -2
  22. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +110 -12
  23. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  24. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  25. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  26. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  27. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  35. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  37. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  38. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  39. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  41. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  43. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  44. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  45. package/Sources/CCPets/Pet/CCPetsImageLoader.h +5 -0
  46. package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +10 -2
  47. package/Sources/CCPets/Pet/CCPetsPetSize.h +10 -0
  48. package/Sources/CCPets/Pet/CCPetsPetSize.m +21 -0
  49. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  50. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  51. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +18 -2
  52. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +53 -22
  53. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +42 -2
  54. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  55. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  56. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  57. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  58. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  59. package/Sources/CCPets/Pet/PetView.m +635 -0
  60. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  61. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  62. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  63. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  64. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  65. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  66. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  67. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  68. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  69. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  70. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  71. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  72. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  73. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  74. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  75. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  76. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  77. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  78. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  79. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  80. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  81. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  82. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  83. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  84. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  85. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  86. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  87. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  88. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  89. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  90. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  91. package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +3 -0
  92. package/Sources/CCPets/UI/MenuPetSizeView.h +5 -0
  93. package/Sources/CCPets/UI/MenuPetSizeView.m +73 -0
  94. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  95. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  96. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  97. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  98. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  99. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  100. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  101. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  102. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  103. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  104. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  105. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  106. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  107. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  108. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  109. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  110. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  111. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  112. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  113. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  114. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  115. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  116. package/THIRD_PARTY_NOTICES.md +1 -1
  117. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  118. package/bin/cc-pets +8 -6
  119. package/bin/claude-with-pet +10 -2
  120. package/bin/codex-with-pet +13 -5
  121. package/package.json +1 -1
  122. package/scripts/build.sh +7 -3
  123. package/scripts/i18n.zsh +9 -52
  124. package/scripts/install-app.sh +4 -0
  125. package/scripts/install-shell-integration.sh +17 -10
  126. package/scripts/uninstall-shell-integration.sh +6 -1
  127. package/Sources/CCPets/CCPetsAppDelegate+Settings.m +0 -226
  128. package/Sources/CCPets/CCPetsEvents.h +0 -10
  129. package/Sources/CCPets/CCPetsImageLoader.h +0 -4
  130. package/Sources/CCPets/CCPetsUsage.h +0 -36
  131. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  132. package/Sources/CCPets/PetView.m +0 -1806
  133. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  134. package/scripts/bridge/cli.mjs +0 -237
  135. package/scripts/bridge/core.mjs +0 -228
  136. package/scripts/bridge/hook.mjs +0 -150
  137. package/scripts/bridge/install.mjs +0 -311
  138. package/scripts/bridge/mcp-server.mjs +0 -308
  139. package/scripts/bridge/options.mjs +0 -87
  140. package/scripts/bridge/process.mjs +0 -151
  141. package/scripts/bridge/reservations.mjs +0 -248
  142. package/scripts/bridge/store.mjs +0 -433
  143. package/scripts/bridge/watch.mjs +0 -69
  144. package/scripts/check-l10n.mjs +0 -168
  145. package/scripts/configure-updater.mjs +0 -43
  146. package/scripts/detect-cli.mjs +0 -68
  147. package/scripts/doctor.mjs +0 -470
  148. package/scripts/i18n.mjs +0 -122
  149. package/scripts/install-claude-hooks.mjs +0 -253
  150. package/scripts/install-codex-hooks.mjs +0 -78
  151. package/scripts/integration-markers.mjs +0 -51
  152. package/scripts/locales/zh-Hans.json +0 -366
  153. package/scripts/pet-store.mjs +0 -415
  154. package/scripts/uninstall-integrations.mjs +0 -205
  155. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  156. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  157. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  159. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  161. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  162. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  163. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  164. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  165. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  166. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  167. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  168. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  169. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  170. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  171. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  172. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  173. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -0,0 +1,816 @@
1
+ #import "CCPetsUIStyle.h"
2
+ #import <QuartzCore/QuartzCore.h>
3
+
4
+ static BOOL AppearanceIsDark(NSAppearance *appearance) {
5
+ return [[appearance bestMatchFromAppearancesWithNames:
6
+ @[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]] isEqualToString:NSAppearanceNameDarkAqua];
7
+ }
8
+
9
+ static NSColor *RGBA(uint32_t rgb, CGFloat alpha) {
10
+ return [NSColor colorWithSRGBRed:((rgb >> 16) & 0xff) / 255.0 green:((rgb >> 8) & 0xff) / 255.0
11
+ blue:(rgb & 0xff) / 255.0 alpha:alpha];
12
+ }
13
+
14
+ // 一对浅色 / 深色取值的动态色。
15
+ static NSColor *Dynamic(uint32_t light, CGFloat lightAlpha, uint32_t dark, CGFloat darkAlpha) {
16
+ NSColor *lightColor = RGBA(light, lightAlpha), *darkColor = RGBA(dark, darkAlpha);
17
+ return [NSColor colorWithName:nil dynamicProvider:^NSColor *(NSAppearance *appearance) {
18
+ return AppearanceIsDark(appearance) ? darkColor : lightColor;
19
+ }];
20
+ }
21
+
22
+ // 每个颜色只建一次:动态色本身就会随外观解析,没必要每次调用都新建。
23
+ #define CACHED_COLOR(expr) \
24
+ static NSColor *color; \
25
+ static dispatch_once_t once; \
26
+ dispatch_once(&once, ^{ color = (expr); }); \
27
+ return color
28
+
29
+ NSColor *CCPetsAccentColor(void) { CACHED_COLOR(Dynamic(0x0b8ea3, 1, 0x4fd3e6, 1)); }
30
+ NSColor *CCPetsAccentInkColor(void) { CACHED_COLOR(Dynamic(0xffffff, 1, 0x062a31, 1)); }
31
+ NSColor *CCPetsAccentFillColor(void) { CACHED_COLOR(Dynamic(0x0b8ea3, 1, 0x1592a5, 1)); }
32
+ NSColor *CCPetsBackgroundColor(void) { CACHED_COLOR(Dynamic(0xf6f7f9, 1, 0x1a1d22, 1)); }
33
+ NSColor *CCPetsCardColor(void) { CACHED_COLOR(Dynamic(0xffffff, 1, 0x24282e, 1)); }
34
+ NSColor *CCPetsLineColor(void) { CACHED_COLOR(Dynamic(0xe3e6ec, 1, 0x33383f, 1)); }
35
+ NSColor *CCPetsInkColor(void) { CACHED_COLOR(Dynamic(0x161b22, 1, 0xeceff3, 1)); }
36
+ NSColor *CCPetsSecondaryInkColor(void) { CACHED_COLOR(Dynamic(0x5a6472, 1, 0xa3acb8, 1)); }
37
+ NSColor *CCPetsTertiaryInkColor(void) { CACHED_COLOR(Dynamic(0x8c95a3, 1, 0x77808d, 1)); }
38
+ NSColor *CCPetsHoverColor(void) { CACHED_COLOR(Dynamic(0x162846, 0.05, 0xffffff, 0.05)); }
39
+ NSColor *CCPetsSelectionColor(void) { CACHED_COLOR(Dynamic(0x0e9db3, 0.13, 0x4fdceb, 0.16)); }
40
+ NSColor *CCPetsRingTrackColor(void) { CACHED_COLOR(Dynamic(0xe3e7ee, 1, 0x343a42, 1)); }
41
+
42
+ NSColor *CCPetsProviderColor(NSString *provider) {
43
+ static NSColor *claude, *codex;
44
+ static dispatch_once_t once;
45
+ dispatch_once(&once, ^{
46
+ claude = Dynamic(0xc8643b, 1, 0xe07a50, 1);
47
+ codex = Dynamic(0x3d4655, 1, 0xb9c2cf, 1);
48
+ });
49
+ return [provider.lowercaseString isEqualToString:@"claude"] ? claude : codex;
50
+ }
51
+
52
+ NSColor *CCPetsStatusColor(CCPetsStatusKind kind) {
53
+ static NSArray<NSColor *> *colors;
54
+ static dispatch_once_t once;
55
+ dispatch_once(&once, ^{
56
+ colors = @[Dynamic(0x8c95a3, 1, 0x8a93a0, 1), Dynamic(0x0b8ea3, 1, 0x4fd3e6, 1),
57
+ Dynamic(0xb86e00, 1, 0xf2b33d, 1), Dynamic(0x1f8a4c, 1, 0x4fc97f, 1),
58
+ Dynamic(0xc8352f, 1, 0xff7a70, 1)];
59
+ });
60
+ return colors[(NSUInteger)MAX(0, MIN(kind, (NSInteger)colors.count - 1))];
61
+ }
62
+
63
+ NSColor *CCPetsStatusBackgroundColor(CCPetsStatusKind kind) {
64
+ static NSArray<NSColor *> *colors;
65
+ static dispatch_once_t once;
66
+ dispatch_once(&once, ^{
67
+ colors = @[Dynamic(0x6e7887, 0.12, 0x8c96a5, 0.15), Dynamic(0x0b8ea3, 0.12, 0x4fd3e6, 0.14),
68
+ Dynamic(0xe59a00, 0.14, 0xf2b33d, 0.15), Dynamic(0x1f8a4c, 0.11, 0x4fc97f, 0.13),
69
+ Dynamic(0xc8352f, 0.11, 0xff7a70, 0.14)];
70
+ });
71
+ return colors[(NSUInteger)MAX(0, MIN(kind, (NSInteger)colors.count - 1))];
72
+ }
73
+
74
+ CCPetsStatusKind CCPetsStatusKindForAgentState(NSString *state) {
75
+ if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) return CCPetsStatusWarn;
76
+ if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) return CCPetsStatusError;
77
+ if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) return CCPetsStatusOK;
78
+ if (state.length == 0 || [state isEqualToString:@"idle"]) return CCPetsStatusIdle;
79
+ return CCPetsStatusWork;
80
+ }
81
+
82
+ const NSInteger CCPetsChartColorCount = 8;
83
+
84
+ // 浅色、深色两套都用色盲模拟校验过:相邻两色在红、绿色盲下色差不低于 8,正常视力下不低于 15。
85
+ NSColor *CCPetsChartColor(NSInteger slot) {
86
+ static NSArray<NSColor *> *colors;
87
+ static NSColor *other;
88
+ static dispatch_once_t once;
89
+ dispatch_once(&once, ^{
90
+ const uint32_t light[] = {0x1597ac, 0xe05c86, 0x6874dc, 0xdd9a1f, 0x9a62d0, 0x3fa577, 0x3a7fc6, 0x8a9a2b};
91
+ const uint32_t dark[] = {0x22a2b8, 0xd65f86, 0x7d87e8, 0xb8841f, 0xa77ad8, 0x3fa577, 0x4c95dc, 0x879733};
92
+ NSMutableArray<NSColor *> *list = [NSMutableArray array];
93
+ for (NSInteger index = 0; index < CCPetsChartColorCount; index++) {
94
+ [list addObject:Dynamic(light[index], 1, dark[index], 1)];
95
+ }
96
+ colors = list;
97
+ other = Dynamic(0x9aa3af, 1, 0x66707c, 1);
98
+ });
99
+ return slot >= 0 && slot < CCPetsChartColorCount ? colors[(NSUInteger)slot] : other;
100
+ }
101
+
102
+ NSTextField *CCPetsLabel(NSString *text, CGFloat size, NSFontWeight weight, NSColor *color) {
103
+ NSTextField *label = [NSTextField labelWithString:text ?: @""];
104
+ label.font = [NSFont systemFontOfSize:size > 0 ? size : NSFont.systemFontSize weight:weight];
105
+ label.textColor = color ?: CCPetsInkColor();
106
+ label.lineBreakMode = NSLineBreakByTruncatingTail;
107
+ return label;
108
+ }
109
+
110
+ NSTextField *CCPetsNumberLabel(NSString *text, CGFloat size, NSFontWeight weight, NSColor *color) {
111
+ NSTextField *label = CCPetsLabel(text, size, weight, color);
112
+ label.font = [NSFont monospacedDigitSystemFontOfSize:size > 0 ? size : NSFont.systemFontSize weight:weight];
113
+ return label;
114
+ }
115
+
116
+ @interface CCPetsWrappingField : NSTextField
117
+ @end
118
+
119
+ @implementation CCPetsWrappingField
120
+ - (void)layout {
121
+ [super layout];
122
+ CGFloat width = NSWidth(self.bounds);
123
+ if (width > 0 && fabs(self.preferredMaxLayoutWidth - width) > 0.5) {
124
+ self.preferredMaxLayoutWidth = width;
125
+ [self invalidateIntrinsicContentSize];
126
+ }
127
+ }
128
+ @end
129
+
130
+ NSTextField *CCPetsWrappingLabel(NSString *text, CGFloat size, NSFontWeight weight, NSColor *color) {
131
+ CCPetsWrappingField *label = [CCPetsWrappingField wrappingLabelWithString:text ?: @""];
132
+ label.font = [NSFont systemFontOfSize:size > 0 ? size : NSFont.systemFontSize weight:weight];
133
+ label.textColor = color ?: CCPetsInkColor();
134
+ [label setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
135
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
136
+ return label;
137
+ }
138
+
139
+ NSView *CCPetsMetricRow(NSArray<NSArray<NSString *> *> *items) {
140
+ NSMutableArray<NSView *> *cells = [NSMutableArray array];
141
+ for (NSArray<NSString *> *item in items) {
142
+ NSTextField *title = CCPetsLabel(item[0], 11, NSFontWeightRegular, CCPetsSecondaryInkColor());
143
+ NSTextField *value = CCPetsNumberLabel(item[1], 20, NSFontWeightBold, CCPetsInkColor());
144
+ NSTextField *detail = CCPetsLabel(item.count > 2 && item[2].length > 0 ? item[2] : @" ", 11,
145
+ NSFontWeightRegular, CCPetsTertiaryInkColor());
146
+ NSView *heading = title;
147
+ if (item.count > 3 && item[3].length > 0) {
148
+ NSImageView *icon = [NSImageView imageViewWithImage:
149
+ [NSImage imageWithSystemSymbolName:@"info.circle" accessibilityDescription:item[3]]];
150
+ icon.symbolConfiguration = [NSImageSymbolConfiguration configurationWithPointSize:10
151
+ weight:NSFontWeightRegular];
152
+ icon.contentTintColor = CCPetsTertiaryInkColor();
153
+ icon.toolTip = item[3];
154
+ [icon setContentHuggingPriority:NSLayoutPriorityRequired
155
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
156
+ NSStackView *line = [NSStackView stackViewWithViews:@[title, icon]];
157
+ line.alignment = NSLayoutAttributeCenterY;
158
+ line.spacing = 3;
159
+ heading = line;
160
+ }
161
+ NSStackView *stack = [NSStackView stackViewWithViews:@[heading, value, detail]];
162
+ stack.orientation = NSUserInterfaceLayoutOrientationVertical;
163
+ stack.alignment = NSLayoutAttributeLeading;
164
+ stack.spacing = 3;
165
+ for (NSTextField *label in @[title, value, detail]) {
166
+ [label setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
167
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
168
+ }
169
+ // 格宽不跟着数字长短走,数字变了也不会左右挪。
170
+ NSView *cell = [NSView new];
171
+ stack.translatesAutoresizingMaskIntoConstraints = NO;
172
+ [cell addSubview:stack];
173
+ CGFloat inset = cells.count == 0 ? 0 : 12;
174
+ [NSLayoutConstraint activateConstraints:@[
175
+ [stack.leadingAnchor constraintEqualToAnchor:cell.leadingAnchor constant:inset],
176
+ [stack.trailingAnchor constraintLessThanOrEqualToAnchor:cell.trailingAnchor constant:-4],
177
+ [stack.topAnchor constraintEqualToAnchor:cell.topAnchor],
178
+ [stack.bottomAnchor constraintEqualToAnchor:cell.bottomAnchor],
179
+ ]];
180
+ if (cells.count > 0) {
181
+ CCPetsLineView *rule = [CCPetsLineView new];
182
+ rule.translatesAutoresizingMaskIntoConstraints = NO;
183
+ [cell addSubview:rule];
184
+ [NSLayoutConstraint activateConstraints:@[
185
+ [rule.leadingAnchor constraintEqualToAnchor:cell.leadingAnchor],
186
+ [rule.widthAnchor constraintEqualToConstant:1],
187
+ [rule.topAnchor constraintEqualToAnchor:cell.topAnchor constant:2],
188
+ [rule.bottomAnchor constraintEqualToAnchor:cell.bottomAnchor constant:-2],
189
+ ]];
190
+ }
191
+ [cells addObject:cell];
192
+ }
193
+ NSStackView *row = [NSStackView stackViewWithViews:cells];
194
+ row.distribution = NSStackViewDistributionFillEqually;
195
+ row.alignment = NSLayoutAttributeTop;
196
+ row.spacing = 12;
197
+ return row;
198
+ }
199
+
200
+ @implementation CCPetsCardView
201
+
202
+ - (instancetype)initWithFrame:(NSRect)frame {
203
+ if ((self = [super initWithFrame:frame])) {
204
+ self.wantsLayer = YES;
205
+ _cornerRadius = 10;
206
+ self.layer.cornerCurve = kCACornerCurveContinuous;
207
+ self.layer.borderWidth = 1;
208
+ self.layer.masksToBounds = YES;
209
+ }
210
+ return self;
211
+ }
212
+
213
+ - (BOOL)wantsUpdateLayer {
214
+ return YES;
215
+ }
216
+
217
+ // 颜色放在 updateLayer 里取,切换深浅色时 AppKit 会再调一次,CGColor 才会跟着变。
218
+ - (void)updateLayer {
219
+ self.layer.cornerRadius = self.cornerRadius;
220
+ self.layer.backgroundColor = (self.fillColor ?: CCPetsCardColor()).CGColor;
221
+ self.layer.borderColor = (self.selected ? CCPetsAccentColor() : CCPetsLineColor()).CGColor;
222
+ self.layer.borderWidth = self.selected ? 1.5 : 1;
223
+ }
224
+
225
+ - (void)setSelected:(BOOL)selected {
226
+ _selected = selected;
227
+ self.needsDisplay = YES;
228
+ }
229
+
230
+ - (void)setCornerRadius:(CGFloat)cornerRadius {
231
+ _cornerRadius = cornerRadius;
232
+ self.needsDisplay = YES;
233
+ }
234
+
235
+ - (void)setFillColor:(NSColor *)fillColor {
236
+ _fillColor = fillColor;
237
+ self.needsDisplay = YES;
238
+ }
239
+
240
+ - (void)setStripeColor:(NSColor *)stripeColor {
241
+ _stripeColor = stripeColor;
242
+ self.needsLayout = YES;
243
+ self.needsDisplay = YES;
244
+ }
245
+
246
+ - (void)layout {
247
+ [super layout];
248
+ CALayer *stripe = nil;
249
+ for (CALayer *layer in self.layer.sublayers) {
250
+ if ([layer.name isEqualToString:@"stripe"]) stripe = layer;
251
+ }
252
+ if (!self.stripeColor) {
253
+ [stripe removeFromSuperlayer];
254
+ return;
255
+ }
256
+ if (!stripe) {
257
+ stripe = [CALayer layer];
258
+ stripe.name = @"stripe";
259
+ [self.layer addSublayer:stripe];
260
+ }
261
+ [CATransaction begin];
262
+ [CATransaction setDisableActions:YES];
263
+ stripe.frame = CGRectMake(0, 0, 3, NSHeight(self.bounds));
264
+ [self.effectiveAppearance performAsCurrentDrawingAppearance:^{
265
+ stripe.backgroundColor = self.stripeColor.CGColor;
266
+ }];
267
+ [CATransaction commit];
268
+ }
269
+
270
+ - (void)viewDidChangeEffectiveAppearance {
271
+ [super viewDidChangeEffectiveAppearance];
272
+ self.needsLayout = YES;
273
+ }
274
+
275
+ @end
276
+
277
+ @implementation CCPetsTileView
278
+
279
+ - (void)mouseDown:(NSEvent *)event {
280
+ // 按下不立刻触发,松开时还在卡片上才算一次点击,和按钮一个手感。
281
+ }
282
+
283
+ - (void)mouseUp:(NSEvent *)event {
284
+ NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
285
+ if (self.onClick && NSPointInRect(point, self.bounds)) self.onClick();
286
+ }
287
+
288
+ - (BOOL)acceptsFirstMouse:(NSEvent *)event {
289
+ return YES;
290
+ }
291
+
292
+ - (void)resetCursorRects {
293
+ if (self.onClick) [self addCursorRect:self.bounds cursor:NSCursor.pointingHandCursor];
294
+ }
295
+
296
+ - (BOOL)isAccessibilityElement {
297
+ return self.onClick != nil;
298
+ }
299
+
300
+ - (NSAccessibilityRole)accessibilityRole {
301
+ return NSAccessibilityButtonRole;
302
+ }
303
+
304
+ - (BOOL)accessibilityPerformPress {
305
+ if (!self.onClick) return NO;
306
+ self.onClick();
307
+ return YES;
308
+ }
309
+
310
+ @end
311
+
312
+ @implementation CCPetsPillButton
313
+
314
+ - (void)setEnabled:(BOOL)enabled {
315
+ [super setEnabled:enabled];
316
+ self.alphaValue = enabled ? 1.0 : 0.55;
317
+ [self.window invalidateCursorRectsForView:self];
318
+ }
319
+
320
+ - (instancetype)initWithFrame:(NSRect)frame {
321
+ if ((self = [super initWithFrame:frame])) {
322
+ self.bordered = NO;
323
+ self.wantsLayer = YES;
324
+ self.font = [NSFont systemFontOfSize:11 weight:NSFontWeightSemibold];
325
+ [self.widthAnchor constraintEqualToConstant:56].active = YES;
326
+ [self.heightAnchor constraintEqualToConstant:22].active = YES;
327
+ }
328
+ return self;
329
+ }
330
+
331
+ - (void)setTitle:(NSString *)title {
332
+ // 白字压在饱和色上,深浅色下都够对比度,所以不跟随外观。
333
+ self.attributedTitle = [[NSAttributedString alloc] initWithString:title attributes:@{
334
+ NSFontAttributeName: [NSFont systemFontOfSize:11 weight:NSFontWeightSemibold],
335
+ NSForegroundColorAttributeName: NSColor.whiteColor}];
336
+ }
337
+
338
+ - (void)setFillColor:(NSColor *)fillColor {
339
+ _fillColor = fillColor;
340
+ [self applyFill];
341
+ }
342
+
343
+ // 按钮要靠 cell 画标题,不能走 updateLayer;底色在外观变化时手动按当前外观解析一次。
344
+ - (void)applyFill {
345
+ self.layer.cornerRadius = 11;
346
+ [self.effectiveAppearance performAsCurrentDrawingAppearance:^{
347
+ self.layer.backgroundColor = (self.fillColor ?: CCPetsAccentColor()).CGColor;
348
+ }];
349
+ }
350
+
351
+ - (void)viewDidChangeEffectiveAppearance {
352
+ [super viewDidChangeEffectiveAppearance];
353
+ [self applyFill];
354
+ }
355
+
356
+ - (void)viewDidMoveToWindow {
357
+ [super viewDidMoveToWindow];
358
+ [self applyFill];
359
+ }
360
+
361
+ - (void)resetCursorRects {
362
+ [self addCursorRect:self.bounds cursor:self.enabled ? NSCursor.pointingHandCursor : NSCursor.arrowCursor];
363
+ }
364
+
365
+ @end
366
+
367
+ // 关闭时的底轨:半透明,压在卡片上和系统开关一个深浅。
368
+ static NSColor *SwitchOffTrackColor(void) { CACHED_COLOR(Dynamic(0x000000, 0.1, 0xffffff, 0.16)); }
369
+
370
+ // macOS 26 起系统开关换了样子:控件比轨道左右各宽 5pt、上下各高 2pt,旋钮是横向胶囊
371
+ // (小号 44×20 的轨道配 26×16 的旋钮)。之前的系统是圆旋钮,轨道铺满控件。
372
+ static BOOL SwitchUsesCapsuleKnob(void) {
373
+ if (@available(macOS 26.0, *)) return YES;
374
+ return NO;
375
+ }
376
+
377
+ void CCPetsApplyAccent(NSControl *control) {
378
+ if ([control isKindOfClass:NSSegmentedControl.class]) {
379
+ ((NSSegmentedControl *)control).selectedSegmentBezelColor = CCPetsAccentFillColor();
380
+ } else if ([control isKindOfClass:NSSlider.class]) {
381
+ ((NSSlider *)control).trackFillColor = CCPetsAccentFillColor();
382
+ } else if ([control isKindOfClass:NSButton.class]) {
383
+ // bezelColor 对普通按钮也生效,会把它整个染色;只给回车触发的默认按钮用。
384
+ NSButton *button = (NSButton *)control;
385
+ if ([button.keyEquivalent isEqualToString:@"\r"]) button.bezelColor = CCPetsAccentFillColor();
386
+ }
387
+ }
388
+
389
+ @implementation CCPetsSwitch
390
+
391
+ // 控件尺寸照抄小号 NSSwitch,换掉之后表单行高、对齐都不变;不同系统版本上它的大小不一样,现量。
392
+ + (NSSize)switchSize {
393
+ static NSSize size;
394
+ static dispatch_once_t once;
395
+ dispatch_once(&once, ^{
396
+ NSSwitch *reference = [NSSwitch new];
397
+ reference.controlSize = NSControlSizeSmall;
398
+ size = reference.fittingSize;
399
+ if (size.width < 1 || size.height < 1) size = SwitchUsesCapsuleKnob() ? NSMakeSize(54, 24) : NSMakeSize(32, 18);
400
+ });
401
+ return size;
402
+ }
403
+
404
+ - (instancetype)initWithFrame:(NSRect)frame {
405
+ if ((self = [super initWithFrame:frame])) {
406
+ self.bordered = NO;
407
+ self.title = @"";
408
+ self.buttonType = NSButtonTypeToggle;
409
+ [self setAccessibilityRole:NSAccessibilityCheckBoxRole];
410
+ [self setAccessibilitySubrole:NSAccessibilitySwitchSubrole];
411
+ }
412
+ return self;
413
+ }
414
+
415
+ - (NSSize)intrinsicContentSize {
416
+ return [CCPetsSwitch switchSize];
417
+ }
418
+
419
+ - (void)setState:(NSControlStateValue)state {
420
+ [super setState:state];
421
+ self.needsDisplay = YES;
422
+ }
423
+
424
+ - (void)setEnabled:(BOOL)enabled {
425
+ [super setEnabled:enabled];
426
+ self.needsDisplay = YES;
427
+ }
428
+
429
+ - (NSRect)trackRect {
430
+ NSSize size = [CCPetsSwitch switchSize];
431
+ if (SwitchUsesCapsuleKnob()) size = NSMakeSize(size.width - 10, size.height - 4);
432
+ return NSMakeRect(round(NSMidX(self.bounds) - size.width / 2.0), round(NSMidY(self.bounds) - size.height / 2.0),
433
+ size.width, size.height);
434
+ }
435
+
436
+ static NSBezierPath *CapsulePath(NSRect rect) {
437
+ CGFloat radius = NSHeight(rect) / 2.0;
438
+ return [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius];
439
+ }
440
+
441
+ // drawRect 里系统已经按本视图的外观设好了当前外观,动态色直接用。
442
+ - (void)drawRect:(NSRect)dirtyRect {
443
+ BOOL on = self.state == NSControlStateValueOn;
444
+ CGContextRef context = NSGraphicsContext.currentContext.CGContext;
445
+ CGContextSaveGState(context);
446
+ CGContextSetAlpha(context, self.enabled ? 1 : 0.45);
447
+
448
+ NSRect track = [self trackRect];
449
+ NSColor *trackColor = on ? CCPetsAccentFillColor() : SwitchOffTrackColor();
450
+ [trackColor setFill];
451
+ [CapsulePath(track) fill];
452
+ if (self.highlighted) {
453
+ [[NSColor colorWithWhite:0 alpha:0.12] setFill];
454
+ [CapsulePath(track) fill];
455
+ }
456
+
457
+ CGFloat inset = 2;
458
+ CGFloat knobHeight = NSHeight(track) - inset * 2;
459
+ CGFloat knobWidth = SwitchUsesCapsuleKnob() ? round(knobHeight * 26.0 / 16.0) : knobHeight;
460
+ CGFloat knobX = on ? NSMaxX(track) - inset - knobWidth : NSMinX(track) + inset;
461
+ NSRect knob = NSMakeRect(knobX, NSMinY(track) + inset, knobWidth, knobHeight);
462
+ NSShadow *shadow = [NSShadow new];
463
+ shadow.shadowColor = [NSColor colorWithWhite:0 alpha:0.2];
464
+ shadow.shadowBlurRadius = 1.5;
465
+ shadow.shadowOffset = NSMakeSize(0, -0.5);
466
+ [shadow set];
467
+ [NSColor.whiteColor setFill];
468
+ [CapsulePath(knob) fill];
469
+ CGContextRestoreGState(context);
470
+ }
471
+
472
+ - (void)drawFocusRingMask {
473
+ [CapsulePath([self trackRect]) fill];
474
+ }
475
+
476
+ - (NSRect)focusRingMaskBounds {
477
+ return [self trackRect];
478
+ }
479
+
480
+ @end
481
+
482
+ @implementation CCPetsColorDot
483
+
484
+ - (instancetype)initWithColor:(NSColor *)color diameter:(CGFloat)diameter {
485
+ if ((self = [super initWithFrame:NSMakeRect(0, 0, diameter, diameter)])) {
486
+ self.wantsLayer = YES;
487
+ self.translatesAutoresizingMaskIntoConstraints = NO;
488
+ self.layer.cornerRadius = diameter / 2;
489
+ _color = color;
490
+ [NSLayoutConstraint activateConstraints:@[
491
+ [self.widthAnchor constraintEqualToConstant:diameter],
492
+ [self.heightAnchor constraintEqualToConstant:diameter],
493
+ ]];
494
+ }
495
+ return self;
496
+ }
497
+
498
+ - (void)setColor:(NSColor *)color {
499
+ _color = color;
500
+ self.needsDisplay = YES;
501
+ }
502
+
503
+ - (BOOL)wantsUpdateLayer {
504
+ return YES;
505
+ }
506
+
507
+ - (void)updateLayer {
508
+ self.layer.backgroundColor = self.color.CGColor;
509
+ }
510
+
511
+ @end
512
+
513
+ @implementation CCPetsLineView
514
+
515
+ - (instancetype)initWithFrame:(NSRect)frame {
516
+ if ((self = [super initWithFrame:frame])) self.wantsLayer = YES;
517
+ return self;
518
+ }
519
+
520
+ - (BOOL)wantsUpdateLayer {
521
+ return YES;
522
+ }
523
+
524
+ - (void)updateLayer {
525
+ self.layer.backgroundColor = CCPetsLineColor().CGColor;
526
+ }
527
+
528
+ @end
529
+
530
+ @interface CCPetsChipView ()
531
+ @property(nonatomic) NSTextField *label;
532
+ @property(nonatomic) NSView *dot;
533
+ @property(nonatomic) NSLayoutConstraint *labelLeading;
534
+ @end
535
+
536
+ @implementation CCPetsChipView
537
+
538
+ - (instancetype)initWithText:(NSString *)text kind:(CCPetsStatusKind)kind {
539
+ if ((self = [super initWithFrame:NSZeroRect])) {
540
+ self.wantsLayer = YES;
541
+ self.translatesAutoresizingMaskIntoConstraints = NO;
542
+ NSView *dot = [NSView new];
543
+ dot.wantsLayer = YES;
544
+ dot.layer.cornerRadius = 2.5;
545
+ dot.translatesAutoresizingMaskIntoConstraints = NO;
546
+ NSTextField *label = CCPetsLabel(text, 11, NSFontWeightSemibold, nil);
547
+ label.translatesAutoresizingMaskIntoConstraints = NO;
548
+ [label setContentCompressionResistancePriority:NSLayoutPriorityRequired
549
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
550
+ [self addSubview:dot];
551
+ [self addSubview:label];
552
+ self.dot = dot;
553
+ self.label = label;
554
+ self.labelLeading = [label.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:17];
555
+ [NSLayoutConstraint activateConstraints:@[
556
+ [dot.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:8],
557
+ [dot.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
558
+ [dot.widthAnchor constraintEqualToConstant:5],
559
+ [dot.heightAnchor constraintEqualToConstant:5],
560
+ self.labelLeading,
561
+ [label.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-8],
562
+ [label.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
563
+ [self.heightAnchor constraintEqualToConstant:20],
564
+ ]];
565
+ [self setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
566
+ _kind = kind;
567
+ [self applyKind];
568
+ }
569
+ return self;
570
+ }
571
+
572
+ - (NSString *)text {
573
+ return self.label.stringValue;
574
+ }
575
+
576
+ - (void)setText:(NSString *)text {
577
+ self.label.stringValue = text ?: @"";
578
+ }
579
+
580
+ - (void)setKind:(CCPetsStatusKind)kind {
581
+ _kind = kind;
582
+ [self applyKind];
583
+ }
584
+
585
+ - (void)setHidesDot:(BOOL)hidesDot {
586
+ _hidesDot = hidesDot;
587
+ self.dot.hidden = hidesDot;
588
+ self.labelLeading.constant = hidesDot ? 8 : 17;
589
+ }
590
+
591
+ - (void)applyKind {
592
+ self.label.textColor = CCPetsStatusColor(self.kind);
593
+ self.needsDisplay = YES;
594
+ }
595
+
596
+ - (BOOL)wantsUpdateLayer {
597
+ return YES;
598
+ }
599
+
600
+ - (void)updateLayer {
601
+ self.layer.cornerRadius = 10;
602
+ self.layer.backgroundColor = CCPetsStatusBackgroundColor(self.kind).CGColor;
603
+ self.dot.layer.backgroundColor = CCPetsStatusColor(self.kind).CGColor;
604
+ }
605
+
606
+ @end
607
+
608
+ @interface CCPetsCountBadge ()
609
+ @property(nonatomic) NSTextField *label;
610
+ @end
611
+
612
+ @implementation CCPetsCountBadge
613
+
614
+ - (instancetype)initWithFrame:(NSRect)frame {
615
+ if ((self = [super initWithFrame:frame])) {
616
+ self.wantsLayer = YES;
617
+ NSTextField *label = CCPetsNumberLabel(@"", 11, NSFontWeightSemibold, CCPetsSecondaryInkColor());
618
+ label.alignment = NSTextAlignmentCenter;
619
+ label.translatesAutoresizingMaskIntoConstraints = NO;
620
+ [self addSubview:label];
621
+ self.label = label;
622
+ [NSLayoutConstraint activateConstraints:@[
623
+ [label.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:6],
624
+ [label.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-6],
625
+ [label.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
626
+ [self.heightAnchor constraintEqualToConstant:18],
627
+ [self.widthAnchor constraintGreaterThanOrEqualToConstant:18],
628
+ ]];
629
+ self.hidden = YES;
630
+ }
631
+ return self;
632
+ }
633
+
634
+ - (void)setCount:(NSInteger)count {
635
+ _count = count;
636
+ self.label.stringValue = [NSString stringWithFormat:@"%ld", (long)count];
637
+ self.hidden = count <= 0;
638
+ }
639
+
640
+ - (void)setWarn:(BOOL)warn {
641
+ _warn = warn;
642
+ self.label.textColor = warn ? CCPetsStatusColor(CCPetsStatusWarn) : CCPetsSecondaryInkColor();
643
+ self.needsDisplay = YES;
644
+ }
645
+
646
+ - (BOOL)wantsUpdateLayer {
647
+ return YES;
648
+ }
649
+
650
+ - (void)updateLayer {
651
+ self.layer.cornerRadius = 9;
652
+ self.layer.backgroundColor = (self.warn ? CCPetsStatusBackgroundColor(CCPetsStatusWarn)
653
+ : CCPetsStatusBackgroundColor(CCPetsStatusIdle)).CGColor;
654
+ }
655
+
656
+ @end
657
+
658
+ // 和 PetView.handleAgentEvent: 用的行一致:{行, 最后一帧}。
659
+ static void SpriteRowForState(NSString *state, NSInteger *row, NSInteger *lastFrame) {
660
+ NSDictionary<NSString *, NSArray<NSNumber *> *> *rows = @{
661
+ @"thinking": @[@5, @7], @"starting": @[@4, @4], @"auto_review": @[@8, @5],
662
+ @"approval": @[@4, @4], @"notification": @[@4, @4],
663
+ @"tool": @[@8, @5], @"subagent": @[@6, @5],
664
+ @"tool_completed": @[@7, @5], @"completed": @[@3, @3],
665
+ @"tool_failed": @[@5, @7], @"failed": @[@5, @7],
666
+ };
667
+ NSArray<NSNumber *> *entry = rows[state ?: @""] ?: @[@0, @5];
668
+ *row = entry[0].integerValue;
669
+ *lastFrame = entry[1].integerValue;
670
+ }
671
+
672
+ static const NSTimeInterval SpriteFrameInterval = 0.16;
673
+
674
+ @interface CCPetsSpriteView ()
675
+ @property(nonatomic) CGImageRef sheetImage;
676
+ @property(nonatomic) NSImage *sheet;
677
+ @property(nonatomic) NSInteger rowCount;
678
+ @property(nonatomic) NSInteger row;
679
+ @property(nonatomic) NSInteger lastFrame;
680
+ @property(nonatomic) NSInteger frameIndex;
681
+ @property(nonatomic) NSTimer *timer;
682
+ @end
683
+
684
+ @implementation CCPetsSpriteView
685
+
686
+ - (instancetype)initWithFrame:(NSRect)frame {
687
+ if ((self = [super initWithFrame:frame])) {
688
+ self.wantsLayer = YES;
689
+ // 像素素材放大用最近邻,和桌宠本体一致。
690
+ self.layer.magnificationFilter = kCAFilterNearest;
691
+ self.layer.minificationFilter = kCAFilterNearest;
692
+ self.layer.contentsGravity = kCAGravityResizeAspect;
693
+ _lastFrame = 5;
694
+ _playing = YES;
695
+ [NSWorkspace.sharedWorkspace.notificationCenter addObserver:self
696
+ selector:@selector(updateTimer)
697
+ name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
698
+ }
699
+ return self;
700
+ }
701
+
702
+ - (void)dealloc {
703
+ [_timer invalidate];
704
+ if (_sheetImage) CGImageRelease(_sheetImage);
705
+ [NSNotificationCenter.defaultCenter removeObserver:self];
706
+ [NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self];
707
+ }
708
+
709
+ - (void)setSheet:(NSImage *)sheet rowCount:(NSInteger)rowCount {
710
+ if (sheet == self.sheet && rowCount == self.rowCount) return;
711
+ self.sheet = sheet;
712
+ self.rowCount = MAX((NSInteger)1, rowCount);
713
+ if (_sheetImage) CGImageRelease(_sheetImage);
714
+ CGImageRef image = [sheet CGImageForProposedRect:NULL context:nil hints:nil];
715
+ _sheetImage = image ? CGImageRetain(image) : NULL;
716
+ [self applyState];
717
+ }
718
+
719
+ - (void)setPlaying:(BOOL)playing {
720
+ if (_playing == playing) return;
721
+ _playing = playing;
722
+ [self updateTimer];
723
+ }
724
+
725
+ - (void)setState:(NSString *)state {
726
+ if ([_state isEqualToString:state]) return;
727
+ _state = [state copy];
728
+ [self applyState];
729
+ }
730
+
731
+ - (void)applyState {
732
+ NSInteger row = 0, lastFrame = 5;
733
+ SpriteRowForState(self.state, &row, &lastFrame);
734
+ if (row >= self.rowCount) {
735
+ row = 0;
736
+ lastFrame = 5;
737
+ }
738
+ self.row = row;
739
+ self.lastFrame = lastFrame;
740
+ self.frameIndex = 0;
741
+ [self showCurrentFrame];
742
+ [self updateTimer];
743
+ }
744
+
745
+ - (void)showCurrentFrame {
746
+ if (!_sheetImage) {
747
+ self.layer.contents = nil;
748
+ return;
749
+ }
750
+ size_t width = CGImageGetWidth(_sheetImage), height = CGImageGetHeight(_sheetImage);
751
+ CGFloat cellWidth = width / 8.0, cellHeight = (CGFloat)height / self.rowCount;
752
+ // CGImage 坐标原点在左上角,行号从上往下数,正好不用翻转。
753
+ CGRect cell = CGRectIntegral(CGRectMake(self.frameIndex * cellWidth, self.row * cellHeight,
754
+ cellWidth, cellHeight));
755
+ CGImageRef frame = CGImageCreateWithImageInRect(_sheetImage, cell);
756
+ [CATransaction begin];
757
+ // 换 contents 默认有 0.25s 淡入,逐帧动画上会拖影。
758
+ [CATransaction setDisableActions:YES];
759
+ self.layer.contents = (__bridge id)frame;
760
+ [CATransaction commit];
761
+ if (frame) CGImageRelease(frame);
762
+ }
763
+
764
+ - (void)viewWillMoveToWindow:(NSWindow *)newWindow {
765
+ [super viewWillMoveToWindow:newWindow];
766
+ for (NSNotificationName name in @[NSWindowDidMiniaturizeNotification,
767
+ NSWindowDidDeminiaturizeNotification, NSWindowWillCloseNotification]) {
768
+ [NSNotificationCenter.defaultCenter removeObserver:self name:name object:nil];
769
+ }
770
+ }
771
+
772
+ - (void)viewDidMoveToWindow {
773
+ [super viewDidMoveToWindow];
774
+ if (self.window) {
775
+ for (NSNotificationName name in @[NSWindowDidMiniaturizeNotification,
776
+ NSWindowDidDeminiaturizeNotification]) {
777
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(updateTimer)
778
+ name:name object:self.window];
779
+ }
780
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(windowWillClose:)
781
+ name:NSWindowWillCloseNotification object:self.window];
782
+ }
783
+ [self updateTimer];
784
+ }
785
+
786
+ - (void)windowWillClose:(NSNotification *)notification {
787
+ [self.timer invalidate];
788
+ self.timer = nil;
789
+ }
790
+
791
+ // 窗口在屏幕上才走表,关窗、最小化都不耗电。不看"是否被别的窗口挡住":那要靠遮挡状态,
792
+ // 它在 Space / 全屏过渡期间会误报十几秒不可见,桌宠本体已经因此弃用(见 tests/test.sh)。
793
+ - (void)updateTimer {
794
+ BOOL visible = self.window.isVisible && !self.window.isMiniaturized;
795
+ BOOL shouldRun = visible && self.playing && _sheetImage && self.lastFrame > 0 &&
796
+ !NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion;
797
+ if (shouldRun == self.timer.isValid) return;
798
+ [self.timer invalidate];
799
+ self.timer = nil;
800
+ if (!shouldRun) {
801
+ self.frameIndex = 0;
802
+ [self showCurrentFrame];
803
+ return;
804
+ }
805
+ __weak typeof(self) weakSelf = self;
806
+ self.timer = [NSTimer timerWithTimeInterval:SpriteFrameInterval repeats:YES block:^(NSTimer *timer) {
807
+ CCPetsSpriteView *view = weakSelf;
808
+ if (!view) return;
809
+ view.frameIndex = view.frameIndex >= view.lastFrame ? 0 : view.frameIndex + 1;
810
+ [view showCurrentFrame];
811
+ }];
812
+ self.timer.tolerance = SpriteFrameInterval * 0.25;
813
+ [NSRunLoop.mainRunLoop addTimer:self.timer forMode:NSRunLoopCommonModes];
814
+ }
815
+
816
+ @end