cc-pets 2.2.1 → 2.4.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 (197) hide show
  1. package/CC_BRIDGE.md +24 -2
  2. package/CC_BRIDGE.zh-CN.md +19 -2
  3. package/CHANGELOG.md +111 -0
  4. package/CHANGELOG.zh-CN.md +111 -0
  5. package/CONTRIBUTING.md +35 -10
  6. package/CONTRIBUTING.zh-CN.md +28 -10
  7. package/README.md +212 -32
  8. package/README.zh-CN.md +167 -36
  9. package/Resources/AgentIcons/claude.png +0 -0
  10. package/Resources/AgentIcons/codex.icns +0 -0
  11. package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
  12. package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
  13. package/Resources/zh-Hans.lproj/Localizable.strings +699 -20
  14. package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
  15. package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +90 -25
  16. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  17. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +17 -3
  18. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +71 -23
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
  20. package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
  21. package/Sources/CCPets/{CCPetsAppDelegate+Settings.m → App/CCPetsAppDelegate+Settings.m} +87 -102
  22. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +121 -51
  23. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  24. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +17 -2
  25. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +107 -11
  26. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  27. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  28. package/Sources/CCPets/{main.m → App/main.m} +74 -1
  29. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  30. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +43 -23
  31. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +832 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +59 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +576 -0
  35. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  36. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +507 -0
  37. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +106 -0
  38. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +897 -0
  39. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  40. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  41. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  42. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  43. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
  44. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
  45. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  46. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  47. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
  48. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
  49. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  50. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  51. package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +2 -1
  52. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +148 -36
  53. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
  54. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
  55. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
  56. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
  57. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  58. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  59. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +11 -2
  60. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +19 -2
  61. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +4 -1
  62. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  63. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  64. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  65. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  66. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  67. package/Sources/CCPets/Pet/PetView.m +635 -0
  68. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  69. package/Sources/CCPets/Support/CCPetsDoctor.m +646 -0
  70. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  71. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  72. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  73. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  74. package/Sources/CCPets/Support/CCPetsPreferences.h +33 -0
  75. package/Sources/CCPets/Support/CCPetsPreferences.m +117 -0
  76. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  77. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  78. package/Sources/CCPets/UI/CCPetsFormBuilder.h +44 -0
  79. package/Sources/CCPets/UI/CCPetsFormBuilder.m +279 -0
  80. package/Sources/CCPets/UI/CCPetsGlassView.h +57 -0
  81. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +60 -11
  82. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  83. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  84. package/Sources/CCPets/UI/CCPetsSettingsPage.h +64 -0
  85. package/Sources/CCPets/UI/CCPetsSettingsPage.m +1412 -0
  86. package/Sources/CCPets/UI/CCPetsUIStyle.h +135 -0
  87. package/Sources/CCPets/UI/CCPetsUIStyle.m +865 -0
  88. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  89. package/Sources/CCPets/UI/CCPetsUsageChartView.m +288 -0
  90. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  91. package/Sources/CCPets/UI/CCPetsUsagePage.m +712 -0
  92. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  93. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  94. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  95. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  96. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  97. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  98. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  99. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  100. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  101. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  102. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  103. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  104. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  105. package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
  106. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  107. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  108. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +97 -0
  109. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +323 -0
  110. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  111. package/Sources/CCPets/Usage/CCPetsUsage.h +58 -0
  112. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  113. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  114. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  115. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  116. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +174 -19
  117. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  118. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  119. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +598 -0
  120. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  121. package/Sources/CCPets/Usage/QuotaDashboardView.m +713 -0
  122. package/THIRD_PARTY_NOTICES.md +8 -4
  123. package/THIRD_PARTY_NOTICES.zh-CN.md +6 -2
  124. package/bin/cc-pets +8 -6
  125. package/bin/claude-with-pet +12 -2
  126. package/bin/codex-with-pet +15 -5
  127. package/package.json +5 -1
  128. package/plugins/jetbrains/README.md +62 -0
  129. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
  130. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
  131. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
  132. package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
  133. package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
  134. package/plugins/vscode/README.md +63 -0
  135. package/plugins/vscode/extension.js +210 -0
  136. package/plugins/vscode/package.json +18 -0
  137. package/scripts/build-idea-plugin.sh +101 -0
  138. package/scripts/build-vscode-extension.sh +112 -0
  139. package/scripts/build.sh +31 -5
  140. package/scripts/compile-cached.zsh +133 -0
  141. package/scripts/i18n.zsh +9 -52
  142. package/scripts/install-app.sh +4 -0
  143. package/scripts/install-shell-integration.sh +17 -10
  144. package/scripts/uninstall-shell-integration.sh +6 -1
  145. package/Sources/CCPets/CCPetsEvents.h +0 -10
  146. package/Sources/CCPets/CCPetsGlassView.h +0 -31
  147. package/Sources/CCPets/CCPetsUsage.h +0 -36
  148. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  149. package/Sources/CCPets/PetView.m +0 -1839
  150. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  151. package/scripts/bridge/cli.mjs +0 -237
  152. package/scripts/bridge/core.mjs +0 -228
  153. package/scripts/bridge/hook.mjs +0 -150
  154. package/scripts/bridge/install.mjs +0 -311
  155. package/scripts/bridge/mcp-server.mjs +0 -308
  156. package/scripts/bridge/options.mjs +0 -87
  157. package/scripts/bridge/process.mjs +0 -151
  158. package/scripts/bridge/reservations.mjs +0 -248
  159. package/scripts/bridge/store.mjs +0 -433
  160. package/scripts/bridge/watch.mjs +0 -69
  161. package/scripts/check-l10n.mjs +0 -168
  162. package/scripts/configure-updater.mjs +0 -43
  163. package/scripts/detect-cli.mjs +0 -68
  164. package/scripts/doctor.mjs +0 -470
  165. package/scripts/i18n.mjs +0 -122
  166. package/scripts/install-claude-hooks.mjs +0 -253
  167. package/scripts/install-codex-hooks.mjs +0 -78
  168. package/scripts/integration-markers.mjs +0 -51
  169. package/scripts/locales/zh-Hans.json +0 -366
  170. package/scripts/pet-store.mjs +0 -415
  171. package/scripts/uninstall-integrations.mjs +0 -205
  172. /package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +0 -0
  173. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  174. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  175. /package/Sources/CCPets/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
  176. /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
  177. /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
  178. /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
  179. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  180. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  181. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  182. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  183. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  184. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  185. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  186. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  187. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  188. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  189. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  190. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  191. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  192. /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
  193. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  194. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  195. /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
  196. /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
  197. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -0,0 +1,1412 @@
1
+ #import "CCPetsSettingsPage.h"
2
+ #import "CCPetsBridge.h"
3
+ #import "CCPetsCLISupport.h"
4
+ #import "CCPetsDiagnosticsPage.h"
5
+ #import "CCPetsFormBuilder.h"
6
+ #import "CCPetsGlassView.h"
7
+ #import "CCPetsImageLoader.h"
8
+ #import "CCPetsIDEIntegration.h"
9
+ #import "CCPetsTerminalIntegration.h"
10
+ #import "CCPetsVSCodeIntegration.h"
11
+ #import "CCPetsL10n.h"
12
+ #import "CCPetsPaths.h"
13
+ #import "CCPetsPetSize.h"
14
+ #import "CCPetsPhrases.h"
15
+ #import "CCPetsPreferences.h"
16
+ #import "CCPetsProfiles.h"
17
+ #import "CCPetsUsageMode.h"
18
+ #import "CCPetsUIStyle.h"
19
+ #import <QuartzCore/QuartzCore.h>
20
+ #include <fcntl.h>
21
+ #include <unistd.h>
22
+
23
+ // 定义在 CCPetsAppDelegate+Speech.m;那边的头文件是 AppDelegate 私有的,这里单独 extern。
24
+ extern NSString *const PetSpeechFrequencyKey;
25
+
26
+ // 控件的 target 只能是对象,用它把 action 转成 block,免得每个控件写一个方法。
27
+ @interface CCPetsSettingsHandler : NSObject
28
+ @property(nonatomic, copy) void (^block)(id sender);
29
+ - (void)invoke:(id)sender;
30
+ @end
31
+
32
+ @implementation CCPetsSettingsHandler
33
+ - (void)invoke:(id)sender {
34
+ if (self.block) self.block(sender);
35
+ }
36
+ @end
37
+
38
+ static NSString *ClickCountText(NSInteger count) {
39
+ return [[NSString stringWithFormat:@"%ld", (long)count] stringByAppendingString:L(@" clicks")];
40
+ }
41
+
42
+ static void RevealFolder(NSString *path) {
43
+ // 第一次用时文件夹可能还不存在;建出来比让按钮点了没反应好。
44
+ [NSFileManager.defaultManager createDirectoryAtPath:path withIntermediateDirectories:YES
45
+ attributes:nil error:nil];
46
+ [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:path isDirectory:YES]];
47
+ }
48
+
49
+ // 三个设置页共用:控件绑定、按 defaults 回填、监听设置变更。
50
+ @interface CCPetsSettingsPageBase ()
51
+ @property(nonatomic) CCPetsFormBuilder *form;
52
+ @property(nonatomic) NSMutableArray<CCPetsSettingsHandler *> *handlers;
53
+ // 每个控件一个"按 defaults 回填自己"的 block。设置一变就全部跑一遍。
54
+ @property(nonatomic) NSMutableArray<void (^)(void)> *reloaders;
55
+ @end
56
+
57
+ @implementation CCPetsSettingsPageBase
58
+
59
+ - (id<CCPetsSettingsActions>)actions {
60
+ id delegate = NSApp.delegate;
61
+ return [delegate respondsToSelector:@selector(updatePetScale:)] ? delegate : nil;
62
+ }
63
+
64
+ - (NSString *)pageTitle {
65
+ return @"";
66
+ }
67
+
68
+ - (NSString *)pageSubtitle {
69
+ return @"";
70
+ }
71
+
72
+ - (void)buildContent {
73
+ }
74
+
75
+ - (void)loadView {
76
+ self.handlers = [NSMutableArray array];
77
+ self.reloaders = [NSMutableArray array];
78
+ self.form = [[CCPetsFormBuilder alloc] initWithTitle:[self pageTitle] subtitle:[self pageSubtitle]];
79
+ self.view = self.form.view;
80
+ [self buildContent];
81
+ [self reloadValues];
82
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(preferencesDidChange:)
83
+ name:CCPetsPreferencesDidChangeNotification object:nil];
84
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(preferencesDidChange:)
85
+ name:CCPetsAuthenticationModesDidChangeNotification object:nil];
86
+ }
87
+
88
+ - (void)dealloc {
89
+ [NSNotificationCenter.defaultCenter removeObserver:self];
90
+ }
91
+
92
+ - (void)preferencesDidChange:(NSNotification *)notification {
93
+ [self reloadValues];
94
+ }
95
+
96
+ - (void)reloadValues {
97
+ for (void (^reload)(void) in self.reloaders) reload();
98
+ }
99
+
100
+ - (void)bind:(NSControl *)control to:(void (^)(id sender))block {
101
+ CCPetsSettingsHandler *handler = [CCPetsSettingsHandler new];
102
+ handler.block = block;
103
+ [self.handlers addObject:handler];
104
+ control.target = handler;
105
+ control.action = @selector(invoke:);
106
+ }
107
+
108
+ - (CCPetsSwitch *)switchWithValue:(BOOL (^)(void))value action:(void (^)(CCPetsSwitch *control))action {
109
+ CCPetsSwitch *control = [CCPetsSwitch new];
110
+ [self bind:control to:^(CCPetsSwitch *sender) { action(sender); }];
111
+ [self.reloaders addObject:^{
112
+ control.state = value() ? NSControlStateValueOn : NSControlStateValueOff;
113
+ }];
114
+ return control;
115
+ }
116
+
117
+ // 普通布尔设置:读写同一个键,写完交给 AppDelegate 生效。
118
+ - (NSView *)switchRowWithTitle:(NSString *)title subtitle:(NSString *)subtitle key:(NSString *)key
119
+ apply:(void (^)(id<CCPetsSettingsActions> actions, BOOL enabled))apply {
120
+ __weak typeof(self) weakSelf = self;
121
+ CCPetsSwitch *control = [self switchWithValue:^BOOL { return CCPetsPrefBool(key); }
122
+ action:^(CCPetsSwitch *sender) {
123
+ apply(weakSelf.actions, sender.state == NSControlStateValueOn);
124
+ }];
125
+ return [CCPetsFormBuilder rowWithTitle:title subtitle:subtitle controls:@[control]];
126
+ }
127
+
128
+ // 系统通知要先拿到授权,失败就弹回关闭,所以不能直接用 switchRow。
129
+ - (NSView *)notificationRowWithTitle:(NSString *)title subtitle:(NSString *)subtitle key:(NSString *)key {
130
+ __weak typeof(self) weakSelf = self;
131
+ CCPetsSwitch *control = [self switchWithValue:^BOOL { return CCPetsPrefBool(key); }
132
+ action:^(CCPetsSwitch *sender) {
133
+ [weakSelf.actions updateNotification:key enabled:sender.state == NSControlStateValueOn
134
+ completion:^(BOOL enabled) {
135
+ sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
136
+ }];
137
+ }];
138
+ return [CCPetsFormBuilder rowWithTitle:title subtitle:subtitle controls:@[control]];
139
+ }
140
+
141
+ - (NSPopUpButton *)popUpWithOptions:(NSArray<NSArray *> *)options selected:(id (^)(void))selected
142
+ action:(void (^)(id value))action {
143
+ NSPopUpButton *popUp = [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO];
144
+ popUp.controlSize = NSControlSizeSmall;
145
+ popUp.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
146
+ for (NSArray *option in options) {
147
+ [popUp addItemWithTitle:option[0]];
148
+ popUp.lastItem.representedObject = option[1];
149
+ }
150
+ [self bind:popUp to:^(NSPopUpButton *sender) { action(sender.selectedItem.representedObject); }];
151
+ [self.reloaders addObject:^{
152
+ id value = selected();
153
+ for (NSMenuItem *item in popUp.itemArray) {
154
+ if (![item.representedObject isEqual:value]) continue;
155
+ [popUp selectItem:item];
156
+ break;
157
+ }
158
+ }];
159
+ return popUp;
160
+ }
161
+
162
+ // 档位少(四个以内)的单选用分段控件,一眼看到全部选项;多了再用弹出菜单。
163
+ - (NSSegmentedControl *)segmentedWithOptions:(NSArray<NSArray *> *)options selected:(id (^)(void))selected
164
+ action:(void (^)(id value))action {
165
+ NSMutableArray<NSString *> *labels = [NSMutableArray array];
166
+ for (NSArray *option in options) [labels addObject:option[0]];
167
+ NSSegmentedControl *control = [NSSegmentedControl segmentedControlWithLabels:labels
168
+ trackingMode:NSSegmentSwitchTrackingSelectOne target:nil action:nil];
169
+ control.controlSize = NSControlSizeSmall;
170
+ control.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
171
+ CCPetsApplyAccent(control);
172
+ [self bind:control to:^(NSSegmentedControl *sender) {
173
+ if (sender.selectedSegment >= 0) action(options[(NSUInteger)sender.selectedSegment][1]);
174
+ }];
175
+ [self.reloaders addObject:^{
176
+ id value = selected();
177
+ for (NSUInteger index = 0; index < options.count; index++) {
178
+ if ([options[index][1] isEqual:value]) control.selectedSegment = (NSInteger)index;
179
+ }
180
+ }];
181
+ return control;
182
+ }
183
+
184
+ // 步进器 + 数值标签。菜单里只有三档,这里可以连续调。
185
+ - (NSView *)stepperRowWithTitle:(NSString *)title key:(NSString *)key minimum:(double)minimum
186
+ maximum:(double)maximum increment:(double)increment fallback:(double)fallback
187
+ format:(NSString *(^)(double value))format {
188
+ NSStepper *stepper = [NSStepper new];
189
+ stepper.controlSize = NSControlSizeSmall;
190
+ stepper.minValue = minimum;
191
+ stepper.maxValue = maximum;
192
+ stepper.increment = increment;
193
+ stepper.valueWraps = NO;
194
+ NSTextField *valueLabel = CCPetsNumberLabel(@"", 12, NSFontWeightRegular, CCPetsInkColor());
195
+ valueLabel.alignment = NSTextAlignmentRight;
196
+ [valueLabel.widthAnchor constraintGreaterThanOrEqualToConstant:52].active = YES;
197
+ __weak typeof(self) weakSelf = self;
198
+ [self bind:stepper to:^(NSStepper *sender) {
199
+ // 步进 0.1 的浮点累加会出现 1.2000000002,按步长取整再交出去。
200
+ double value = round(sender.doubleValue / increment) * increment;
201
+ [weakSelf.actions updatePetInteractionValue:@(value) forKey:key];
202
+ }];
203
+ [self.reloaders addObject:^{
204
+ id stored = [NSUserDefaults.standardUserDefaults objectForKey:key];
205
+ double value = [stored isKindOfClass:NSNumber.class] ? [stored doubleValue] : fallback;
206
+ // 生气阈值的下限跟着比心阈值走,和 CCPetsPrefNormalizedValue 的钳制一致。
207
+ if ([key isEqualToString:PetInteractionAnnoyedThresholdKey]) {
208
+ stepper.minValue = MAX((NSInteger)2, [NSUserDefaults.standardUserDefaults
209
+ integerForKey:PetInteractionHeartThresholdKey]) + 1;
210
+ }
211
+ stepper.doubleValue = value;
212
+ valueLabel.stringValue = format(value);
213
+ }];
214
+ return [CCPetsFormBuilder rowWithTitle:title controls:@[valueLabel, stepper]];
215
+ }
216
+
217
+ - (NSButton *)smallButtonWithTitle:(NSString *)title action:(void (^)(void))action {
218
+ NSButton *button = [NSButton buttonWithTitle:title target:nil action:nil];
219
+ button.controlSize = NSControlSizeSmall;
220
+ button.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
221
+ [self bind:button to:^(id sender) { action(); }];
222
+ return button;
223
+ }
224
+
225
+ - (NSSlider *)sliderWithMinimum:(double)minimum maximum:(double)maximum width:(CGFloat)width {
226
+ NSSlider *slider = [NSSlider sliderWithValue:minimum minValue:minimum maxValue:maximum target:nil action:nil];
227
+ slider.continuous = YES;
228
+ slider.controlSize = NSControlSizeSmall;
229
+ CCPetsApplyAccent(slider);
230
+ [slider.widthAnchor constraintEqualToConstant:width].active = YES;
231
+ return slider;
232
+ }
233
+
234
+ - (NSTextField *)sliderValueLabel {
235
+ NSTextField *label = CCPetsNumberLabel(@"", 12, NSFontWeightRegular, CCPetsSecondaryInkColor());
236
+ label.alignment = NSTextAlignmentRight;
237
+ [label.widthAnchor constraintEqualToConstant:40].active = YES;
238
+ return label;
239
+ }
240
+
241
+ @end
242
+
243
+ #pragma mark - 多账号
244
+
245
+ @interface CCPetsAccountsPage ()
246
+ // 上次建页时的账号与集成状态;没变就不重建,免得切页、回到前台时整页闪一下。
247
+ @property(nonatomic, copy) NSArray<NSDictionary *> *entries;
248
+ // 控件回调(弹出菜单、确认框、选文件面板)期间主队列照样会跑,这时重建会释放正在执行的
249
+ // 闭包和弹出菜单所依附的按钮,只记下来,等回调返回后再建。
250
+ @property(nonatomic) NSInteger interactionDepth;
251
+ @property(nonatomic) BOOL needsRebuild;
252
+ @end
253
+
254
+ @implementation CCPetsAccountsPage
255
+
256
+ - (NSString *)pageTitle {
257
+ return L(@"Multi-Account");
258
+ }
259
+
260
+ - (NSString *)pageSubtitle {
261
+ return L(@"Add and manage Claude and Codex Homes.");
262
+ }
263
+
264
+ - (void)loadView {
265
+ [super loadView];
266
+ // 集成状态还取决于 CC Bridge 开关和各 Home 的配置文件:诊断修复、命令行改动之后回到 App 时也要重读。
267
+ for (NSNotificationName name in @[CCPetsProfilesDidChangeNotification, CCPetsDiagnosticsDidChangeNotification,
268
+ NSApplicationDidBecomeActiveNotification]) {
269
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(profilesDidChange:)
270
+ name:name object:nil];
271
+ }
272
+ }
273
+
274
+ - (void)viewWillAppear {
275
+ [super viewWillAppear];
276
+ [self profilesDidChange:nil];
277
+ }
278
+
279
+ - (void)profilesDidChange:(NSNotification *)notification {
280
+ if (notification && !self.view.window) return;
281
+ if (self.interactionDepth > 0) {
282
+ self.needsRebuild = YES;
283
+ return;
284
+ }
285
+ if ([self.entries isEqualToArray:[self currentEntries]]) return;
286
+ [self.handlers removeAllObjects];
287
+ [self.reloaders removeAllObjects];
288
+ [self.form removeAllContent];
289
+ [self buildContent];
290
+ }
291
+
292
+ - (NSArray<NSDictionary *> *)currentEntries {
293
+ NSMutableArray<NSDictionary *> *entries = [NSMutableArray array];
294
+ for (NSDictionary *profile in CCPetsProfiles()) {
295
+ [entries addObject:@{@"profile": profile, @"state": CCPetsProfileStatus(profile)[@"state"] ?: @""}];
296
+ }
297
+ return entries.copy;
298
+ }
299
+
300
+ - (void)bind:(NSControl *)control to:(void (^)(id sender))block {
301
+ __weak typeof(self) weakSelf = self;
302
+ [super bind:control to:^(id sender) {
303
+ typeof(self) strongSelf = weakSelf;
304
+ strongSelf.interactionDepth++;
305
+ block(sender);
306
+ strongSelf.interactionDepth--;
307
+ if (strongSelf.interactionDepth > 0 || !strongSelf.needsRebuild) return;
308
+ strongSelf.needsRebuild = NO;
309
+ // 下一轮再建:现在还在这个控件的闭包里。
310
+ dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf profilesDidChange:nil]; });
311
+ }];
312
+ }
313
+
314
+ - (NSButton *)manageButtonForProfile:(NSDictionary *)profile {
315
+ __weak typeof(self) weakSelf = self;
316
+ NSButton *button = [NSButton buttonWithTitle:L(@"Manage…") target:nil action:nil];
317
+ button.controlSize = NSControlSizeSmall;
318
+ button.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
319
+ [self bind:button to:^(NSButton *sender) {
320
+ NSMenu *menu = [NSMenu new];
321
+ NSMutableArray<NSArray *> *actions = [@[
322
+ @[L(@"Repair Integration"), NSStringFromSelector(@selector(repairAgentProfile:))],
323
+ @[L(@"Rename…"), NSStringFromSelector(@selector(renameAgentProfile:))]
324
+ ] mutableCopy];
325
+ if (!CCPetsProfileIsOfficialDefault(profile)) {
326
+ [actions addObject:@[L(@"Relocate Home…"), NSStringFromSelector(@selector(relocateAgentProfile:))]];
327
+ [actions addObject:@[L(@"Remove Integration…"), NSStringFromSelector(@selector(removeAgentProfile:))]];
328
+ }
329
+ for (NSArray *action in actions) {
330
+ NSMenuItem *item = [menu addItemWithTitle:action[0]
331
+ action:NSSelectorFromString(action[1]) keyEquivalent:@""];
332
+ item.target = weakSelf.actions;
333
+ item.representedObject = profile[@"id"];
334
+ }
335
+ [menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(0, NSMaxY(sender.bounds)) inView:sender];
336
+ }];
337
+ return button;
338
+ }
339
+
340
+ - (void)buildContent {
341
+ __weak typeof(self) weakSelf = self;
342
+ [self.form setAccessoryViews:@[
343
+ [self smallButtonWithTitle:L(@"Add Claude Home…") action:^{ [weakSelf.actions addClaudeProfile:nil]; }],
344
+ [self smallButtonWithTitle:L(@"Add Codex Home…") action:^{ [weakSelf.actions addCodexProfile:nil]; }]
345
+ ]];
346
+ self.entries = [self currentEntries];
347
+ if (self.entries.count == 0) {
348
+ [self.form addGroupWithTitle:nil rows:@[
349
+ [CCPetsFormBuilder rowWithTitle:L(@"No Agent accounts detected")
350
+ subtitle:L(@"Use the buttons above to add an existing Claude or Codex Home.") controls:@[]]
351
+ ] footer:nil];
352
+ return;
353
+ }
354
+ for (NSString *provider in @[CCPetsProfileProviderClaude, CCPetsProfileProviderCodex]) {
355
+ NSMutableArray<NSView *> *rows = [NSMutableArray array];
356
+ for (NSDictionary *entry in self.entries) {
357
+ NSDictionary *profile = entry[@"profile"];
358
+ if (![profile[@"provider"] isEqualToString:provider]) continue;
359
+ NSString *state = entry[@"state"];
360
+ NSColor *color = [state isEqualToString:CCPetsProfileStateIntegrated]
361
+ ? CCPetsSecondaryInkColor() : NSColor.systemOrangeColor;
362
+ NSTextField *label = CCPetsLabel(CCPetsProfileStateTitle(state), 11, NSFontWeightRegular, color);
363
+ NSView *row = [CCPetsFormBuilder rowWithTitle:profile[@"displayName"] ?: profile[@"slug"]
364
+ subtitle:CCPetsTildePath(profile[@"home"])
365
+ controls:@[label, [self manageButtonForProfile:profile]]];
366
+ row.toolTip = profile[@"home"];
367
+ [rows addObject:row];
368
+ }
369
+ if (rows.count > 0) [self.form addGroupWithTitle:
370
+ [provider isEqualToString:CCPetsProfileProviderClaude] ? @"Claude" : @"Codex" rows:rows footer:nil];
371
+ }
372
+ }
373
+
374
+ @end
375
+
376
+ #pragma mark - 宠物
377
+
378
+ @interface CCPetsPetPage ()
379
+ @property(nonatomic) NSStackView *pickerRows;
380
+ @property(nonatomic) NSMutableDictionary<NSString *, CCPetsTileView *> *petTiles;
381
+ @property(nonatomic) NSMutableDictionary<NSString *, CCPetsSpriteView *> *petSprites;
382
+ @property(nonatomic) NSMutableDictionary<NSString *, NSImage *> *sheetCache;
383
+ // 自己素材文件夹里的宠物才有:卡片右上角的删除按钮和右键菜单项。当前这只不让删,和桌宠右键菜单一致。
384
+ @property(nonatomic) NSMutableDictionary<NSString *, NSButton *> *petDeleteButtons;
385
+ @property(nonatomic) NSMutableDictionary<NSString *, NSMenuItem *> *petDeleteItems;
386
+ // 列表现在画的是哪几只(按 id 次序)。外面增删了宠物,对不上就重排。
387
+ @property(nonatomic) NSArray<NSString *> *renderedPetIDs;
388
+ // 盯着自己的素材文件夹:桌宠右键菜单删除、`cc-pets pet add/remove`、Finder 里拖进拖出都会改它。
389
+ @property(nonatomic) dispatch_source_t petsWatcher;
390
+ @property(nonatomic) NSTextField *sampleLine;
391
+ @end
392
+
393
+ // 选择列表一行几只。窗口最窄时(内容区约 520pt)每张卡也有 110pt 以上,名字放得下。
394
+ static const NSUInteger PetPickerColumns = 4;
395
+
396
+ @implementation CCPetsPetPage
397
+
398
+ - (NSString *)pageTitle {
399
+ return L(@"Pet");
400
+ }
401
+
402
+ - (NSString *)pageSubtitle {
403
+ return L(@"Pick the pet that lives on your desktop, its size, how chatty it is and how it reacts when poked.");
404
+ }
405
+
406
+ - (void)loadView {
407
+ self.petTiles = [NSMutableDictionary dictionary];
408
+ self.petSprites = [NSMutableDictionary dictionary];
409
+ self.sheetCache = [NSMutableDictionary dictionary];
410
+ self.petDeleteButtons = [NSMutableDictionary dictionary];
411
+ self.petDeleteItems = [NSMutableDictionary dictionary];
412
+ [super loadView];
413
+ // 切宠物不走 defaults 写入口(选中项记在桌宠自己身上),靠名片通知得知换了。
414
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(petDidChange:)
415
+ name:CCPetsPetCardDidChangeNotification object:nil];
416
+ // 文件夹一开始可能不存在(监视不上),回到窗口时再对一次,兜住这种情况。
417
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(windowDidBecomeKey:)
418
+ name:NSWindowDidBecomeKeyNotification object:nil];
419
+ [self startWatchingPetsDirectory];
420
+ }
421
+
422
+ - (void)dealloc {
423
+ [self stopWatchingPetsDirectory];
424
+ }
425
+
426
+ - (void)petDidChange:(NSNotification *)notification {
427
+ // 删掉当前那只时 AppDelegate 会换到下一只并发这条通知,此时列表也少了一只。
428
+ [self reloadPickerIfChanged];
429
+ [self updatePetSelection];
430
+ }
431
+
432
+ - (void)windowDidBecomeKey:(NSNotification *)notification {
433
+ if (notification.object != self.view.window) return;
434
+ if (!self.petsWatcher) [self startWatchingPetsDirectory];
435
+ [self reloadPickerIfChanged];
436
+ }
437
+
438
+ - (void)startWatchingPetsDirectory {
439
+ [self stopWatchingPetsDirectory];
440
+ int descriptor = open(OwnPetsDirectory().fileSystemRepresentation, O_EVTONLY);
441
+ if (descriptor < 0) return;
442
+ dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, (uintptr_t)descriptor,
443
+ DISPATCH_VNODE_WRITE | DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME, dispatch_get_main_queue());
444
+ __weak typeof(self) weakSelf = self;
445
+ dispatch_source_set_event_handler(source, ^{
446
+ typeof(self) page = weakSelf;
447
+ if (!page) return;
448
+ // 文件夹本身被删或改名,旧描述符就废了,重新打开。
449
+ if (dispatch_source_get_data(source) & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME)) {
450
+ [page startWatchingPetsDirectory];
451
+ }
452
+ // `pet add` 会连着改好几次(临时目录、改名),合并成一次重排。
453
+ [NSObject cancelPreviousPerformRequestsWithTarget:page selector:@selector(reloadPickerIfChanged) object:nil];
454
+ [page performSelector:@selector(reloadPickerIfChanged) withObject:nil afterDelay:0.3];
455
+ });
456
+ dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
457
+ self.petsWatcher = source;
458
+ dispatch_resume(source);
459
+ }
460
+
461
+ - (void)stopWatchingPetsDirectory {
462
+ if (!self.petsWatcher) return;
463
+ dispatch_source_cancel(self.petsWatcher);
464
+ self.petsWatcher = nil;
465
+ }
466
+
467
+ - (void)reloadPickerIfChanged {
468
+ NSMutableArray<NSString *> *ids = [NSMutableArray array];
469
+ for (NSDictionary *option in [self.actions petPickerOptions] ?: @[]) [ids addObject:option[@"id"]];
470
+ if (self.renderedPetIDs && [ids isEqualToArray:self.renderedPetIDs]) return;
471
+ [self rebuildPicker];
472
+ }
473
+
474
+ - (void)buildContent {
475
+ __weak typeof(self) weakSelf = self;
476
+
477
+ NSStackView *rows = [NSStackView stackViewWithViews:@[]];
478
+ rows.orientation = NSUserInterfaceLayoutOrientationVertical;
479
+ rows.alignment = NSLayoutAttributeLeading;
480
+ rows.spacing = 10;
481
+ self.pickerRows = rows;
482
+ [self.form addView:rows];
483
+ [self rebuildPicker];
484
+
485
+ // 大小
486
+ NSSlider *scale = [self sliderWithMinimum:CCPetsPetMinimumScale maximum:CCPetsPetMaximumScale width:200];
487
+ NSTextField *scaleLabel = [self sliderValueLabel];
488
+ [self bind:scale to:^(NSSlider *sender) { [weakSelf.actions updatePetScale:sender.doubleValue]; }];
489
+ [self.reloaders addObject:^{
490
+ CGFloat value = CCPetsPetScalePreference();
491
+ scale.doubleValue = value;
492
+ scaleLabel.stringValue = [NSString stringWithFormat:@"%ld%%", (long)lround(value * 100)];
493
+ }];
494
+ [self.form addGroupWithTitle:nil rows:@[
495
+ [CCPetsFormBuilder rowWithTitle:L(@"Pet Size") controls:@[scale, scaleLabel]],
496
+ [self switchRowWithTitle:L(@"Import Codex Pets") subtitle:L(@"Copy pets from ~/.codex/pets into your own folder")
497
+ key:ImportCodexPetsKey
498
+ apply:^(id<CCPetsSettingsActions> actions, BOOL enabled) { [actions updateImportCodexPets:enabled]; }],
499
+ ] footer:nil];
500
+
501
+ // 碎碎念
502
+ NSSegmentedControl *frequency = [self segmentedWithOptions:@[
503
+ @[L(@"Rarely"), @"low"], @[L(@"Normal"), @"normal"], @[L(@"Often"), @"high"], @[L(@"Chatty"), @"chatty"]]
504
+ selected:^id { return [NSUserDefaults.standardUserDefaults stringForKey:PetSpeechFrequencyKey] ?: @"normal"; }
505
+ action:^(NSString *value) { [weakSelf.actions updateSpeechFrequency:value]; }];
506
+ NSPopUpButton *source = [self popUpWithOptions:@[
507
+ @[L(@"Pet-specific Lines"), PetPhrasesSourcePet], @[L(@"Default Lines"), PetPhrasesSourceDefault]]
508
+ selected:^id { return PetPhrasesSource(); }
509
+ action:^(NSString *value) { [weakSelf.actions updatePhrasesSource:value]; }];
510
+
511
+ // 先抽一句给用户看,满意再让桌面上的宠物说:换了台词来源能马上听到区别。
512
+ NSTextField *sample = CCPetsLabel(@"", 12, NSFontWeightRegular, CCPetsSecondaryInkColor());
513
+ [sample setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
514
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
515
+ self.sampleLine = sample;
516
+ NSButton *say = [self smallButtonWithTitle:L(@"Say It") action:^{
517
+ NSString *text = weakSelf.sampleLine.toolTip;
518
+ if (text.length == 0) text = [weakSelf.actions sampleSpeechLine];
519
+ if (text.length > 0) [weakSelf.actions presentSpeechText:text];
520
+ [weakSelf drawSampleLine];
521
+ }];
522
+ NSButton *edit = [self smallButtonWithTitle:L(@"Edit Lines…") action:^{ [weakSelf.actions editPhrasesFile:nil]; }];
523
+ [self drawSampleLine];
524
+ [self.reloaders addObject:^{ [weakSelf drawSampleLine]; }];
525
+
526
+ [self.form addGroupWithTitle:L(@"Chatter") rows:@[
527
+ [self switchRowWithTitle:L(@"Let the pet talk on its own") subtitle:nil key:PetSpeechEnabledKey
528
+ apply:^(id<CCPetsSettingsActions> actions, BOOL enabled) { [actions updateSpeechEnabled:enabled]; }],
529
+ [CCPetsFormBuilder rowWithTitle:L(@"Frequency") controls:@[frequency]],
530
+ [CCPetsFormBuilder rowWithTitle:L(@"Line Source") controls:@[source]],
531
+ [CCPetsFormBuilder rowWithTitle:L(@"Try a Line") controls:@[sample, say, edit]],
532
+ ] footer:nil];
533
+
534
+ // 戳它的反应是宠物自己的性格,和碎碎念放在一起,不和系统通知混在一页。
535
+ [self.form addGroupWithTitle:L(@"Click Reactions") rows:@[
536
+ [self switchRowWithTitle:L(@"React when poked") subtitle:nil key:PetInteractionEnabledKey
537
+ apply:^(id<CCPetsSettingsActions> actions, BOOL enabled) {
538
+ [actions updatePetInteractionEnabled:enabled];
539
+ }],
540
+ [self stepperRowWithTitle:L(@"Hearts After") key:PetInteractionHeartThresholdKey
541
+ minimum:2 maximum:20 increment:1 fallback:3
542
+ format:^NSString *(double value) { return ClickCountText((NSInteger)value); }],
543
+ [self stepperRowWithTitle:L(@"Annoyed After") key:PetInteractionAnnoyedThresholdKey
544
+ minimum:3 maximum:50 increment:1 fallback:10
545
+ format:^NSString *(double value) { return ClickCountText((NSInteger)value); }],
546
+ [self stepperRowWithTitle:L(@"Click Window") key:PetInteractionIntervalKey
547
+ minimum:0.4 maximum:3.0 increment:0.1 fallback:1.2
548
+ format:^NSString *(double value) {
549
+ return [[NSString stringWithFormat:@"%.1f", value] stringByAppendingString:L(@" s")];
550
+ }],
551
+ ] footer:nil];
552
+ }
553
+
554
+ - (void)drawSampleLine {
555
+ NSString *text = [self.actions sampleSpeechLine];
556
+ self.sampleLine.toolTip = text;
557
+ self.sampleLine.stringValue = text.length > 0 ? [NSString stringWithFormat:L(@"“%@”"), text] : @"";
558
+ }
559
+
560
+ // 宠物卡片:精灵图 + 名字 + 来源。最后一张是"添加宠物",打开素材文件夹。
561
+ - (void)rebuildPicker {
562
+ for (NSView *view in [self.pickerRows.arrangedSubviews copy]) {
563
+ [self.pickerRows removeArrangedSubview:view];
564
+ [view removeFromSuperview];
565
+ }
566
+ [self.petTiles removeAllObjects];
567
+ [self.petSprites removeAllObjects];
568
+ [self.petDeleteButtons removeAllObjects];
569
+ [self.petDeleteItems removeAllObjects];
570
+ NSArray<NSDictionary *> *options = [self.actions petPickerOptions] ?: @[];
571
+ self.renderedPetIDs = [options valueForKey:@"id"];
572
+ NSMutableArray<NSView *> *tiles = [NSMutableArray array];
573
+ __weak typeof(self) weakSelf = self;
574
+ for (NSDictionary *option in options) {
575
+ NSString *petID = option[@"id"];
576
+ CCPetsSpriteView *sprite = [[CCPetsSpriteView alloc] initWithFrame:NSZeroRect];
577
+ CCPetsTileView *tile = [self tileWithTop:sprite title:option[@"name"]
578
+ subtitle:[option[@"builtin"] boolValue] ? L(@"Built-in") : L(@"Your folder")];
579
+ tile.onClick = ^{ [weakSelf.actions switchPetToID:petID]; };
580
+ tile.toolTip = option[@"name"];
581
+ self.petTiles[petID] = tile;
582
+ self.petSprites[petID] = sprite;
583
+ if (![option[@"builtin"] boolValue]) [self attachDeleteControlsToTile:tile option:option];
584
+ [tiles addObject:tile];
585
+ [self loadSheetForOption:option intoSprite:sprite];
586
+ }
587
+ NSTextField *plus = CCPetsLabel(@"+", 30, NSFontWeightLight, CCPetsTertiaryInkColor());
588
+ plus.alignment = NSTextAlignmentCenter;
589
+ CCPetsTileView *add = [self tileWithTop:plus title:L(@"Add a Pet") subtitle:L(@"cc-pets pet add <name>")];
590
+ add.onClick = ^{ RevealFolder(OwnPetsDirectory()); };
591
+ add.toolTip = L(@"Opens your pets folder. Put a sprite sheet in its own folder there, or run cc-pets pet add <name>.");
592
+ [tiles addObject:add];
593
+
594
+ for (NSUInteger start = 0; start < tiles.count; start += PetPickerColumns) {
595
+ NSMutableArray<NSView *> *rowViews = [NSMutableArray array];
596
+ for (NSUInteger index = start; index < start + PetPickerColumns; index++) {
597
+ // 末行不满时用空视图占位,卡片宽度和上面几行对齐。
598
+ [rowViews addObject:index < tiles.count ? tiles[index] : [NSView new]];
599
+ }
600
+ NSStackView *row = [NSStackView stackViewWithViews:rowViews];
601
+ row.distribution = NSStackViewDistributionFillEqually;
602
+ row.spacing = 10;
603
+ row.alignment = NSLayoutAttributeTop;
604
+ row.translatesAutoresizingMaskIntoConstraints = NO;
605
+ [self.pickerRows addArrangedSubview:row];
606
+ [row.widthAnchor constraintEqualToAnchor:self.pickerRows.widthAnchor].active = YES;
607
+ }
608
+ [self updatePetSelection];
609
+ }
610
+
611
+ - (void)attachDeleteControlsToTile:(CCPetsTileView *)tile option:(NSDictionary *)option {
612
+ NSString *petID = option[@"id"];
613
+ NSString *name = option[@"name"];
614
+ __weak typeof(self) weakSelf = self;
615
+ void (^confirm)(void) = ^{ [weakSelf confirmDeletePetWithID:petID name:name]; };
616
+
617
+ NSButton *trash = [NSButton buttonWithImage:[NSImage imageWithSystemSymbolName:@"trash"
618
+ accessibilityDescription:L(@"Delete pet")] target:nil action:nil];
619
+ trash.bordered = NO;
620
+ trash.contentTintColor = CCPetsSecondaryInkColor();
621
+ trash.toolTip = L(@"Delete pet");
622
+ [self bind:trash to:^(id sender) { confirm(); }];
623
+ trash.translatesAutoresizingMaskIntoConstraints = NO;
624
+ [tile addSubview:trash];
625
+ [NSLayoutConstraint activateConstraints:@[
626
+ [trash.topAnchor constraintEqualToAnchor:tile.topAnchor constant:6],
627
+ [trash.trailingAnchor constraintEqualToAnchor:tile.trailingAnchor constant:-6],
628
+ [trash.widthAnchor constraintEqualToConstant:20],
629
+ [trash.heightAnchor constraintEqualToConstant:20],
630
+ ]];
631
+ tile.hoverAccessoryView = trash;
632
+
633
+ // 右键菜单:键盘 / 旁白用户摸不到悬停按钮,也给他们一条路。
634
+ CCPetsSettingsHandler *handler = [CCPetsSettingsHandler new];
635
+ handler.block = ^(id sender) { confirm(); };
636
+ [self.handlers addObject:handler];
637
+ NSMenu *menu = [NSMenu new];
638
+ menu.autoenablesItems = NO;
639
+ NSMenuItem *item = [menu addItemWithTitle:L(@"Delete pet") action:@selector(invoke:) keyEquivalent:@""];
640
+ item.target = handler;
641
+ tile.menu = menu;
642
+
643
+ self.petDeleteButtons[petID] = trash;
644
+ self.petDeleteItems[petID] = item;
645
+ }
646
+
647
+ - (void)confirmDeletePetWithID:(NSString *)petID name:(NSString *)name {
648
+ if ([petID isEqualToString:[self.actions currentPetID]]) return;
649
+ NSAlert *alert = [NSAlert new];
650
+ alert.alertStyle = NSAlertStyleWarning;
651
+ alert.messageText = [NSString stringWithFormat:L(@"Delete “%@”?"), name ?: @""];
652
+ alert.informativeText = L(@"This can't be undone. Continue?");
653
+ NSButton *deleteButton = [alert addButtonWithTitle:L(@"Delete")];
654
+ deleteButton.hasDestructiveAction = YES;
655
+ [alert addButtonWithTitle:L(@"Cancel")];
656
+ __weak typeof(self) weakSelf = self;
657
+ void (^finish)(NSModalResponse) = ^(NSModalResponse response) {
658
+ if (response != NSAlertFirstButtonReturn) return;
659
+ // 删除失败时 AppDelegate 自己会弹错误,这里只管成功后重排列表。
660
+ if ([weakSelf.actions deletePetWithID:petID]) [weakSelf rebuildPicker];
661
+ };
662
+ NSWindow *window = self.view.window;
663
+ if (window) [alert beginSheetModalForWindow:window completionHandler:finish];
664
+ else finish([alert runModal]);
665
+ }
666
+
667
+ - (CCPetsTileView *)tileWithTop:(NSView *)top title:(NSString *)title subtitle:(NSString *)subtitle {
668
+ CCPetsTileView *tile = [CCPetsTileView new];
669
+ NSTextField *name = CCPetsLabel(title, 12, NSFontWeightSemibold, CCPetsInkColor());
670
+ NSTextField *detail = CCPetsLabel(subtitle, 11, NSFontWeightRegular, CCPetsTertiaryInkColor());
671
+ for (NSTextField *label in @[name, detail]) {
672
+ label.alignment = NSTextAlignmentCenter;
673
+ [label setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
674
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
675
+ }
676
+ for (NSView *view in @[top, name, detail]) {
677
+ view.translatesAutoresizingMaskIntoConstraints = NO;
678
+ [tile addSubview:view];
679
+ }
680
+ [NSLayoutConstraint activateConstraints:@[
681
+ // 素材格子是 140×150,按同样比例缩小。
682
+ [top.topAnchor constraintEqualToAnchor:tile.topAnchor constant:12],
683
+ [top.centerXAnchor constraintEqualToAnchor:tile.centerXAnchor],
684
+ [top.widthAnchor constraintEqualToConstant:66],
685
+ [top.heightAnchor constraintEqualToConstant:72],
686
+ [name.topAnchor constraintEqualToAnchor:top.bottomAnchor constant:6],
687
+ [name.leadingAnchor constraintEqualToAnchor:tile.leadingAnchor constant:8],
688
+ [name.trailingAnchor constraintEqualToAnchor:tile.trailingAnchor constant:-8],
689
+ [detail.topAnchor constraintEqualToAnchor:name.bottomAnchor constant:1],
690
+ [detail.leadingAnchor constraintEqualToAnchor:tile.leadingAnchor constant:8],
691
+ [detail.trailingAnchor constraintEqualToAnchor:tile.trailingAnchor constant:-8],
692
+ [detail.bottomAnchor constraintEqualToAnchor:tile.bottomAnchor constant:-12],
693
+ ]];
694
+ return tile;
695
+ }
696
+
697
+ // 精灵图解码要几十毫秒一张,Codex 导入的宠物可能有几十只:每张放到下一轮主线程再解,
698
+ // 页面先出来,图一张张补上。解码器会读屏幕倍率,所以留在主线程。
699
+ - (void)loadSheetForOption:(NSDictionary *)option intoSprite:(CCPetsSpriteView *)sprite {
700
+ NSString *path = option[@"path"];
701
+ NSInteger rowCount = [option[@"rowCount"] integerValue] ?: 9;
702
+ NSImage *cached = self.sheetCache[path];
703
+ if (cached) {
704
+ [sprite setSheet:cached rowCount:rowCount];
705
+ return;
706
+ }
707
+ __weak typeof(self) weakSelf = self;
708
+ __weak CCPetsSpriteView *weakSprite = sprite;
709
+ dispatch_async(dispatch_get_main_queue(), ^{
710
+ if (!weakSelf || !weakSprite || path.length == 0) return;
711
+ NSImage *sheet = LoadPetSpriteImage(path, NSMakeSize(66, 72), rowCount);
712
+ if (!sheet) return;
713
+ weakSelf.sheetCache[path] = sheet;
714
+ [weakSprite setSheet:sheet rowCount:rowCount];
715
+ });
716
+ }
717
+
718
+ - (void)updatePetSelection {
719
+ NSString *current = [self.actions currentPetID];
720
+ [self.petTiles enumerateKeysAndObjectsUsingBlock:^(NSString *petID, CCPetsTileView *tile, BOOL *stop) {
721
+ BOOL selected = [petID isEqualToString:current];
722
+ tile.selected = selected;
723
+ // 只让选中的那只动,其余停在第一帧。
724
+ self.petSprites[petID].playing = selected;
725
+ NSButton *trash = self.petDeleteButtons[petID];
726
+ if (trash) {
727
+ trash.hidden = YES;
728
+ tile.hoverAccessoryView = selected ? nil : trash;
729
+ self.petDeleteItems[petID].enabled = !selected;
730
+ }
731
+ }];
732
+ }
733
+
734
+ @end
735
+
736
+ #pragma mark - 提醒
737
+
738
+ @implementation CCPetsAlertsPage
739
+
740
+ - (NSString *)pageTitle {
741
+ return L(@"Alerts");
742
+ }
743
+
744
+ - (NSString *)pageSubtitle {
745
+ return L(@"When to interrupt you: system notifications, the status card and message badges.");
746
+ }
747
+
748
+ - (void)buildContent {
749
+ [self.form addGroupWithTitle:L(@"Notifications") rows:@[
750
+ [self notificationRowWithTitle:L(@"Awaiting approval") subtitle:L(@"An Agent is stuck on a permission prompt")
751
+ key:NotificationApprovalKey],
752
+ [self notificationRowWithTitle:L(@"Task failed") subtitle:nil key:NotificationFailureKey],
753
+ [self notificationRowWithTitle:L(@"Task done") subtitle:nil key:NotificationCompletionKey],
754
+ [self notificationRowWithTitle:L(@"Stalled") subtitle:L(@"The same step has been running too long")
755
+ key:NotificationStallKey],
756
+ ] footer:nil];
757
+
758
+ // CC Bridge 这里只放只影响桌宠的两项;启用和免审批会改 Claude Code / Codex 的配置,仍在右键菜单里。
759
+ [self.form addGroupWithTitle:L(@"Desktop Status Card") rows:@[
760
+ [self switchRowWithTitle:L(@"Show Status Card") subtitle:L(@"The card next to the pet while an Agent is working")
761
+ key:StatusBubbleExpandedKey
762
+ apply:^(id<CCPetsSettingsActions> actions, BOOL enabled) { [actions updateStatusBubbleExpanded:enabled]; }],
763
+ [self switchRowWithTitle:L(@"CC Bridge unread badge") subtitle:nil key:BridgeBadgeEnabledKey
764
+ apply:^(id<CCPetsSettingsActions> actions, BOOL enabled) { [actions updateBridgeBadgeEnabled:enabled]; }],
765
+ [self notificationRowWithTitle:L(@"CC Bridge message notifications")
766
+ subtitle:L(@"Only who sent it to whom, never the message") key:BridgeNotificationKey],
767
+ ] footer:L(@"Enabling CC Bridge, auto-approve and other options that change Claude Code / Codex settings stay in the pet's right-click menu.")];
768
+ }
769
+
770
+ @end
771
+
772
+ #pragma mark - 通用
773
+
774
+ @interface CCPetsGeneralPage ()
775
+ @property(nonatomic) CCPetsGlassView *glassPreview;
776
+ @property(nonatomic, copy) NSArray<NSDictionary *> *usageProfiles;
777
+ // 终端跳转只用一张卡片,行随检测结果重建;未运行 / 不支持的折叠到末尾一行。
778
+ @property(nonatomic) NSView *terminalJumpCard;
779
+ @property(nonatomic) BOOL terminalJumpShowAll;
780
+ @property(nonatomic, copy) NSArray *terminalJumpSnapshot;
781
+ @property(nonatomic) NSTimer *ideStatusTimer;
782
+ @property(nonatomic) BOOL ideStatusRefreshing;
783
+ @end
784
+
785
+ // 汇总预览外的玻璃:被拉宽时圆角跟着内容一起等比放大,和真实面板的比例一致。
786
+ @implementation CCPetsGeneralPage
787
+
788
+ - (void)loadView {
789
+ [super loadView];
790
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(preferencesDidChange:)
791
+ name:CCPetsProfilesDidChangeNotification object:nil];
792
+ }
793
+
794
+ - (void)viewWillAppear {
795
+ [super viewWillAppear];
796
+ [self reloadValues];
797
+ [self refreshIDEIntegration];
798
+ [self.ideStatusTimer invalidate];
799
+ __weak typeof(self) weakSelf = self;
800
+ self.ideStatusTimer = [NSTimer scheduledTimerWithTimeInterval:5 repeats:YES block:^(NSTimer *timer) {
801
+ [weakSelf refreshIDEIntegration];
802
+ }];
803
+ }
804
+
805
+ - (void)viewDidDisappear {
806
+ [super viewDidDisappear];
807
+ [self.ideStatusTimer invalidate];
808
+ self.ideStatusTimer = nil;
809
+ }
810
+
811
+ - (void)refreshIDEIntegration {
812
+ if (self.ideStatusRefreshing) return;
813
+ self.ideStatusRefreshing = YES;
814
+ __weak typeof(self) weakSelf = self;
815
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
816
+ NSArray *snapshot = @[CCPetsTerminalIntegrationSnapshot(), CCPetsIDEIntegrationSnapshot(),
817
+ CCPetsVSCodeIntegrationSnapshot()];
818
+ dispatch_async(dispatch_get_main_queue(), ^{
819
+ CCPetsGeneralPage *page = weakSelf;
820
+ if (!page) return;
821
+ page.ideStatusRefreshing = NO;
822
+ // 每 5 秒刷新一次,状态没变就不重建,免得行闪烁、按钮丢焦点。
823
+ if ([snapshot isEqual:page.terminalJumpSnapshot]) return;
824
+ page.terminalJumpSnapshot = snapshot;
825
+ [page applyTerminalJumpSnapshot:snapshot];
826
+ });
827
+ });
828
+ }
829
+
830
+ // 右侧的状态小标:可选的彩色圆点 + 灰字。
831
+ - (NSTextField *)terminalJumpBadge:(NSString *)text dotColor:(NSColor *)color {
832
+ NSMutableAttributedString *value = [NSMutableAttributedString new];
833
+ NSFont *font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
834
+ if (color) {
835
+ [value appendAttributedString:[[NSAttributedString alloc] initWithString:@"● "
836
+ attributes:@{NSFontAttributeName: font, NSForegroundColorAttributeName: color}]];
837
+ }
838
+ [value appendAttributedString:[[NSAttributedString alloc] initWithString:text
839
+ attributes:@{NSFontAttributeName: font, NSForegroundColorAttributeName: CCPetsSecondaryInkColor()}]];
840
+ NSTextField *label = [NSTextField labelWithAttributedString:value];
841
+ [label setContentCompressionResistancePriority:NSLayoutPriorityRequired
842
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
843
+ return label;
844
+ }
845
+
846
+ - (NSView *)scriptTerminalRow:(NSDictionary *)terminal {
847
+ __weak typeof(self) weakSelf = self;
848
+ NSString *state = terminal[@"state"];
849
+ NSString *bundleID = terminal[@"bundleID"];
850
+ BOOL ghostty = [terminal[@"group"] isEqualToString:@"ghostty"];
851
+ NSString *title = [bundleID isEqualToString:@"com.apple.Terminal"] ? L(@"macOS Terminal") : terminal[@"name"];
852
+ if (ghostty && [terminal[@"version"] length]) title = [NSString stringWithFormat:@"%@ %@", title, terminal[@"version"]];
853
+ NSString *granted = ghostty ? L(@"Selects the tab and split by TTY")
854
+ : ([bundleID isEqualToString:@"com.googlecode.iterm2"] ? L(@"Selects the session by TTY") : L(@"Selects the tab by TTY"));
855
+ NSString *subtitle;
856
+ NSArray<NSView *> *controls;
857
+ if ([state isEqualToString:@"granted"]) {
858
+ subtitle = granted;
859
+ controls = @[[self terminalJumpBadge:L(@"Allowed") dotColor:NSColor.systemGreenColor]];
860
+ } else if ([state isEqualToString:@"denied"]) {
861
+ subtitle = L(@"Automation denied — the jump only brings the app forward");
862
+ controls = @[[self smallButtonWithTitle:L(@"Open System Settings…") action:^{ CCPetsOpenAutomationSettings(); }]];
863
+ } else if ([state isEqualToString:@"notDetermined"]) {
864
+ subtitle = L(@"macOS asks for permission on the first jump");
865
+ controls = @[[self smallButtonWithTitle:L(@"Allow…") action:^{
866
+ CCPetsRequestTerminalAutomation(bundleID, ^{ [weakSelf refreshIDEIntegration]; });
867
+ }]];
868
+ } else if ([state isEqualToString:@"unsupported"]) {
869
+ subtitle = L(@"Requires Ghostty 1.4 or later for exact jumps");
870
+ controls = @[[self terminalJumpBadge:L(@"Needs 1.4+") dotColor:nil]];
871
+ } else {
872
+ subtitle = L(@"Open the app to check automation permission");
873
+ controls = @[[self terminalJumpBadge:L(@"Not running") dotColor:nil]];
874
+ }
875
+ return [CCPetsFormBuilder rowWithTitle:title subtitle:subtitle controls:controls];
876
+ }
877
+
878
+ - (NSView *)jetBrainsRow:(NSDictionary *)ide {
879
+ __weak typeof(self) weakSelf = self;
880
+ NSString *state = ide[@"state"];
881
+ NSString *title = ide[@"name"];
882
+ NSString *version = ide[@"version"];
883
+ if (version.length && ![title containsString:version]) title = [NSString stringWithFormat:@"%@ %@", title, version];
884
+ BOOL automatic = [ide[@"autoInstall"] boolValue];
885
+ void (^install)(void) = ^{
886
+ CCPetsPromptInstallIDEPlugin(ide, ^{
887
+ weakSelf.terminalJumpSnapshot = nil;
888
+ [weakSelf refreshIDEIntegration];
889
+ });
890
+ };
891
+ NSString *subtitle;
892
+ NSArray<NSView *> *controls;
893
+ if ([state isEqualToString:@"connected"]) {
894
+ subtitle = L(@"Selects the terminal tab through the plugin");
895
+ controls = @[[self terminalJumpBadge:L(@"Connected") dotColor:NSColor.systemGreenColor]];
896
+ } else if ([state isEqualToString:@"installed"]) {
897
+ subtitle = L(@"Installed — open a project or restart the IDE to connect");
898
+ controls = @[[self terminalJumpBadge:L(@"Waiting to connect") dotColor:NSColor.systemOrangeColor]];
899
+ } else if ([state isEqualToString:@"pendingRestart"]) {
900
+ subtitle = [NSString stringWithFormat:L(@"Plugin %@ is in place — restart the IDE to load it"), ide[@"pluginVersion"] ?: @""];
901
+ controls = @[[self terminalJumpBadge:L(@"Restart needed") dotColor:NSColor.systemOrangeColor]];
902
+ } else if ([state isEqualToString:@"outdated"]) {
903
+ subtitle = [NSString stringWithFormat:L(@"Plugin %@ installed — %@ available"),
904
+ ide[@"pluginVersion"] ?: @"?", ide[@"bundledVersion"] ?: @"?"];
905
+ controls = @[[self smallButtonWithTitle:automatic ? L(@"Update") : L(@"Update…") action:install]];
906
+ } else if ([state isEqualToString:@"disabled"]) {
907
+ subtitle = L(@"Plugin disabled — enable it in the IDE's Plugins settings");
908
+ controls = @[[self terminalJumpBadge:L(@"Plugin disabled") dotColor:nil]];
909
+ } else if ([state isEqualToString:@"unsupported"]) {
910
+ subtitle = L(@"Requires version 2026.2 or 2026.3");
911
+ controls = @[[self terminalJumpBadge:L(@"Unsupported") dotColor:nil]];
912
+ } else {
913
+ subtitle = automatic ? L(@"Plugin not detected") : L(@"Plugin not detected — custom plugin folder, install manually");
914
+ controls = @[[self smallButtonWithTitle:automatic ? L(@"Install") : L(@"Install Plugin…") action:install]];
915
+ }
916
+ return [CCPetsFormBuilder rowWithTitle:title subtitle:subtitle controls:controls];
917
+ }
918
+
919
+ - (NSView *)vscodeRow:(NSDictionary *)app {
920
+ __weak typeof(self) weakSelf = self;
921
+ NSString *state = app[@"state"];
922
+ NSString *title = app[@"name"];
923
+ NSString *version = app[@"version"];
924
+ if (version.length && ![title containsString:version]) title = [NSString stringWithFormat:@"%@ %@", title, version];
925
+ BOOL automatic = [app[@"autoInstall"] boolValue];
926
+ void (^install)(void) = ^{
927
+ CCPetsPromptInstallVSCodeExtension(app, ^{
928
+ weakSelf.terminalJumpSnapshot = nil;
929
+ [weakSelf refreshIDEIntegration];
930
+ });
931
+ };
932
+ NSString *subtitle;
933
+ NSArray<NSView *> *controls;
934
+ if ([state isEqualToString:@"connected"]) {
935
+ subtitle = L(@"Selects the terminal through the extension");
936
+ controls = @[[self terminalJumpBadge:L(@"Connected") dotColor:NSColor.systemGreenColor]];
937
+ } else if ([state isEqualToString:@"installed"]) {
938
+ subtitle = [app[@"running"] boolValue] ? L(@"Installed — reload a window to connect")
939
+ : L(@"Installed — connects when the app starts");
940
+ controls = @[[self terminalJumpBadge:L(@"Waiting to connect") dotColor:NSColor.systemOrangeColor]];
941
+ } else if ([state isEqualToString:@"pendingRestart"]) {
942
+ subtitle = [NSString stringWithFormat:L(@"Extension %@ is in place — reload open windows to load it"), app[@"pluginVersion"] ?: @""];
943
+ controls = @[[self terminalJumpBadge:L(@"Reload needed") dotColor:NSColor.systemOrangeColor]];
944
+ } else if ([state isEqualToString:@"outdated"]) {
945
+ subtitle = [NSString stringWithFormat:L(@"Extension %@ installed — %@ available"),
946
+ app[@"pluginVersion"] ?: @"?", app[@"bundledVersion"] ?: @"?"];
947
+ controls = @[[self smallButtonWithTitle:automatic ? L(@"Update") : L(@"Update…") action:install]];
948
+ } else if ([state isEqualToString:@"disabled"]) {
949
+ subtitle = L(@"Extension disabled — enable it in the Extensions view");
950
+ controls = @[[self terminalJumpBadge:L(@"Plugin disabled") dotColor:nil]];
951
+ } else if ([state isEqualToString:@"unsupported"]) {
952
+ subtitle = L(@"Requires VS Code 1.80 or later");
953
+ controls = @[[self terminalJumpBadge:L(@"Unsupported") dotColor:nil]];
954
+ } else {
955
+ subtitle = automatic ? L(@"Extension not detected") : L(@"Extension not detected — no command line tool, install manually");
956
+ controls = @[[self smallButtonWithTitle:automatic ? L(@"Install") : L(@"Install Extension…") action:install]];
957
+ }
958
+ return [CCPetsFormBuilder rowWithTitle:title subtitle:subtitle controls:controls];
959
+ }
960
+
961
+ // 排序档位:0 正在工作,1 需要用户处理,2 可安装,3 未运行 / 不支持(默认折叠)。
962
+ static NSInteger TerminalJumpRank(NSDictionary *item) {
963
+ NSString *state = item[@"state"];
964
+ if ([state isEqualToString:@"connected"] || [state isEqualToString:@"granted"]) return 0;
965
+ if ([@[@"pendingRestart", @"installed", @"outdated", @"denied", @"notDetermined", @"disabled"] containsObject:state]) return 1;
966
+ // 插件缺失:应用开着时提示安装,没开就折叠。
967
+ if ([state isEqualToString:@"missing"]) return [item[@"running"] boolValue] ? 2 : 3;
968
+ return 3;
969
+ }
970
+
971
+ // 产品名之外的部分作为版本标签,例如 "IntelliJ IDEA 2026.3 EAP" → "2026.3 EAP"。
972
+ static NSString *TerminalJumpVersionLabel(NSDictionary *item, NSString *product) {
973
+ NSString *name = item[@"name"];
974
+ if (product.length && [name hasPrefix:product]) {
975
+ NSString *rest = [[name substringFromIndex:product.length]
976
+ stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
977
+ if (rest.length) return rest;
978
+ }
979
+ return [item[@"version"] length] ? item[@"version"] : name;
980
+ }
981
+
982
+ // 合并行里单个版本的简短状态。
983
+ static NSString *TerminalJumpShortState(NSDictionary *item, BOOL vscode) {
984
+ NSString *state = item[@"state"];
985
+ if ([state isEqualToString:@"connected"]) return L(@"Connected");
986
+ if ([state isEqualToString:@"installed"]) return L(@"Waiting to connect");
987
+ if ([state isEqualToString:@"pendingRestart"]) return vscode ? L(@"Reload needed") : L(@"Restart needed");
988
+ if ([state isEqualToString:@"outdated"]) return L(@"Update available");
989
+ if ([state isEqualToString:@"disabled"]) return L(@"Plugin disabled");
990
+ if ([state isEqualToString:@"unsupported"]) return L(@"Unsupported");
991
+ return L(@"Plugin not detected");
992
+ }
993
+
994
+ // 同一 JetBrains 产品的多个版本合成一行:副标题逐个列出版本状态,只给需要操作的版本放按钮。
995
+ - (NSView *)mergedIDERow:(NSArray<NSDictionary *> *)items product:(NSString *)product {
996
+ __weak typeof(self) weakSelf = self;
997
+ NSMutableArray<NSString *> *parts = [NSMutableArray array];
998
+ NSMutableArray<NSView *> *buttons = [NSMutableArray array];
999
+ for (NSDictionary *ide in items) {
1000
+ NSString *label = TerminalJumpVersionLabel(ide, product);
1001
+ [parts addObject:[NSString stringWithFormat:@"%@ %@", label, TerminalJumpShortState(ide, NO)]];
1002
+ NSString *state = ide[@"state"];
1003
+ BOOL outdated = [state isEqualToString:@"outdated"];
1004
+ if (!outdated && !([state isEqualToString:@"missing"] && [ide[@"running"] boolValue])) continue;
1005
+ BOOL automatic = [ide[@"autoInstall"] boolValue];
1006
+ NSString *base = outdated ? L(@"Update") : L(@"Install");
1007
+ NSString *title = [NSString stringWithFormat:@"%@ %@%@", base, label, automatic ? @"" : @"…"];
1008
+ [buttons addObject:[self smallButtonWithTitle:title action:^{
1009
+ CCPetsPromptInstallIDEPlugin(ide, ^{
1010
+ weakSelf.terminalJumpSnapshot = nil;
1011
+ [weakSelf refreshIDEIntegration];
1012
+ });
1013
+ }]];
1014
+ }
1015
+ NSArray<NSView *> *controls = buttons;
1016
+ if (buttons.count == 0) {
1017
+ // 没有可操作项时显示最好的那个状态(items 已按档位排好)。
1018
+ NSInteger rank = TerminalJumpRank(items.firstObject);
1019
+ NSColor *dot = rank == 0 ? NSColor.systemGreenColor : (rank == 1 &&
1020
+ ![items.firstObject[@"state"] isEqualToString:@"disabled"] ? NSColor.systemOrangeColor : nil);
1021
+ controls = @[[self terminalJumpBadge:TerminalJumpShortState(items.firstObject, NO) dotColor:dot]];
1022
+ }
1023
+ return [CCPetsFormBuilder rowWithTitle:product subtitle:[parts componentsJoinedByString:@" · "] controls:controls];
1024
+ }
1025
+
1026
+ - (void)applyTerminalJumpSnapshot:(NSArray *)snapshot {
1027
+ // 每个条目 = 卡片里的一行:{rank, title, build}。JetBrains 同产品多版本先合并。
1028
+ NSMutableArray<NSDictionary *> *entries = [NSMutableArray array];
1029
+ __weak typeof(self) weakSelf = self;
1030
+ for (NSDictionary *terminal in snapshot[0]) {
1031
+ NSString *name = [terminal[@"bundleID"] isEqualToString:@"com.apple.Terminal"] ? L(@"macOS Terminal") : terminal[@"name"];
1032
+ [entries addObject:@{@"rank": @(TerminalJumpRank(terminal)), @"title": name ?: @"",
1033
+ @"build": ^NSView *{ return [weakSelf scriptTerminalRow:terminal]; }}];
1034
+ }
1035
+ NSMutableDictionary<NSString *, NSMutableArray *> *products = [NSMutableDictionary dictionary];
1036
+ NSMutableArray<NSString *> *productOrder = [NSMutableArray array];
1037
+ for (NSDictionary *ide in snapshot[1]) {
1038
+ NSString *key = [ide[@"productName"] length] ? ide[@"productName"] : ide[@"name"];
1039
+ if (!products[key]) { products[key] = [NSMutableArray array]; [productOrder addObject:key]; }
1040
+ [products[key] addObject:ide];
1041
+ }
1042
+ NSComparator byRank = ^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
1043
+ return [@(TerminalJumpRank(a)) compare:@(TerminalJumpRank(b))];
1044
+ };
1045
+ for (NSString *product in productOrder) {
1046
+ NSArray *items = [products[product] sortedArrayWithOptions:NSSortStable usingComparator:byRank];
1047
+ NSDictionary *only = items.count == 1 ? items.firstObject : nil;
1048
+ [entries addObject:@{@"rank": @(TerminalJumpRank(items.firstObject)), @"title": product,
1049
+ @"build": only ? ^NSView *{ return [weakSelf jetBrainsRow:only]; }
1050
+ : ^NSView *{ return [weakSelf mergedIDERow:items product:product]; }}];
1051
+ }
1052
+ for (NSDictionary *app in snapshot[2]) {
1053
+ [entries addObject:@{@"rank": @(TerminalJumpRank(app)), @"title": app[@"name"] ?: @"",
1054
+ @"build": ^NSView *{ return [weakSelf vscodeRow:app]; }}];
1055
+ }
1056
+ NSArray *sorted = [entries sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
1057
+ return [a[@"rank"] compare:b[@"rank"]];
1058
+ }];
1059
+
1060
+ // 默认只显示需要关注的行,最多 5 行;其余收进末尾的“显示全部”。
1061
+ static const NSUInteger visibleLimit = 5;
1062
+ NSMutableArray<NSDictionary *> *prominent = [NSMutableArray array];
1063
+ NSMutableArray<NSDictionary *> *folded = [NSMutableArray array];
1064
+ for (NSDictionary *entry in sorted) {
1065
+ BOOL keep = [entry[@"rank"] integerValue] < 3 && prominent.count < visibleLimit;
1066
+ [(keep ? prominent : folded) addObject:entry];
1067
+ }
1068
+ NSMutableArray<NSView *> *rows = [NSMutableArray array];
1069
+ for (NSDictionary *entry in self.terminalJumpShowAll ? sorted : prominent) {
1070
+ [rows addObject:((NSView *(^)(void))entry[@"build"])()];
1071
+ }
1072
+ if (folded.count && !self.terminalJumpShowAll) {
1073
+ NSArray *names = [folded valueForKey:@"title"];
1074
+ NSString *title = [NSString stringWithFormat:L(@"%lu hidden"), (unsigned long)folded.count];
1075
+ [rows addObject:[CCPetsFormBuilder rowWithTitle:title subtitle:[names componentsJoinedByString:L(@", ")]
1076
+ controls:@[[self smallButtonWithTitle:L(@"Show All") action:^{
1077
+ weakSelf.terminalJumpShowAll = YES;
1078
+ if (weakSelf.terminalJumpSnapshot) [weakSelf applyTerminalJumpSnapshot:weakSelf.terminalJumpSnapshot];
1079
+ }]]]];
1080
+ } else if (folded.count) {
1081
+ [rows addObject:[CCPetsFormBuilder rowWithTitle:@"" controls:@[[self smallButtonWithTitle:L(@"Show Less") action:^{
1082
+ weakSelf.terminalJumpShowAll = NO;
1083
+ if (weakSelf.terminalJumpSnapshot) [weakSelf applyTerminalJumpSnapshot:weakSelf.terminalJumpSnapshot];
1084
+ }]]]];
1085
+ }
1086
+ if (rows.count == 0) {
1087
+ [rows addObject:[CCPetsFormBuilder rowWithTitle:L(@"No supported terminal detected") controls:@[]]];
1088
+ }
1089
+ [CCPetsFormBuilder replaceRowsInCard:self.terminalJumpCard withRows:rows];
1090
+ }
1091
+
1092
+ - (NSArray<NSDictionary *> *)currentUsageProfiles {
1093
+ NSMutableArray<NSDictionary *> *profiles = [NSMutableArray array];
1094
+ for (NSString *provider in @[@"claude", @"codex"]) {
1095
+ NSArray *registered = CCPetsProfilesForProvider(provider);
1096
+ [profiles addObjectsFromArray:registered.count > 0 ? registered : @[@{@"provider": provider}]];
1097
+ }
1098
+ return profiles.copy;
1099
+ }
1100
+
1101
+ - (void)reloadValues {
1102
+ if (![self.usageProfiles isEqualToArray:[self currentUsageProfiles]]) {
1103
+ // 新增、移除、改名或重新定位账号后重建行,同时释放旧控件的闭包。
1104
+ [self.handlers removeAllObjects];
1105
+ [self.reloaders removeAllObjects];
1106
+ [self.form removeAllContent];
1107
+ [self buildContent];
1108
+ }
1109
+ [super reloadValues];
1110
+ }
1111
+
1112
+ - (NSString *)pageTitle {
1113
+ return L(@"Settings");
1114
+ }
1115
+
1116
+ - (NSString *)pageSubtitle {
1117
+ return @"";
1118
+ }
1119
+
1120
+ - (NSView *)themePreviewLiquid:(BOOL)liquid {
1121
+ NSView *preview = [NSView new];
1122
+ preview.wantsLayer = YES;
1123
+ preview.layer.cornerRadius = 6;
1124
+ preview.layer.masksToBounds = YES;
1125
+ if (liquid) {
1126
+ CAGradientLayer *gradient = [CAGradientLayer layer];
1127
+ gradient.colors = @[(id)[NSColor colorWithSRGBRed:0.43 green:0.56 blue:0.70 alpha:1].CGColor,
1128
+ (id)[NSColor colorWithSRGBRed:0.18 green:0.29 blue:0.42 alpha:1].CGColor,
1129
+ (id)[NSColor colorWithSRGBRed:0.25 green:0.37 blue:0.27 alpha:1].CGColor];
1130
+ gradient.startPoint = CGPointMake(0, 1);
1131
+ gradient.endPoint = CGPointMake(1, 0);
1132
+ gradient.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
1133
+ [preview.layer addSublayer:gradient];
1134
+ } else {
1135
+ preview.layer.backgroundColor = [NSColor colorWithSRGBRed:0.12 green:0.14 blue:0.16 alpha:1].CGColor;
1136
+ }
1137
+ // Liquid Glass:玻璃铺满预览区,线条放在玻璃上;压暗调的是玻璃背后的压暗层,和桌宠浮层一致。
1138
+ NSView *container = preview;
1139
+ if (liquid) {
1140
+ CCPetsGlassView *glass = [[CCPetsGlassView alloc] initWithFrame:NSMakeRect(0, 0, 200, 62)
1141
+ material:NSVisualEffectMaterialUnderWindowBackground appearance:NSAppearanceNameDarkAqua cornerRadius:6];
1142
+ // 预览很矮,上下暗带调小;必须在 usesWidgetGlass 之前设。
1143
+ glass.edgeShadeHeight = 6;
1144
+ glass.edgeShadeAlpha = 0.45;
1145
+ glass.forcesLiquidGlass = YES;
1146
+ glass.usesWidgetGlass = YES;
1147
+ glass.translatesAutoresizingMaskIntoConstraints = NO;
1148
+ [preview addSubview:glass];
1149
+ [NSLayoutConstraint activateConstraints:@[
1150
+ [glass.leadingAnchor constraintEqualToAnchor:preview.leadingAnchor],
1151
+ [glass.trailingAnchor constraintEqualToAnchor:preview.trailingAnchor],
1152
+ [glass.topAnchor constraintEqualToAnchor:preview.topAnchor],
1153
+ [glass.bottomAnchor constraintEqualToAnchor:preview.bottomAnchor],
1154
+ ]];
1155
+ self.glassPreview = glass;
1156
+ container = glass.contentView;
1157
+ }
1158
+ NSArray<NSArray *> *bars = @[@[@1.0, liquid ? @0.55 : @0.25], @[@0.7, liquid ? @0.85 : @1.0], @[@0.45, liquid ? @0.55 : @0.25]];
1159
+ NSView *previous = nil;
1160
+ for (NSUInteger index = 0; index < bars.count; index++) {
1161
+ NSView *bar = [NSView new];
1162
+ bar.wantsLayer = YES;
1163
+ bar.layer.cornerRadius = 2;
1164
+ // 经典主题的第二条用强调青,和真正的经典面板一样。
1165
+ bar.layer.backgroundColor = (!liquid && index == 1)
1166
+ ? [NSColor colorWithSRGBRed:0.31 green:0.83 blue:0.90 alpha:1].CGColor
1167
+ : [NSColor colorWithWhite:1 alpha:[bars[index][1] doubleValue]].CGColor;
1168
+ bar.translatesAutoresizingMaskIntoConstraints = NO;
1169
+ [container addSubview:bar];
1170
+ [NSLayoutConstraint activateConstraints:@[
1171
+ [bar.leadingAnchor constraintEqualToAnchor:container.leadingAnchor constant:10],
1172
+ [bar.widthAnchor constraintEqualToAnchor:container.widthAnchor multiplier:[bars[index][0] doubleValue]
1173
+ constant:-20 * [bars[index][0] doubleValue]],
1174
+ [bar.heightAnchor constraintEqualToConstant:4],
1175
+ previous ? [bar.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:5]
1176
+ : [bar.topAnchor constraintEqualToAnchor:container.topAnchor constant:18],
1177
+ ]];
1178
+ previous = bar;
1179
+ }
1180
+ return preview;
1181
+ }
1182
+
1183
+ // accessory:卡片底部的附加行(Liquid Glass 卡片里放压暗滑块),可为 nil。
1184
+ - (CCPetsTileView *)themeTileLiquid:(BOOL)liquid accessory:(NSView *)accessory {
1185
+ CCPetsTileView *tile = [CCPetsTileView new];
1186
+ NSView *preview = [self themePreviewLiquid:liquid];
1187
+ NSTextField *title = CCPetsLabel(liquid ? @"Liquid Glass" : L(@"Classic"), 13, NSFontWeightSemibold, CCPetsInkColor());
1188
+ NSMutableArray<NSView *> *views = [NSMutableArray arrayWithObjects:preview, title, nil];
1189
+ // 两张卡片结构对齐:预览 → 标题 → 说明 → 底部一行(经典是说明文字,Liquid Glass 是压暗滑块)。
1190
+ NSTextField *note = CCPetsLabel(liquid ? L(@"macOS 26 or later") : L(@"Works on all macOS versions"),
1191
+ 11, NSFontWeightRegular, CCPetsTertiaryInkColor());
1192
+ [views addObject:note];
1193
+ if (accessory) [views addObject:accessory];
1194
+ for (NSView *view in views) {
1195
+ view.translatesAutoresizingMaskIntoConstraints = NO;
1196
+ [tile addSubview:view];
1197
+ }
1198
+ NSView *last = accessory ?: note ?: title;
1199
+ [NSLayoutConstraint activateConstraints:@[
1200
+ [preview.topAnchor constraintEqualToAnchor:tile.topAnchor constant:10],
1201
+ [preview.leadingAnchor constraintEqualToAnchor:tile.leadingAnchor constant:10],
1202
+ [preview.trailingAnchor constraintEqualToAnchor:tile.trailingAnchor constant:-10],
1203
+ [preview.heightAnchor constraintEqualToConstant:62],
1204
+ [title.topAnchor constraintEqualToAnchor:preview.bottomAnchor constant:10],
1205
+ [title.leadingAnchor constraintEqualToAnchor:tile.leadingAnchor constant:12],
1206
+ [title.trailingAnchor constraintLessThanOrEqualToAnchor:tile.trailingAnchor constant:-12],
1207
+ // 两张卡片等高(经典卡没有说明行),所以底边只约束"不超出",多出的高度留在下面。
1208
+ [last.bottomAnchor constraintLessThanOrEqualToAnchor:tile.bottomAnchor constant:-10],
1209
+ ]];
1210
+ if (note) {
1211
+ [NSLayoutConstraint activateConstraints:@[
1212
+ [note.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:1],
1213
+ [note.leadingAnchor constraintEqualToAnchor:title.leadingAnchor],
1214
+ ]];
1215
+ }
1216
+ if (accessory) {
1217
+ [NSLayoutConstraint activateConstraints:@[
1218
+ [accessory.topAnchor constraintEqualToAnchor:(note ?: title).bottomAnchor constant:8],
1219
+ [accessory.leadingAnchor constraintEqualToAnchor:tile.leadingAnchor constant:12],
1220
+ [accessory.trailingAnchor constraintEqualToAnchor:tile.trailingAnchor constant:-12],
1221
+ ]];
1222
+ // 附加行里是滑块这类控件,不该显示卡片的手形指针。
1223
+ if (liquid) tile.cursorExclusionView = accessory;
1224
+ }
1225
+ // 内容更多的 Liquid Glass 卡片决定高度,经典卡片通过等高约束跟随,多出的高度留在下面。
1226
+ if (liquid) [last.bottomAnchor constraintEqualToAnchor:tile.bottomAnchor constant:-10].active = YES;
1227
+ return tile;
1228
+ }
1229
+
1230
+ - (void)buildContent {
1231
+ __weak typeof(self) weakSelf = self;
1232
+
1233
+ // 浮层外观:两张主题卡片,压暗滑块放在 Liquid Glass 卡片里,拖动时上方预览实时变化。
1234
+ [self.form addGroupTitle:L(@"Panel Appearance") note:nil];
1235
+ // 滑块按 0–100 的强度展示,实际压暗仍是 0–45(换算在 CCPetsGlassDimLevelForPercent)。
1236
+ NSSlider *dim = [NSSlider sliderWithValue:0 minValue:0 maxValue:100 target:nil action:nil];
1237
+ dim.continuous = YES;
1238
+ dim.controlSize = NSControlSizeSmall;
1239
+ CCPetsApplyAccent(dim);
1240
+ [dim setContentHuggingPriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
1241
+ NSTextField *dimLabel = [self sliderValueLabel];
1242
+ NSTextField *dimTitle = CCPetsLabel(L(@"Dimming"), 11, NSFontWeightRegular, CCPetsSecondaryInkColor());
1243
+ NSStackView *dimRow = [NSStackView stackViewWithViews:@[dimTitle, dim, dimLabel]];
1244
+ dimRow.orientation = NSUserInterfaceLayoutOrientationHorizontal;
1245
+ dimRow.alignment = NSLayoutAttributeCenterY;
1246
+ dimRow.spacing = 8;
1247
+ dimRow.toolTip = L(@"Raise it when a bright wallpaper makes text hard to read");
1248
+ dim.toolTip = dimRow.toolTip;
1249
+
1250
+ NSTextField *classicDetail = CCPetsLabel(L(@"Opaque dark background for better readability"),
1251
+ 11, NSFontWeightRegular, CCPetsSecondaryInkColor());
1252
+ classicDetail.lineBreakMode = NSLineBreakByTruncatingTail;
1253
+ [classicDetail setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
1254
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
1255
+ NSStackView *classicRow = [NSStackView stackViewWithViews:@[classicDetail]];
1256
+ classicRow.alignment = NSLayoutAttributeCenterY;
1257
+ CCPetsTileView *classic = [self themeTileLiquid:NO accessory:classicRow];
1258
+ CCPetsTileView *liquid = [self themeTileLiquid:YES accessory:dimRow];
1259
+ classic.onClick = ^{ [weakSelf.actions updatePanelTheme:@"classic"]; };
1260
+ BOOL liquidAvailable = CCPetsLiquidGlassAvailable();
1261
+ if (liquidAvailable) liquid.onClick = ^{ [weakSelf.actions updatePanelTheme:@"liquid"]; };
1262
+ else liquid.alphaValue = 0.5;
1263
+ NSStackView *themes = [NSStackView stackViewWithViews:@[classic, liquid]];
1264
+ themes.distribution = NSStackViewDistributionFillEqually;
1265
+ themes.alignment = NSLayoutAttributeTop;
1266
+ themes.spacing = 10;
1267
+ themes.translatesAutoresizingMaskIntoConstraints = NO;
1268
+ // 两张卡片只占整行宽度的 70%,靠左排,避免比其他设置行更抢眼。
1269
+ NSView *themeRow = [NSView new];
1270
+ [themeRow addSubview:themes];
1271
+ [NSLayoutConstraint activateConstraints:@[
1272
+ [themes.leadingAnchor constraintEqualToAnchor:themeRow.leadingAnchor],
1273
+ [themes.topAnchor constraintEqualToAnchor:themeRow.topAnchor],
1274
+ [themes.bottomAnchor constraintEqualToAnchor:themeRow.bottomAnchor],
1275
+ [themes.widthAnchor constraintEqualToAnchor:themeRow.widthAnchor multiplier:0.7],
1276
+ ]];
1277
+ [self.form addView:themeRow];
1278
+ [classic.heightAnchor constraintEqualToAnchor:liquid.heightAnchor].active = YES;
1279
+ // 底部一行和滑块那行等高,文字与“压暗”对齐。两张卡片进了同一个父视图后才能互相约束。
1280
+ [classicRow.heightAnchor constraintEqualToAnchor:dimRow.heightAnchor].active = YES;
1281
+
1282
+ [self bind:dim to:^(NSSlider *sender) {
1283
+ NSInteger value = (NSInteger)lround(sender.doubleValue);
1284
+ dimLabel.stringValue = [NSString stringWithFormat:@"%ld%%", (long)value];
1285
+ [weakSelf showGlassDim:CCPetsGlassDimLevelForPercent(value)];
1286
+ [weakSelf.actions updateGlassDimLevel:@(value)];
1287
+ }];
1288
+ [self.reloaders addObject:^{
1289
+ BOOL isLiquid = [CCPetsPanelTheme() isEqualToString:@"liquid"] && liquidAvailable;
1290
+ classic.selected = !isLiquid;
1291
+ liquid.selected = isLiquid;
1292
+ NSInteger percent = CCPetsGlassDimPercent();
1293
+ dim.doubleValue = percent;
1294
+ dimLabel.stringValue = [NSString stringWithFormat:@"%ld%%", (long)percent];
1295
+ // 压暗只作用于原生玻璃,经典主题下没有这层。
1296
+ dim.enabled = isLiquid;
1297
+ [weakSelf showGlassDim:CCPetsGlassDimLevel()];
1298
+ }];
1299
+
1300
+ NSMutableArray<NSArray *> *languages = [NSMutableArray arrayWithObject:@[L(@"System Default"), CCPetsLanguageSystem]];
1301
+ for (NSString *language in CCPetsSupportedLanguages()) {
1302
+ [languages addObject:@[CCPetsLanguageDisplayName(language), language]];
1303
+ }
1304
+ NSPopUpButton *language = [self popUpWithOptions:languages
1305
+ selected:^id { return CCPetsLanguagePreference(); }
1306
+ action:^(NSString *value) {
1307
+ if ([value isEqualToString:CCPetsLanguagePreference()]) return;
1308
+ // 主窗口收到语言变更会重建本页,别在控件自己的 action 里把它拆掉。
1309
+ dispatch_async(dispatch_get_main_queue(), ^{ CCPetsSetLanguagePreference(value); });
1310
+ }];
1311
+ NSSegmentedControl *appearance = [self segmentedWithOptions:@[
1312
+ @[L(@"System Default"), @"system"], @[L(@"Light"), @"light"], @[L(@"Dark"), @"dark"]]
1313
+ selected:^id { return CCPetsMainWindowAppearancePreference(); }
1314
+ action:^(NSString *value) { CCPetsPrefSetObject(CCPetsMainWindowAppearanceKey, value); }];
1315
+ [self.form addGroupWithTitle:nil rows:@[
1316
+ [CCPetsFormBuilder rowWithTitle:L(@"Language") controls:@[language]],
1317
+ [CCPetsFormBuilder rowWithTitle:L(@"Window Appearance")
1318
+ subtitle:L(@"Only this window; the pet's panels follow Panel Appearance above") controls:@[appearance]],
1319
+ ] footer:nil];
1320
+
1321
+ [self.form addGroupWithTitle:L(@"Launch Protection") rows:@[
1322
+ [self switchRowWithTitle:@"Shadowrocket"
1323
+ subtitle:L(@"Block Claude / Codex when Shadowrocket is disconnected or the exit is in an unsupported region")
1324
+ key:CCPetsShadowrocketLaunchCheckKey
1325
+ apply:^(id<CCPetsSettingsActions> actions, BOOL enabled) {
1326
+ CCPetsPrefSetBool(CCPetsShadowrocketLaunchCheckKey, enabled);
1327
+ }],
1328
+ ] footer:L(@"Off by default. Checks each service's exit IP and region through CC Pets wrappers; does not validate your account or API key.")];
1329
+
1330
+ // 悬停面板:每家一个胶囊,点一下在订阅额度和 Token 用量之间切换,和右键菜单同一个样子。
1331
+ [self.form addGroupTitle:L(@"Hover Panel") note:L(@"Click a pill to switch")];
1332
+ NSMutableArray<NSView *> *panelRows = [NSMutableArray array];
1333
+ self.usageProfiles = [self currentUsageProfiles];
1334
+ for (NSDictionary *profile in self.usageProfiles) {
1335
+ NSString *provider = [profile[@"provider"] isEqualToString:@"codex"] ? @"Codex" : @"Claude";
1336
+ NSString *name = profile[@"displayName"] ?: provider;
1337
+ CCPetsPillButton *pill = [CCPetsPillButton new];
1338
+ [pill setAccessibilityLabel:[NSString stringWithFormat:L(@"%@ usage display"), name]];
1339
+ NSView *row = [CCPetsFormBuilder rowWithTitle:name subtitle:@" " controls:@[pill]];
1340
+ NSTextField *detail = [self subtitleLabelInRow:row];
1341
+ [self bind:pill to:^(id sender) {
1342
+ NSDictionary *current = profile[@"id"] ? CCPetsProfileWithID(profile[@"id"]) : profile;
1343
+ if (!current || !CCPetsProfileCanSwitchUsageMode(current)) return;
1344
+ BOOL api = CCPetsProfileShowsAPIUsage(current);
1345
+ if (current[@"id"]) [weakSelf.actions updateUsageDisplayMode:api ? @"subscription" : @"api" forProfileID:current[@"id"]];
1346
+ else [weakSelf.actions updateUsageDisplayMode:api ? @"subscription" : @"api" forKey:CCPetsUsageModePreferenceKey(current)];
1347
+ }];
1348
+ [self.reloaders addObject:^{
1349
+ NSDictionary *current = profile[@"id"] ? CCPetsProfileWithID(profile[@"id"]) : profile;
1350
+ BOOL api = current && CCPetsProfileShowsAPIUsage(current);
1351
+ pill.enabled = current && CCPetsProfileCanSwitchUsageMode(current);
1352
+ pill.toolTip = pill.enabled ? nil : L(@"API authentication: usage display is fixed to API.");
1353
+ pill.title = api ? L(@"API") : L(@"Plan");
1354
+ // 订阅用绿、用量用蓝,和右键菜单里的胶囊一致。
1355
+ pill.fillColor = api ? CCPetsChartColor(6) : CCPetsChartColor(5);
1356
+ detail.stringValue = !pill.enabled ? L(@"API authentication: usage display is fixed to API.")
1357
+ : (api ? L(@"Token usage: today's new and cached tokens")
1358
+ : L(@"Plan quota: what's left of the 5-hour and weekly limits"));
1359
+ }];
1360
+ [panelRows addObject:row];
1361
+ }
1362
+ // 三项可以任意组合:用"可多选"的分段控件,一行放得下,也和上面的分段控件一个样子。
1363
+ NSArray<NSString *> *metricKeys = @[SystemCPUEnabledKey, SystemTemperatureEnabledKey, SystemMemoryEnabledKey];
1364
+ NSSegmentedControl *metrics = [NSSegmentedControl segmentedControlWithLabels:@[@"CPU", L(@"Temperature"), L(@"Memory")]
1365
+ trackingMode:NSSegmentSwitchTrackingSelectAny target:nil action:nil];
1366
+ metrics.controlSize = NSControlSizeSmall;
1367
+ metrics.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
1368
+ CCPetsApplyAccent(metrics);
1369
+ [self bind:metrics to:^(NSSegmentedControl *sender) {
1370
+ NSInteger segment = sender.selectedSegment;
1371
+ if (segment < 0 || segment >= (NSInteger)metricKeys.count) return;
1372
+ [weakSelf.actions updateSystemMetric:metricKeys[(NSUInteger)segment] enabled:[sender isSelectedForSegment:segment]];
1373
+ }];
1374
+ [self.reloaders addObject:^{
1375
+ for (NSUInteger index = 0; index < metricKeys.count; index++) {
1376
+ [metrics setSelected:CCPetsPrefBool(metricKeys[index]) forSegment:(NSInteger)index];
1377
+ }
1378
+ }];
1379
+ [panelRows addObject:[CCPetsFormBuilder rowWithTitle:L(@"System Status") controls:@[metrics]]];
1380
+ [self.form addGroupWithTitle:nil rows:panelRows footer:nil];
1381
+
1382
+ // 终端跳转:一张卡片,行在 refreshIDEIntegration 拿到检测结果后填入。
1383
+ [self.form addGroupTitle:L(@"Terminal Jump") note:L(@"Click an agent card to return to its terminal")
1384
+ info:L(@"Terminal, iTerm2 and Ghostty are located by TTY through AppleScript and need CC Pets allowed under System Settings → Privacy & Security → Automation. JetBrains IDEs need the CC Pets Terminal plugin (2026.2 / 2026.3, local Reworked terminal), installed in each IDE separately. VS Code and its forks such as Cursor and Windsurf need the CC Pets Terminal extension, installed in each app separately; remote windows are not supported. Other terminals such as Warp are only brought forward.")];
1385
+ NSView *checking = [CCPetsFormBuilder rowWithTitle:L(@"Checking…") controls:@[]];
1386
+ self.terminalJumpCard = [self.form addGroupWithTitle:nil rows:@[checking] footer:nil];
1387
+ self.terminalJumpSnapshot = nil;
1388
+
1389
+ [self.form addGroupWithTitle:L(@"Data") rows:@[
1390
+ [CCPetsFormBuilder rowWithTitle:L(@"Pet sprites folder") subtitle:[self displayPath:OwnPetsDirectory()]
1391
+ controls:@[[self smallButtonWithTitle:L(@"Show in Finder") action:^{ RevealFolder(OwnPetsDirectory()); }]]],
1392
+ ] footer:nil];
1393
+ }
1394
+
1395
+ - (NSString *)displayPath:(NSString *)path {
1396
+ return path.stringByAbbreviatingWithTildeInPath;
1397
+ }
1398
+
1399
+ // rowWithTitle:subtitle: 里的说明标签,胶囊切换时要跟着改文字。
1400
+ - (NSTextField *)subtitleLabelInRow:(NSView *)row {
1401
+ NSStackView *stack = (NSStackView *)row;
1402
+ NSStackView *titles = (NSStackView *)stack.arrangedSubviews.firstObject;
1403
+ if (![titles isKindOfClass:NSStackView.class]) return nil;
1404
+ return (NSTextField *)titles.arrangedSubviews.lastObject;
1405
+ }
1406
+
1407
+ // level 是实际不透明度百分比(0–45)。
1408
+ - (void)showGlassDim:(double)level {
1409
+ [self.glassPreview applyDimLevel:level];
1410
+ }
1411
+
1412
+ @end