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
@@ -10,8 +10,16 @@ NSImage *LoadPetSpriteImage(NSString *path, NSSize cellSize, NSInteger rowCount)
10
10
  CGImageSourceCopyPropertiesAtIndex(source, 0, NULL));
11
11
  CGFloat sourceWidth = [properties[(NSString *)kCGImagePropertyPixelWidth] doubleValue];
12
12
  CGFloat sourceHeight = [properties[(NSString *)kCGImagePropertyPixelHeight] doubleValue];
13
- CGFloat desiredWidth = MAX(1.0, cellSize.width) * 8.0;
14
- CGFloat desiredHeight = MAX(1.0, cellSize.height) * rowCount;
13
+ // cellSize 是逻辑点,ImageIO 的缩略尺寸是物理像素。按 1x 解码再画入
14
+ // Retina 的 2x 帧缓存,只会放大已经丢掉细节的缩略图。
15
+ // 加载发生在窗口创建前,取所有屏幕的最高倍率,并至少保留 2x,避免
16
+ // 从普通屏移到 Retina 时源图不足。标准 Codex 精灵图因此直接保留原图。
17
+ CGFloat backingScale = 2.0;
18
+ for (NSScreen *screen in NSScreen.screens) {
19
+ backingScale = MAX(backingScale, screen.backingScaleFactor);
20
+ }
21
+ CGFloat desiredWidth = MAX(1.0, cellSize.width) * backingScale * 8.0;
22
+ CGFloat desiredHeight = MAX(1.0, cellSize.height) * backingScale * rowCount;
15
23
  CGFloat scale = MIN(1.0, MAX(desiredWidth / MAX(1.0, sourceWidth),
16
24
  desiredHeight / MAX(1.0, sourceHeight)));
17
25
  if (scale >= 0.98) {
@@ -0,0 +1,10 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ extern NSString *const CCPetsPetScaleKey;
4
+ extern const CGFloat CCPetsPetMinimumScale;
5
+ extern const CGFloat CCPetsPetMaximumScale;
6
+ CGFloat CCPetsPetScalePreference(void);
7
+ // 状态卡与消息气泡随宠物缩小,放大时最多使用原尺寸。
8
+ CGFloat CCPetsBubbleScalePreference(void);
9
+ // 按滑动条的最大尺寸预解码,连续缩放时无需重新读文件。
10
+ NSSize CCPetsPetDecodeCellSize(void);
@@ -0,0 +1,21 @@
1
+ #import "CCPetsPetSize.h"
2
+ #import <math.h>
3
+
4
+ NSString *const CCPetsPetScaleKey = @"CCPetsPetScale";
5
+ const CGFloat CCPetsPetMinimumScale = 0.5;
6
+ const CGFloat CCPetsPetMaximumScale = 2.0;
7
+
8
+ CGFloat CCPetsPetScalePreference(void) {
9
+ id value = [NSUserDefaults.standardUserDefaults objectForKey:CCPetsPetScaleKey];
10
+ if (![value isKindOfClass:NSNumber.class]) return 1.0;
11
+ double scale = [value doubleValue];
12
+ return isfinite(scale) ? MAX(CCPetsPetMinimumScale, MIN(CCPetsPetMaximumScale, scale)) : 1.0;
13
+ }
14
+
15
+ NSSize CCPetsPetDecodeCellSize(void) {
16
+ return NSMakeSize(140 * CCPetsPetMaximumScale, 150 * CCPetsPetMaximumScale);
17
+ }
18
+
19
+ CGFloat CCPetsBubbleScalePreference(void) {
20
+ return MIN(CCPetsPetScalePreference(), 1.0);
21
+ }
@@ -0,0 +1,12 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // `cc-pets pet <子命令>`:cc-pets 自己的素材仓库。
4
+ //
5
+ // 素材可以来自多个"源"(source),但一律落到 ~/.cc-pets/pets(CC_PETS_PETS_DIR 可覆盖),
6
+ // 不碰 ~/.petdex/pets 和 ~/.codex/pets——那两个目录是别的工具在写,混在一起就没法"只看自己装的宠物"。
7
+ //
8
+ // 目录名保持素材本名(boba 就是 boba),来源记在宠物目录内的 .source.json 里。这样桌宠端不需要知道
9
+ // "源"这回事,右键菜单里也不会出现 boba@petdex 这种名字;同名素材的冲突交给 --as 显式改名解决。
10
+ //
11
+ // arguments 不含 "pet" 本身。返回进程退出码。
12
+ int CCPetsPetStoreMain(NSArray<NSString *> *arguments);
@@ -0,0 +1,476 @@
1
+ #import "CCPetsL10n.h"
2
+ #import "CCPetsPetStore.h"
3
+ #import "CCPetsCLISupport.h"
4
+ #import "CCPetsJSON.h"
5
+ #import "CCPetsPaths.h"
6
+ #import "CCPetsVersion.h"
7
+
8
+ #define LF(localized, values) CCPetsInterpolate(localized, values)
9
+
10
+ static NSString *const SidecarName = @".source.json";
11
+ static const NSTimeInterval ManifestTTL = 6 * 60 * 60;
12
+
13
+ // 一个源的完整定义就是这几项。以后接自建 registry 时在这里加一项即可,命令、目录结构和桌宠端都不用动。
14
+ // 清单是远端数据,理论上可以指向任意地址;下载前把 host 卡死,免得一次清单投毒就变成"从任意地址往本地写文件"。
15
+ static NSDictionary<NSString *, NSDictionary *> *Sources(void) {
16
+ return @{
17
+ @"petdex": @{
18
+ @"label": @"PetDex",
19
+ @"manifestUrl": @"https://petdex.dev/api/manifest",
20
+ @"assetHosts": @[@"assets.petdex.dev"],
21
+ @"referer": @"https://petdex.dev/",
22
+ @"homepage": @"https://petdex.dev"
23
+ }
24
+ };
25
+ }
26
+
27
+ static NSString *DefaultSource(void) {
28
+ return CCPetsEnvironmentValue(@"CC_PETS_SOURCE") ?: @"petdex";
29
+ }
30
+
31
+ // 请求素材源时自报家门:对方运维从日志里能看出流量来自 CC Pets,想联系或限流都有个明确的对象。
32
+ static NSString *UserAgent(void) {
33
+ return [NSString stringWithFormat:@"cc-pets/%s (+https://github.com/Sunnyshinnny776/cc-pets)", CC_PETS_VERSION];
34
+ }
35
+
36
+ static NSString *Dim(NSString *text) { return [NSString stringWithFormat:@"\033[2m%@\033[0m", text]; }
37
+ static NSString *Cyan(NSString *text) { return [NSString stringWithFormat:@"\033[36m%@\033[0m", text]; }
38
+ static NSString *Green(NSString *text) { return [NSString stringWithFormat:@"\033[32m%@\033[0m", text]; }
39
+ static NSString *Red(NSString *text) { return [NSString stringWithFormat:@"\033[31m%@\033[0m", text]; }
40
+
41
+ static void Print(NSString *text) { CCPetsPrintLine(stdout, text); }
42
+ static void PrintError(NSString *text) { CCPetsPrintLine(stderr, text); }
43
+
44
+ static void Fail(NSString *message) {
45
+ PrintError(Red(message));
46
+ exit(1);
47
+ }
48
+
49
+ static NSString *PetsRoot(void) {
50
+ NSString *override = CCPetsEnvironmentValue(@"CC_PETS_PETS_DIR");
51
+ if (override) {
52
+ if ([override hasPrefix:@"~/"]) override = [CCPetsHomeDirectory() stringByAppendingPathComponent:[override substringFromIndex:2]];
53
+ return CCPetsResolvePath(override);
54
+ }
55
+ return [CCPetsHomeDirectory() stringByAppendingPathComponent:@".cc-pets/pets"];
56
+ }
57
+
58
+ // 与 CC Bridge、cc-pets clean 一致:CC_PETS_HOME 可覆盖 ~/.cc-pets。
59
+ static NSString *CachePath(NSString *sourceName) {
60
+ NSString *home = CCPetsEnvironmentValue(@"CC_PETS_HOME") ?: [CCPetsHomeDirectory() stringByAppendingPathComponent:@".cc-pets"];
61
+ return [[home stringByAppendingPathComponent:@"cache"] stringByAppendingPathComponent:
62
+ [NSString stringWithFormat:@"manifest-%@.json", sourceName]];
63
+ }
64
+
65
+ // 每个源都可以单独用环境变量改清单地址,主要给测试和自建源的本地联调用。
66
+ static NSString *ManifestURLFor(NSString *sourceName) {
67
+ return CCPetsEnvironmentValue([@"CC_PETS_MANIFEST_URL_" stringByAppendingString:sourceName.uppercaseString])
68
+ ?: Sources()[sourceName][@"manifestUrl"];
69
+ }
70
+
71
+ static BOOL Matches(NSString *pattern, NSString *text) {
72
+ if (![text isKindOfClass:NSString.class]) return NO;
73
+ NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
74
+ return [expression firstMatchInString:text options:0 range:NSMakeRange(0, text.length)] != nil;
75
+ }
76
+
77
+ // slug 直接用作目录名,而它来自远端清单,必须自己校验,不能指望上游。
78
+ static BOOL IsSafeSlug(id slug) {
79
+ return Matches(@"\\A[A-Za-z0-9][A-Za-z0-9._-]*\\z", slug) && ![slug containsString:@".."];
80
+ }
81
+
82
+ // 本地名由用户通过 --as 指定,可以用中文等 Unicode 字母。路径分隔符、空白和控制字符不在允许集内;
83
+ // 首字符必须是字母或数字,避免生成隐藏目录。
84
+ static BOOL IsSafeLocalName(id name) {
85
+ return Matches(@"\\A[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}._-]*\\z", name) && ![name containsString:@".."];
86
+ }
87
+
88
+ // "petdex:boba" -> @{source: petdex, slug: boba};不带前缀就用默认源。
89
+ static NSDictionary *ParseSpec(NSString *spec) {
90
+ NSRange separator = [spec rangeOfString:@":"];
91
+ if (separator.location == NSNotFound) return @{@"source": DefaultSource(), @"slug": spec};
92
+ NSString *source = [spec substringToIndex:separator.location];
93
+ if (!Sources()[source]) {
94
+ Fail(LF(L(@"Unknown pet source \"{source}\". Available sources: {SOURCES}"),
95
+ (@{@"source": source, @"SOURCES": [Sources().allKeys componentsJoinedByString:@", "]})));
96
+ }
97
+ return @{@"source": source, @"slug": [spec substringFromIndex:NSMaxRange(separator)]};
98
+ }
99
+
100
+ #pragma mark - 网络
101
+
102
+ // 同步请求:命令行一次只做一件事,没必要把调用方改成异步。返回数据,失败时 data 为 nil 并给出 HTTP 状态或错误。
103
+ static NSData *Fetch(NSURL *url, NSDictionary<NSString *, NSString *> *headers, NSInteger *status, NSString **error) {
104
+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
105
+ [headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
106
+ [request setValue:value forHTTPHeaderField:key];
107
+ }];
108
+ request.timeoutInterval = 60;
109
+ __block NSData *result = nil;
110
+ __block NSInteger code = 0;
111
+ __block NSString *failure = nil;
112
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
113
+ [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *taskError) {
114
+ if (taskError) {
115
+ failure = taskError.localizedDescription;
116
+ } else {
117
+ code = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 200;
118
+ result = data;
119
+ }
120
+ dispatch_semaphore_signal(done);
121
+ }] resume];
122
+ dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
123
+ if (status) *status = code;
124
+ if (error) *error = failure;
125
+ return failure ? nil : result;
126
+ }
127
+
128
+ static NSArray<NSDictionary *> *FetchManifest(NSString *sourceName, BOOL refresh) {
129
+ NSString *cache = CachePath(sourceName);
130
+ NSString *label = Sources()[sourceName][@"label"];
131
+ if (!refresh) {
132
+ NSDate *modified = [NSFileManager.defaultManager attributesOfItemAtPath:cache error:nil].fileModificationDate;
133
+ if (modified && -modified.timeIntervalSinceNow < ManifestTTL) {
134
+ NSData *data = [NSData dataWithContentsOfFile:cache];
135
+ id cached = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
136
+ if ([cached isKindOfClass:NSDictionary.class] && [cached[@"pets"] isKindOfClass:NSArray.class]) return cached[@"pets"];
137
+ }
138
+ }
139
+ NSURL *url = [NSURL URLWithString:ManifestURLFor(sourceName)];
140
+ NSInteger status = 0;
141
+ NSString *error = nil;
142
+ NSData *data = url ? Fetch(url, @{@"User-Agent": UserAgent()}, &status, &error) : nil;
143
+ if (!data && !url) error = ManifestURLFor(sourceName);
144
+ if (error || status < 200 || status >= 300) {
145
+ Fail(LF(L(@"Failed to fetch the {label} pet list: HTTP {status}"), (@{@"label": label, @"status": error ?: @(status)})));
146
+ }
147
+ id body = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
148
+ if (![body isKindOfClass:NSDictionary.class] || ![body[@"pets"] isKindOfClass:NSArray.class]) {
149
+ Fail(LF(L(@"The {label} pet list has an unexpected format"), @{@"label": label}));
150
+ }
151
+ [NSFileManager.defaultManager createDirectoryAtPath:cache.stringByDeletingLastPathComponent withIntermediateDirectories:YES attributes:nil error:nil];
152
+ [data writeToFile:cache atomically:YES];
153
+ NSMutableArray<NSDictionary *> *pets = [NSMutableArray array];
154
+ for (id pet in body[@"pets"]) {
155
+ if ([pet isKindOfClass:NSDictionary.class]) [pets addObject:pet];
156
+ }
157
+ return pets;
158
+ }
159
+
160
+ static NSData *Download(id urlValue, NSDictionary *source, NSString **error) {
161
+ NSString *text = [urlValue isKindOfClass:NSString.class] ? urlValue : @"";
162
+ NSURL *url = [NSURL URLWithString:text];
163
+ if (!url || !url.scheme) {
164
+ *error = LF(L(@"Invalid pet URL: {url}"), @{@"url": text});
165
+ return nil;
166
+ }
167
+ if (![url.scheme isEqualToString:@"https"] || ![source[@"assetHosts"] containsObject:url.host ?: @""]) {
168
+ *error = LF(L(@"Untrusted pet source: {url}"), @{@"url": url.host.length > 0 ? url.host : text});
169
+ return nil;
170
+ }
171
+ NSInteger status = 0;
172
+ NSString *failure = nil;
173
+ NSData *data = Fetch(url, @{@"Referer": source[@"referer"], @"User-Agent": UserAgent()}, &status, &failure);
174
+ if (!data || status < 200 || status >= 300) {
175
+ *error = LF(L(@"Download failed {pathname} -> HTTP {status}"), (@{@"pathname": url.path ?: @"", @"status": failure ?: @(status)}));
176
+ return nil;
177
+ }
178
+ return data;
179
+ }
180
+
181
+ #pragma mark - 本地素材
182
+
183
+ static NSDictionary *ReadSidecar(NSString *directory) {
184
+ NSData *data = [NSData dataWithContentsOfFile:[directory stringByAppendingPathComponent:SidecarName]];
185
+ id raw = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
186
+ return [raw isKindOfClass:NSDictionary.class] && [raw[@"source"] isKindOfClass:NSString.class] ? raw : nil;
187
+ }
188
+
189
+ // 已经存在的目录不能闷声覆盖:可能是另一个源的同名素材,也可能是用户自己手放的图。
190
+ static NSString *InstallBlocker(NSString *directory, NSString *sourceName, NSString *localName) {
191
+ if (![NSFileManager.defaultManager fileExistsAtPath:directory]) return nil;
192
+ NSDictionary *sidecar = ReadSidecar(directory);
193
+ if ([sidecar[@"source"] isEqual:sourceName]) return nil;
194
+ NSString *owner = sidecar ? LF(L(@"came from {source}"), @{@"source": sidecar[@"source"]})
195
+ : L(@"wasn't installed by cc-pets pet (no source record)");
196
+ return [LF(L(@"{localName} already exists and {owner}. Install it under another name: "), (@{@"localName": localName, @"owner": owner}))
197
+ stringByAppendingFormat:@"cc-pets pet add %@:%@ --as %@-%@", sourceName, localName, localName, sourceName];
198
+ }
199
+
200
+ static NSString *InstallPet(NSDictionary *pet, NSString *sourceName, NSString *localName, NSString **error) {
201
+ NSDictionary *source = Sources()[sourceName];
202
+ if (!IsSafeSlug(pet[@"slug"])) {
203
+ *error = LF(L(@"Invalid pet name: {slug}"), @{@"slug": [pet[@"slug"] description] ?: @""});
204
+ return nil;
205
+ }
206
+ NSString *directory = [PetsRoot() stringByAppendingPathComponent:localName];
207
+ NSString *blocker = InstallBlocker(directory, sourceName, localName);
208
+ if (blocker) {
209
+ *error = blocker;
210
+ return nil;
211
+ }
212
+ NSData *meta = Download(pet[@"petJsonUrl"], source, error);
213
+ if (!meta) return nil;
214
+ NSData *sprite = Download(pet[@"spritesheetUrl"], source, error);
215
+ if (!sprite) return nil;
216
+ NSString *extension = [[NSURL URLWithString:pet[@"spritesheetUrl"]].path hasSuffix:@".png"] ? @"png" : @"webp";
217
+ [NSFileManager.defaultManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
218
+ // 同一只宠物换过格式时,旧的 spritesheet 会留下来抢加载顺序,先清掉。
219
+ for (NSString *stale in @[@"spritesheet.webp", @"spritesheet.png"]) {
220
+ if (![stale isEqualToString:[@"spritesheet." stringByAppendingString:extension]]) {
221
+ [NSFileManager.defaultManager removeItemAtPath:[directory stringByAppendingPathComponent:stale] error:nil];
222
+ }
223
+ }
224
+ // pet.json 原样落盘,不掺自己的字段——保持上游原始内容,以后比对和更新才干净。
225
+ [meta writeToFile:[directory stringByAppendingPathComponent:@"pet.json"] atomically:YES];
226
+ [sprite writeToFile:[directory stringByAppendingPathComponent:[@"spritesheet." stringByAppendingString:extension]] atomically:YES];
227
+ CCPetsJSONObject *sidecar = [CCPetsJSONObject new];
228
+ sidecar[@"source"] = sourceName;
229
+ sidecar[@"slug"] = pet[@"slug"];
230
+ NSISO8601DateFormatter *formatter = [NSISO8601DateFormatter new];
231
+ formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime | NSISO8601DateFormatWithFractionalSeconds;
232
+ sidecar[@"installedAt"] = [formatter stringFromDate:NSDate.date];
233
+ [[CCPetsJSONStringify(sidecar) stringByAppendingString:@"\n"] writeToFile:[directory stringByAppendingPathComponent:SidecarName]
234
+ atomically:YES encoding:NSUTF8StringEncoding error:nil];
235
+ return directory;
236
+ }
237
+
238
+ static NSArray<NSDictionary *> *InstalledPets(void) {
239
+ NSString *root = PetsRoot();
240
+ NSMutableArray<NSDictionary *> *pets = [NSMutableArray array];
241
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:root error:nil]) {
242
+ if ([name hasPrefix:@"."]) continue;
243
+ if (!CCPetsDirectoryExists([root stringByAppendingPathComponent:name])) continue;
244
+ NSDictionary *sidecar = ReadSidecar([root stringByAppendingPathComponent:name]);
245
+ [pets addObject:@{@"name": name, @"source": sidecar[@"source"] ?: NSNull.null,
246
+ @"slug": [sidecar[@"slug"] isKindOfClass:NSString.class] ? sidecar[@"slug"] : NSNull.null}];
247
+ }
248
+ [pets sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
249
+ return [a[@"name"] localizedCompare:b[@"name"]];
250
+ }];
251
+ return pets;
252
+ }
253
+
254
+ #pragma mark - 命令
255
+
256
+ static NSArray<NSString *> *Positional(NSArray<NSString *> *arguments, NSInteger skipIndex) {
257
+ NSMutableArray<NSString *> *values = [NSMutableArray array];
258
+ [arguments enumerateObjectsUsingBlock:^(NSString *value, NSUInteger index, BOOL *stop) {
259
+ if (![value hasPrefix:@"--"] && (NSInteger)index != skipIndex) [values addObject:value];
260
+ }];
261
+ return values;
262
+ }
263
+
264
+ static int CommandAdd(NSArray<NSString *> *arguments) {
265
+ BOOL refresh = [arguments containsObject:@"--refresh"];
266
+ NSUInteger asIndex = [arguments indexOfObject:@"--as"];
267
+ NSString *alias = asIndex != NSNotFound && asIndex + 1 < arguments.count ? arguments[asIndex + 1] : nil;
268
+ if (asIndex != NSNotFound && (!alias || [alias hasPrefix:@"--"])) Fail(L(@"--as needs a name after it."));
269
+ if (alias && !IsSafeLocalName(alias)) Fail(LF(L(@"Invalid --as name: {alias}"), @{@"alias": alias}));
270
+ NSOrderedSet<NSString *> *specs = [NSOrderedSet orderedSetWithArray:Positional(arguments, asIndex == NSNotFound ? -1 : (NSInteger)asIndex + 1)];
271
+ if (specs.count == 0) {
272
+ Fail(LF(L(@"Usage: {cyan}"), @{@"cyan": Cyan(L(@"cc-pets pet add [source:]<name> [name...] [--as <local-name>]"))}));
273
+ }
274
+ if (alias && specs.count > 1) Fail(L(@"--as can only rename one pet at a time."));
275
+
276
+ // 按源分组,同一个源只拉一次清单。
277
+ NSMutableArray<NSString *> *sourceOrder = [NSMutableArray array];
278
+ NSMutableDictionary<NSString *, NSMutableArray<NSString *> *> *bySource = [NSMutableDictionary dictionary];
279
+ for (NSString *spec in specs) {
280
+ NSDictionary *item = ParseSpec(spec);
281
+ if (!bySource[item[@"source"]]) {
282
+ bySource[item[@"source"]] = [NSMutableArray array];
283
+ [sourceOrder addObject:item[@"source"]];
284
+ }
285
+ [bySource[item[@"source"]] addObject:item[@"slug"]];
286
+ }
287
+ NSUInteger failed = 0, installed = 0;
288
+ for (NSString *sourceName in sourceOrder) {
289
+ NSMutableDictionary<NSString *, NSDictionary *> *index = [NSMutableDictionary dictionary];
290
+ for (NSDictionary *pet in FetchManifest(sourceName, refresh)) {
291
+ if ([pet[@"slug"] isKindOfClass:NSString.class]) index[pet[@"slug"]] = pet;
292
+ }
293
+ for (NSString *slug in bySource[sourceName]) {
294
+ NSDictionary *pet = index[slug];
295
+ if (!pet) {
296
+ failed++;
297
+ PrintError(LF(L(@"{red} {sourceName}:{slug}: not in the pet list"), (@{@"red": Red(@"×"), @"sourceName": sourceName, @"slug": slug})));
298
+ continue;
299
+ }
300
+ NSString *localName = alias ?: slug;
301
+ NSString *error = nil;
302
+ NSString *directory = InstallPet(pet, sourceName, localName, &error);
303
+ if (!directory) {
304
+ failed++;
305
+ PrintError([NSString stringWithFormat:@"%@ %@:%@: %@", Red(@"×"), sourceName, slug, error]);
306
+ continue;
307
+ }
308
+ installed++;
309
+ NSString *renamed = [localName isEqualToString:slug] ? @"" : Dim([NSString stringWithFormat:@" (%@:%@)", sourceName, slug]);
310
+ Print([NSString stringWithFormat:@"%@ %@%@ %@", Green(@"✓"), localName, renamed, Dim([@"→ " stringByAppendingString:directory])]);
311
+ }
312
+ }
313
+ if (installed > 0) {
314
+ Print(Dim(LF(L(@"Pets directory: {petsRoot}"), @{@"petsRoot": PetsRoot()})));
315
+ Print(Dim(L(@"Click “Rescan” in the pet menu or restart the pet to see new pets.")));
316
+ }
317
+ return failed > 0 ? 1 : 0;
318
+ }
319
+
320
+ static int CommandSearch(NSArray<NSString *> *arguments) {
321
+ BOOL refresh = [arguments containsObject:@"--refresh"];
322
+ NSArray<NSString *> *positional = Positional(arguments, -1);
323
+ // 关键词本身也可以带源前缀:`cc-pets pet search petdex:otter`。
324
+ NSDictionary *scoped = positional.count > 0 && [positional[0] containsString:@":"] ? ParseSpec(positional[0])
325
+ : @{@"source": DefaultSource(), @"slug": [positional componentsJoinedByString:@" "]};
326
+ NSString *sourceName = scoped[@"source"];
327
+ NSMutableArray<NSString *> *words = [NSMutableArray arrayWithObject:scoped[@"slug"]];
328
+ if (positional.count > 1) [words addObjectsFromArray:[positional subarrayWithRange:NSMakeRange(1, positional.count - 1)]];
329
+ NSString *keyword = [[words componentsJoinedByString:@" "]
330
+ stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].lowercaseString;
331
+ NSArray<NSDictionary *> *pets = FetchManifest(sourceName, refresh);
332
+ NSMutableArray<NSDictionary *> *matched = [NSMutableArray array];
333
+ for (NSDictionary *pet in pets) {
334
+ NSString *haystack = [NSString stringWithFormat:@"%@ %@ %@", pet[@"slug"] ?: @"",
335
+ [pet[@"displayName"] isKindOfClass:NSString.class] ? pet[@"displayName"] : @"",
336
+ [pet[@"submittedBy"] isKindOfClass:NSString.class] ? pet[@"submittedBy"] : @""].lowercaseString;
337
+ if (keyword.length == 0 || [haystack containsString:keyword]) [matched addObject:pet];
338
+ }
339
+ if (matched.count == 0) {
340
+ Fail(LF(L(@"No pets on {label} match \"{keyword}\"."), (@{@"label": Sources()[sourceName][@"label"], @"keyword": keyword})));
341
+ }
342
+ NSArray<NSDictionary *> *shown = matched.count > 60 ? [matched subarrayWithRange:NSMakeRange(0, 60)] : matched;
343
+ for (NSDictionary *pet in shown) {
344
+ NSString *author = [pet[@"submittedBy"] isKindOfClass:NSString.class] && [pet[@"submittedBy"] length] > 0
345
+ ? Dim([@" by " stringByAppendingString:pet[@"submittedBy"]]) : @"";
346
+ NSString *display = [pet[@"displayName"] isKindOfClass:NSString.class] ? pet[@"displayName"] : @"";
347
+ Print([NSString stringWithFormat:@" %@ %@%@", Cyan([pet[@"slug"] description]), display, author]);
348
+ }
349
+ if (matched.count > shown.count) {
350
+ Print(Dim(LF(L(@" … {length} results, showing the first {shown}."), (@{@"length": @(matched.count), @"shown": @(shown.count)}))));
351
+ }
352
+ Print(Dim(LF(L(@"Install one: cc-pets pet add {sourceName}:{slug}"), (@{@"sourceName": sourceName, @"slug": [shown[0][@"slug"] description]}))));
353
+ return 0;
354
+ }
355
+
356
+ static int CommandList(void) {
357
+ NSArray<NSDictionary *> *pets = InstalledPets();
358
+ if (pets.count == 0) {
359
+ Print(Dim(LF(L(@"No pets in {petsRoot} yet."), @{@"petsRoot": PetsRoot()})));
360
+ Print(Dim(L(@"Try: cc-pets pet add boba")));
361
+ return 0;
362
+ }
363
+ NSMutableDictionary<NSString *, NSMutableArray<NSDictionary *> *> *groups = [NSMutableDictionary dictionary];
364
+ for (NSDictionary *pet in pets) {
365
+ NSString *key = pet[@"source"] == NSNull.null ? @"" : pet[@"source"];
366
+ if (!groups[key]) groups[key] = [NSMutableArray array];
367
+ [groups[key] addObject:pet];
368
+ }
369
+ // 有来源记录的源按名字排在前面,手放的素材垫底。
370
+ NSArray<NSString *> *keys = [groups.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *a, NSString *b) {
371
+ if (a.length == 0) return NSOrderedDescending;
372
+ if (b.length == 0) return NSOrderedAscending;
373
+ return [a localizedCompare:b];
374
+ }];
375
+ // 不能 add、只会出现在已装素材里的来源。桌宠的"导入 Codex 素材"开关会写 source: "codex"。
376
+ NSDictionary<NSString *, NSString *> *localLabels = @{@"codex": L(@"Codex (imported)")};
377
+ for (NSString *key in keys) {
378
+ NSString *label = key.length == 0 ? L(@"Local pets (no source record)") : (Sources()[key][@"label"] ?: localLabels[key] ?: key);
379
+ Print([@" " stringByAppendingString:label]);
380
+ for (NSDictionary *pet in groups[key]) {
381
+ // 目录名和上游 slug 不一致时(--as 改过名)把原名标出来。
382
+ NSString *slug = pet[@"slug"] == NSNull.null ? nil : pet[@"slug"];
383
+ NSString *origin = slug && ![slug isEqualToString:pet[@"name"]] ? Dim([NSString stringWithFormat:@" (%@:%@)", key, slug]) : @"";
384
+ Print([NSString stringWithFormat:@" %@%@", Cyan(pet[@"name"]), origin]);
385
+ }
386
+ }
387
+ Print(Dim(LF(L(@"{length} in total, in {petsRoot}"), (@{@"length": @(pets.count), @"petsRoot": PetsRoot()}))));
388
+ return 0;
389
+ }
390
+
391
+ static int CommandRemove(NSArray<NSString *> *arguments) {
392
+ NSArray<NSString *> *names = Positional(arguments, -1);
393
+ if (names.count == 0) Fail(LF(L(@"Usage: {cyan}"), @{@"cyan": Cyan(L(@"cc-pets pet remove <name> [name...]"))}));
394
+ NSUInteger removed = 0;
395
+ for (NSString *name in names) {
396
+ if (!IsSafeLocalName(name)) {
397
+ PrintError(LF(L(@"{red} {name}: invalid name"), (@{@"red": Red(@"×"), @"name": name})));
398
+ continue;
399
+ }
400
+ NSString *directory = [PetsRoot() stringByAppendingPathComponent:name];
401
+ if (![NSFileManager.defaultManager fileExistsAtPath:directory]) {
402
+ PrintError(LF(L(@"{red} {name}: not installed"), (@{@"red": Red(@"×"), @"name": name})));
403
+ continue;
404
+ }
405
+ NSDictionary *sidecar = ReadSidecar(directory);
406
+ [NSFileManager.defaultManager removeItemAtPath:directory error:nil];
407
+ removed++;
408
+ Print(LF(L(@"{green} Removed {name}{source}"), (@{@"green": Green(@"✓"), @"name": name,
409
+ @"source": sidecar ? Dim(LF(L(@" (from {source})"), @{@"source": sidecar[@"source"]})) : @""})));
410
+ }
411
+ return removed < names.count ? 1 : 0;
412
+ }
413
+
414
+ static int CommandSource(void) {
415
+ for (NSString *name in [Sources().allKeys sortedArrayUsingSelector:@selector(compare:)]) {
416
+ NSDictionary *source = Sources()[name];
417
+ NSString *marker = [name isEqualToString:DefaultSource()] ? Green(L(@" (default)")) : @"";
418
+ Print([NSString stringWithFormat:@" %@%@ %@ %@", Cyan(name), marker, source[@"label"], Dim(source[@"homepage"])]);
419
+ }
420
+ Print(Dim(L(@"Change the default source with CC_PETS_SOURCE, or prefix a name with `source:`.")));
421
+ return 0;
422
+ }
423
+
424
+ static int CommandDir(void) {
425
+ [NSFileManager.defaultManager createDirectoryAtPath:PetsRoot() withIntermediateDirectories:YES attributes:nil error:nil];
426
+ Print(PetsRoot());
427
+ return 0;
428
+ }
429
+
430
+ static void Usage(void) {
431
+ Print([@[
432
+ @"",
433
+ LF(L(@" {cyan} — install pets into cc-pets' own directory"), @{@"cyan": Cyan(@"cc-pets pet")}),
434
+ @"",
435
+ LF(L(@" {cyan} [source:]<name>... download pets to {petsRoot}"), (@{@"cyan": Cyan(@"add"), @"petsRoot": Dim(PetsRoot())})),
436
+ LF(L(@" {cyan} [source:][keyword] search pets (no keyword lists all)"), @{@"cyan": Cyan(@"search")}),
437
+ LF(L(@" {cyan} list installed pets, grouped by source"), @{@"cyan": Cyan(@"list")}),
438
+ LF(L(@" {cyan} <name>... remove installed pets"), @{@"cyan": Cyan(@"remove")}),
439
+ LF(L(@" {cyan} list available sources"), @{@"cyan": Cyan(@"source")}),
440
+ LF(L(@" {cyan} print the pets directory"), @{@"cyan": Cyan(@"dir")}),
441
+ @"",
442
+ [@" " stringByAppendingString:Dim([NSString stringWithFormat:@"%@%@%@",
443
+ L(@"Names can have a source prefix (petdex:boba); otherwise the default source is used: "), DefaultSource(), L(@".")])],
444
+ [@" " stringByAppendingString:Dim(L(@"--as <local-name> installs under another directory name (any language) to avoid name clashes."))],
445
+ [@" " stringByAppendingString:Dim(L(@"--refresh forces a refresh of the pet list cache (cached for 6 hours by default)."))],
446
+ [@" " stringByAppendingString:Dim(L(@"CC_PETS_PETS_DIR changes the pets directory; CC_PETS_SOURCE changes the default source."))],
447
+ @"",
448
+ [NSString stringWithFormat:@" %@ cc-pets pet search otter", Dim(@"$")],
449
+ [NSString stringWithFormat:@" %@ cc-pets pet add boba", Dim(@"$")],
450
+ [NSString stringWithFormat:@" %@ cc-pets pet add petdex:boba --as boba-petdex", Dim(@"$")],
451
+ LF(L(@" {dim} cc-pets pet add boba --as bubble-tea"), @{@"dim": Dim(@"$")}),
452
+ @""
453
+ ] componentsJoinedByString:@"\n"]);
454
+ }
455
+
456
+ int CCPetsPetStoreMain(NSArray<NSString *> *argv) {
457
+ NSString *command = argv.firstObject;
458
+ NSArray<NSString *> *arguments = argv.count > 1 ? [argv subarrayWithRange:NSMakeRange(1, argv.count - 1)] : @[];
459
+ if (!Sources()[DefaultSource()]) {
460
+ Fail(LF(L(@"CC_PETS_SOURCE points to an unknown source \"{DEFAULT_SOURCE}\". Available sources: {SOURCES}"),
461
+ (@{@"DEFAULT_SOURCE": DefaultSource(), @"SOURCES": [Sources().allKeys componentsJoinedByString:@", "]})));
462
+ }
463
+ if ([@[@"add", @"install"] containsObject:command ?: @""]) return CommandAdd(arguments);
464
+ if ([command isEqualToString:@"search"]) return CommandSearch(arguments);
465
+ if ([@[@"list", @"ls"] containsObject:command ?: @""]) return CommandList();
466
+ if ([@[@"remove", @"rm"] containsObject:command ?: @""]) return CommandRemove(arguments);
467
+ if ([@[@"source", @"sources"] containsObject:command ?: @""]) return CommandSource();
468
+ if ([command isEqualToString:@"dir"]) return CommandDir();
469
+ if (!command || [@[@"help", @"--help", @"-h"] containsObject:command]) {
470
+ Usage();
471
+ return 0;
472
+ }
473
+ PrintError(Red(LF(L(@"Unknown subcommand: {command}"), @{@"command": command})));
474
+ Usage();
475
+ return 2;
476
+ }
@@ -63,15 +63,31 @@ NSString *PetPhrasesFilePath(void);
63
63
  //
64
64
  // 专属目录:~/.cc-pets/speech/。可用 CC_PETS_PHRASES_PET_DIR 覆盖(测试用)。
65
65
  NSString *PetPhrasesPetDirectory(void);
66
- // petID(builtin:默认.webp / external:哆啦A梦)转成文件名用的 key。
66
+ // petID(builtin:ByteMochi.webp / external:团子)转成文件名用的 key。
67
67
  //
68
68
  // petID 里的冒号、素材名里的斜杠都不能直接进文件名,内置素材的 .webp 后缀留着也只是
69
- // 噪音,所以统一规整成 builtin-默认 / external-哆啦A梦。中文原样保留——用户要能在
69
+ // 噪音,所以统一规整成 builtin-ByteMochi / external-团子。中文原样保留——用户要能在
70
70
  // Finder 里一眼认出哪份是哪只的,转义成百分号编码就白瞎了。
71
71
  NSString *PetPhrasesKeyForPetID(NSString *petID);
72
72
  // 某只宠物的专属词库路径。petID 为空返回 nil。
73
73
  NSString *PetPhrasesFilePathForPetID(NSString *petID);
74
74
 
75
+ // 选中宠物的偏好键。值是 petID;很早的版本存的是不带 builtin: 前缀的内置文件名。
76
+ extern NSString *const PetSelectedSpriteKey;
77
+ // 内置素材从 默认.webp 改名为 ByteMochi.webp(2.2.1 之后)。petID 由文件名派生,改名后旧 ID 找不到,
78
+ // 选了内置宠物的用户会被退回到列表第一只(外部素材排在前面),为它写的专属台词也不再生效。
79
+ // 启动时调用一次:把选中的宠物改成新 ID;旧的专属台词文件改名过去,新文件已存在时不覆盖。
80
+ // 幂等,没有旧状态时什么都不做。
81
+ void PetMigrateRenamedBuiltinSprite(NSUserDefaults *defaults);
82
+
83
+ // 全局台词来源偏好,切换宠物和重启后仍保留。未设置时保持原来的专属优先行为。
84
+ // 专属模式按小节回落到通用词库;默认模式只读通用词库,不改写任何台词文件。
85
+ extern NSString *const PetPhrasesSourceKey;
86
+ extern NSString *const PetPhrasesSourcePet;
87
+ extern NSString *const PetPhrasesSourceDefault;
88
+ NSString *PetPhrasesSource(void);
89
+ void PetPhrasesSetSource(NSString *source);
90
+
75
91
  // 当前是哪只宠物。取词层本来是纯函数,这里是唯一的外部状态——桌宠启动和每次切换
76
92
  // 宠物时由 AppDelegate 推进来。做成 setter 而不是让 PetPhraseForTag 多带一个参数:
77
93
  // 说话的调用点散在十几处,每处都传一遍 petID 只会让人漏传,而漏传的表现是"专属台词