cc-pets 2.2.1 → 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 (171) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +60 -0
  4. package/CHANGELOG.zh-CN.md +60 -0
  5. package/CONTRIBUTING.md +13 -10
  6. package/CONTRIBUTING.zh-CN.md +11 -10
  7. package/README.md +113 -24
  8. package/README.zh-CN.md +89 -28
  9. package/Resources/zh-Hans.lproj/Localizable.strings +568 -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} +82 -23
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +17 -3
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +70 -22
  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/{CCPetsAppDelegate+Settings.m → App/CCPetsAppDelegate+Settings.m} +86 -98
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +8 -4
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  20. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +15 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +107 -11
  22. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  23. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  24. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  25. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  26. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  27. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  35. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  37. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  38. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  39. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  41. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  43. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  44. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  45. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  46. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +11 -2
  47. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +19 -2
  48. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +4 -1
  49. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  50. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  51. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  52. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  53. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  54. package/Sources/CCPets/Pet/PetView.m +635 -0
  55. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  56. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  57. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  58. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  59. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  60. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  61. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  62. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  63. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  64. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  65. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  66. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  67. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  68. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  69. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  70. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  71. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  72. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  73. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  74. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  75. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  76. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  77. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  78. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  79. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  80. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  81. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  82. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  83. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  84. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  85. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  86. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  87. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  88. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  89. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  90. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  91. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  92. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  93. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  94. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  95. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  96. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  97. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  98. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  99. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  100. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  101. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  102. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  103. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  104. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  105. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  106. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  107. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  108. package/THIRD_PARTY_NOTICES.md +1 -1
  109. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  110. package/bin/cc-pets +8 -6
  111. package/bin/claude-with-pet +10 -2
  112. package/bin/codex-with-pet +13 -5
  113. package/package.json +1 -1
  114. package/scripts/build.sh +7 -3
  115. package/scripts/i18n.zsh +9 -52
  116. package/scripts/install-app.sh +4 -0
  117. package/scripts/install-shell-integration.sh +17 -10
  118. package/scripts/uninstall-shell-integration.sh +6 -1
  119. package/Sources/CCPets/CCPetsEvents.h +0 -10
  120. package/Sources/CCPets/CCPetsUsage.h +0 -36
  121. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  122. package/Sources/CCPets/PetView.m +0 -1839
  123. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  124. package/scripts/bridge/cli.mjs +0 -237
  125. package/scripts/bridge/core.mjs +0 -228
  126. package/scripts/bridge/hook.mjs +0 -150
  127. package/scripts/bridge/install.mjs +0 -311
  128. package/scripts/bridge/mcp-server.mjs +0 -308
  129. package/scripts/bridge/options.mjs +0 -87
  130. package/scripts/bridge/process.mjs +0 -151
  131. package/scripts/bridge/reservations.mjs +0 -248
  132. package/scripts/bridge/store.mjs +0 -433
  133. package/scripts/bridge/watch.mjs +0 -69
  134. package/scripts/check-l10n.mjs +0 -168
  135. package/scripts/configure-updater.mjs +0 -43
  136. package/scripts/detect-cli.mjs +0 -68
  137. package/scripts/doctor.mjs +0 -470
  138. package/scripts/i18n.mjs +0 -122
  139. package/scripts/install-claude-hooks.mjs +0 -253
  140. package/scripts/install-codex-hooks.mjs +0 -78
  141. package/scripts/integration-markers.mjs +0 -51
  142. package/scripts/locales/zh-Hans.json +0 -366
  143. package/scripts/pet-store.mjs +0 -415
  144. package/scripts/uninstall-integrations.mjs +0 -205
  145. /package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +0 -0
  146. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  147. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  148. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  149. /package/Sources/CCPets/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
  150. /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
  151. /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
  152. /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
  153. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  154. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  155. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  156. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  157. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  159. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  161. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  162. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  163. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  164. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  165. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  166. /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
  167. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  168. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  169. /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
  170. /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
  171. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -1,1839 +0,0 @@
1
- #import "PetView.h"
2
- #import "CCPetsL10n.h"
3
- #import <QuartzCore/QuartzCore.h>
4
- #import "MenuToggleSwitch.h"
5
- #import "MenuHintView.h"
6
- #import "CCPetsPaths.h"
7
- #import "CCPetsImageLoader.h"
8
- #import "CCPetsBridge.h"
9
- #import "CCPetsGlassView.h"
10
- #import "MenuChoiceRow.h"
11
- #import "MenuPetSizeView.h"
12
- #import "CCPetsPetSize.h"
13
- #import "CCPetsPhrases.h"
14
-
15
- // 碎碎念频率档位的 defaults 键。定义在 CCPetsAppDelegate+Speech.m,这里只读不写;
16
- // 单独 extern 而不 import 那个头文件,是因为它反过来 import 了 PetView.h。
17
- extern NSString *const PetSpeechFrequencyKey;
18
-
19
- NSString *const PetInteractionEnabledKey = @"CCPetsInteractionEnabled";
20
- NSString *const PetInteractionHeartThresholdKey = @"CCPetsInteractionHeartThreshold";
21
- NSString *const PetInteractionAnnoyedThresholdKey = @"CCPetsInteractionAnnoyedThreshold";
22
- NSString *const PetInteractionIntervalKey = @"CCPetsInteractionInterval";
23
-
24
- // 按下后位移超过这个距离才判定为拖动,之内视为点击。
25
- static const CGFloat PetDragThreshold = 3.0;
26
- // 菜单里自绘行的宽度:主菜单要撑满 menu.minimumWidth,子菜单按自身内容收窄,
27
- // 三个子菜单(用量展示模式 / 系统通知 / 系统状态)用同一个宽度,看起来才是一套。
28
- static const CGFloat PetMenuRowWidth = 194.0;
29
- // 两者都只是下限:译文长短差得多("等待审批" 对 "Awaiting approval"),开关行会按自己的
30
- // 标题撑宽,菜单再把同一子菜单里的行统一拉到最宽那一行。
31
- static const CGFloat PetSubmenuRowWidth = 134.0;
32
- // 与“系统通知”里文案到开关的间距共用,素材名称到删除按钮也保持一致。
33
- static const CGFloat PetMenuControlGap = 8.0;
34
- static const NSInteger PetMenuCheckViewTag = 1001;
35
- static const NSInteger PetMenuDeleteButtonTag = 1002;
36
- // 呼吸:只向上浮,不做上下对称摆动。宠物视图在 230×170 的窗口里位于 (43,0,144,150),
37
- // 下方一点余量都没有,往下 1px 就被窗口裁掉。静止位不变,所以离屏基准图不受影响。
38
- static const CGFloat PetBreathRise = 1.5;
39
- static const NSTimeInterval PetBreathPeriod = 3.6;
40
- // 拖动滞后只做水平方向。窗口左右各有 43px 余量,而下方是 0——垂直滞后往下一点就被裁掉,
41
- // 只留向上会变成不对称的怪动作,不如不做。反正拖动本来就按水平方向选跑动行,
42
- // 水平滞后正好强化那个方向感。
43
- static const CGFloat PetDragLagMax = 13.0;
44
- static const CGFloat PetDragLagFactor = 0.85;
45
- // 松手后的"落脚":先压扁再回弹到静止。锚点在脚底,所以压扁是往下坐,不会越界。
46
- static const NSTimeInterval PetSettleDuration = 0.34;
47
- // 微动层:待机时每隔一段随机时间做一个有始有终的小动作。间隔必须随机——固定周期
48
- // 会被下意识数出拍子,一旦数出来就全毁了。
49
- static const NSTimeInterval PetMicroIntervalMin = 8.0;
50
- static const NSTimeInterval PetMicroIntervalMax = 25.0;
51
- // 无聊曲线的三个拐点(秒)。闲久了先躁动、再倦、最后几乎不动,是条先升后降的曲线。
52
- static const NSTimeInterval PetBoredomRestless = 120.0;
53
- static const NSTimeInterval PetBoredomTired = 600.0;
54
- static const NSTimeInterval PetBoredomDrowsy = 1800.0;
55
- // 十六向朝向定格保持多久(秒)。这是素材本来就设计成静止的格子,定格不违和。
56
- static const NSTimeInterval PetGlanceHoldMin = 0.7;
57
- static const NSTimeInterval PetGlanceHoldMax = 1.6;
58
- // 生理余韵:agent 干完活之后呼吸会快一阵,再用几十秒平复回基线。
59
- // 事件结束不等于状态归零——这种跨状态的连续性是免费的活物感。
60
- static const double PetExertionPerEvent = 0.15;
61
- static const NSTimeInterval PetExertionHalfLife = 25.0;
62
- // 上次交互时间落盘的键。重启后接着算无聊曲线,隔了几小时再开就是从"打盹"开始,
63
- // 而不是每次启动都精神抖擞。
64
- static NSString *const PetLastActivityKey = @"CCPetsLastActivityAt";
65
- static const NSTimeInterval PetActivitySaveInterval = 60.0;
66
-
67
- // 微动的种类。加新动作就往这里加一项、再往 microBehaviorTable 里登记一行,
68
- // 调度器不用改。
69
- typedef NS_ENUM(NSInteger, PetMicroBehaviorKind) {
70
- PetMicroBehaviorGlance, // 逐格转头看鼠标,需要十六向朝向行
71
- PetMicroBehaviorScan, // row 3 张望,任何素材都有
72
- };
73
-
74
- @interface PetView ()
75
- @property(weak) NSMenu *activePetSwitchMenu;
76
- @property(copy) NSString *pendingDeletePetID;
77
- // 素材能力:由行数在 applySheet: 时一次算出,之后全程只读这个,不再各处判行数。
78
- //
79
- // 散在各处写 rowCount == 11 的话,每加一个行为就多一处分支,测试翻倍且迟早漂移。
80
- // 收成能力位之后,差异降级成"微动表里哪几行可用"这一个数据问题,调度器根本
81
- // 不知道有分档这回事。
82
- @property BOOL hasLookRows;
83
- // 按能力过滤后的可用微动表,每项 @{kind, weight}。
84
- @property NSArray<NSDictionary *> *microBehaviorTable;
85
- // 精灵内容单独挂一层:呼吸、弹簧、落地 squash 都要对这一层做 CA 动画,放在视图自己的
86
- // layer 上会连带影响命中测试和子视图几何。
87
- @property CALayer *spriteLayer;
88
- @property NSSize spriteCacheSize;
89
- // 当前帧已经停了几拍,够 frameHolds 里那个数才推进。
90
- @property NSUInteger holdTicks;
91
- // 待机当前的速度档(拍/帧)。行为已关,字段留给微动层的慢放用。
92
- @property NSUInteger idleHold;
93
- // 微动层:独立于 oneShot 的一套标志。
94
- //
95
- // 绝对不能复用 oneShot——它在 nextFrame: 里播完会连带把 agentActive 清成 NO
96
- // (见那一处注释)。微动是待机期间的自发动作,跟 agent 状态毫无关系,借它的壳会把
97
- // "agent 正在干活"这个状态误清掉。
98
- @property BOOL microActive;
99
- // 下一次换图走一次短淡入淡出。进出微动那一下是硬切,加这一下过渡就不突兀了。
100
- @property BOOL fadeNextContents;
101
- @property NSInteger microCountdown;
102
- // 最后一次"有事发生"的时间:agent 事件、鼠标交互、拖动都算。无聊曲线按它算。
103
- //
104
- // 不要改用 agentActive 判断闲了多久:mouseDown: 会无条件把它清成 NO,不管 agent
105
- // 是不是还在跑,用户随手点一下宠物就会让无聊曲线误启动。
106
- @property NSTimeInterval lastActivityTime;
107
- // 注意力:真正在看的方向、以及这次注意力还能维持多久。
108
- @property NSTimeInterval attentionUntil;
109
- @property NSTimeInterval attentionCooldownUntil;
110
- // 生理余韵:用力程度(0~1,按半衰期衰减)、上次更新时刻、当前呼吸档位。
111
- @property double exertion;
112
- @property NSTimeInterval exertionUpdatedAt;
113
- @property NSInteger breathLevel;
114
- @property NSTimeInterval lastActivitySavedAt;
115
- // 拖动期间记上一次窗口位置,用来算这一帧走了多远。窗口服务器接管拖动后不给应用连续
116
- // 事件,但 NSWindowDidMoveNotification 照发,这是拖动中唯一拿得到的位移信号。
117
- @property NSPoint lastDragWindowOrigin;
118
- @property BOOL observingWindowMove;
119
- // 连击只统计没有变成拖动的左键释放。
120
- @property NSInteger interactionClickCount;
121
- @property NSTimeInterval lastInteractionClickAt;
122
- // 按格栅格化的位图。视网膜下每格 280×300×4 ≈ 328KB,整表 88 格会到 28MB,
123
- // 所以设 cost 上限让它只留住真正在播的那些格。
124
- @property NSCache<NSNumber *, id> *cellCache;
125
- @end
126
-
127
- @implementation PetView
128
- - (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount {
129
- if ((self = [super initWithFrame:frame])) {
130
- _sheet = sheet;
131
- _spriteRowCount = rowCount;
132
- _lookDirection = -1;
133
- _frames = @[@0, @1, @2, @3, @4, @5];
134
- _frameHolds = @[@1, @1, @1, @1, @1, @1];
135
- _petMenuPreviewCache = [NSCache new];
136
- _petMenuPreviewCache.countLimit = 24;
137
- _petMenuPreviewCache.totalCostLimit = 4 * 1024 * 1024;
138
- _cellCache = [NSCache new];
139
- _cellCache.totalCostLimit = 6 * 1024 * 1024;
140
- self.wantsLayer = YES;
141
- _spriteLayer = [CALayer layer];
142
- // 像素素材放大必须用最近邻,等价于原来 drawRect: 里的 NSImageInterpolationNone。
143
- _spriteLayer.magnificationFilter = kCAFilterNearest;
144
- _spriteLayer.minificationFilter = kCAFilterNearest;
145
- // contentsScale 由 rebuildSpriteCache 按 backingScaleFactor 定,这里不预设。
146
- // 锚点放在脚底:呼吸和之后的落地 squash 都该以脚为支点,锚在正中会变成
147
- // "整体缩放",看着像忽远忽近而不是有重量。
148
- _spriteLayer.anchorPoint = CGPointMake(0.5, 0.0);
149
- [self.layer addSublayer:_spriteLayer];
150
- [self layoutSpriteLayer];
151
- [self rebuildSpriteCache];
152
- [NSNotificationCenter.defaultCenter addObserver:self
153
- selector:@selector(powerStateDidChange:)
154
- name:NSProcessInfoPowerStateDidChangeNotification object:nil];
155
- [NSWorkspace.sharedWorkspace.notificationCenter addObserver:self
156
- selector:@selector(powerStateDidChange:)
157
- name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
158
- [self updatePowerPreferences];
159
- [self updateFrameTimer];
160
- NSTrackingArea *tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect
161
- options:NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
162
- NSTrackingActiveAlways | NSTrackingInVisibleRect
163
- owner:self userInfo:nil];
164
- [self addTrackingArea:tracking];
165
- [self rebuildCapabilities];
166
- [self updateLookTracking];
167
- }
168
- return self;
169
- }
170
- // 只碰 ivar,不走属性 setter:setter 会调用 updateFrameTimer,在 dealloc 期间
171
- // 重新排一个定时器出来。
172
- - (void)dealloc {
173
- [_frameTimer invalidate];
174
- if (_globalMouseMonitor) [NSEvent removeMonitor:_globalMouseMonitor];
175
- if (_localMouseMonitor) [NSEvent removeMonitor:_localMouseMonitor];
176
- [NSNotificationCenter.defaultCenter removeObserver:self];
177
- [NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self];
178
- }
179
- - (void)powerStateDidChange:(NSNotification *)notification {
180
- [self updatePowerPreferences];
181
- }
182
- - (void)updatePowerPreferences {
183
- BOOL lowPower = NSProcessInfo.processInfo.lowPowerModeEnabled;
184
- BOOL reduceMotion = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion;
185
- if (self.lowPowerMode == lowPower && self.reduceMotion == reduceMotion) return;
186
- self.lowPowerMode = lowPower;
187
- self.reduceMotion = reduceMotion;
188
- [self.frameTimer invalidate];
189
- self.frameTimer = nil;
190
- [self updateFrameTimer];
191
- [self updateBreathingAnimation];
192
- }
193
- // 定时器只看可见性。十六向跟随期间它也要转——注意力现在是有时限的,到点必须有人
194
- // 把它收回来,而 updateLookForScreenPoint: 只在鼠标移动时才被调用,鼠标一停就没人
195
- // 收尾了。跟随期间 nextFrame: 除了这个到期检查之外仍然什么都不做。
196
- - (void)updateFrameTimer {
197
- BOOL shouldRun = !self.animationSuspended;
198
- if (shouldRun == self.frameTimer.isValid) return;
199
- if (!shouldRun) {
200
- [self.frameTimer invalidate];
201
- self.frameTimer = nil;
202
- return;
203
- }
204
- // block 版定时器 + weak self,避免 NSTimer 持有 target 造成 PetView 永不释放。
205
- __weak PetView *weakSelf = self;
206
- NSTimeInterval interval = PetFrameInterval;
207
- if (self.lowPowerMode) interval *= 1.5;
208
- if (self.reduceMotion) interval *= 2.0;
209
- // 必须注册到 common modes:performWindowDragWithEvent: 期间主 runloop 处于
210
- // NSEventTrackingRunLoopMode,只挂在默认 mode 上的定时器不会触发,宠物会
211
- // 定格在拖动起手的那一帧上,直到松手才继续动。
212
- self.frameTimer = [NSTimer timerWithTimeInterval:interval repeats:YES
213
- block:^(NSTimer *timer) { [weakSelf nextFrame:timer]; }];
214
- self.frameTimer.tolerance = interval * 0.25;
215
- [NSRunLoop.mainRunLoop addTimer:self.frameTimer forMode:NSRunLoopCommonModes];
216
- }
217
- - (void)setLookDirection:(NSInteger)value {
218
- if (_lookDirection == value) return;
219
- _lookDirection = value;
220
- [self updateFrameTimer];
221
- }
222
- - (void)setAnimationSuspended:(BOOL)suspended {
223
- if (_animationSuspended == suspended) return;
224
- _animationSuspended = suspended;
225
- [self updateFrameTimer];
226
- // 停表只管得住 NSTimer 驱动的逐帧动画。呼吸、弹簧这些走 CA,时钟在 render server
227
- // 那边,屏幕睡了照跑——必须把这一层的本地时间也冻住,否则 P0 省下来的电又漏回去。
228
- [self setSpriteLayerPaused:suspended];
229
- if (suspended) {
230
- // 屏幕睡了就把栅格化缓存整个放掉:这是常驻内存里最大的一块,而睡眠期间一格都用不上。
231
- // 醒来重新栅格化只是几毫秒的事,换十几兆常驻内存很划算。
232
- [self.cellCache removeAllObjects];
233
- } else {
234
- [self updateSpriteContents];
235
- }
236
- }
237
- // 冻结/恢复 layer 自己的时间轴。恢复时要把暂停期间流逝的时间补回 beginTime,
238
- // 否则动画会从"睡了多久就跳多远"的位置继续。
239
- - (void)setSpriteLayerPaused:(BOOL)paused {
240
- CALayer *layer = self.spriteLayer;
241
- if (!layer) return;
242
- if (paused) {
243
- if (layer.speed == 0.0) return;
244
- CFTimeInterval now = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
245
- layer.speed = 0.0;
246
- layer.timeOffset = now;
247
- } else {
248
- if (layer.speed != 0.0) return;
249
- CFTimeInterval pausedAt = layer.timeOffset;
250
- layer.speed = 1.0;
251
- layer.timeOffset = 0.0;
252
- layer.beginTime = 0.0;
253
- layer.beginTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedAt;
254
- }
255
- }
256
- - (void)startLookTracking {
257
- if (!self.hasLookRows || self.globalMouseMonitor || self.localMouseMonitor) return;
258
- __weak PetView *weakSelf = self;
259
- self.globalMouseMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskMouseMoved
260
- handler:^(NSEvent *event) {
261
- [weakSelf updateLookForScreenPoint:NSEvent.mouseLocation];
262
- }];
263
- self.localMouseMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskMouseMoved
264
- handler:^NSEvent *(NSEvent *event) {
265
- [weakSelf updateLookForScreenPoint:NSEvent.mouseLocation];
266
- return event;
267
- }];
268
- }
269
- - (void)stopLookTracking {
270
- if (self.globalMouseMonitor) {
271
- [NSEvent removeMonitor:self.globalMouseMonitor];
272
- self.globalMouseMonitor = nil;
273
- }
274
- if (self.localMouseMonitor) {
275
- [NSEvent removeMonitor:self.localMouseMonitor];
276
- self.localMouseMonitor = nil;
277
- }
278
- self.lookDirection = -1;
279
- }
280
- - (void)updateLookTracking {
281
- if (self.hasLookRows) [self startLookTracking];
282
- else [self stopLookTracking];
283
- }
284
- // 注意力有惯性也有衰减,这是活物和传感器的分水岭。
285
- //
286
- // 改造前是鼠标一动就实时跟随——那是摄像头。现在是:多数移动它压根不理会,偶尔才
287
- // "注意到",看一阵子就失去兴趣回正,而且短期内不会再被同一波移动勾走。
288
- // 副作用是开销大幅下降:原来屏幕上每个鼠标事件都要换一次朝向定格并重绘,现在只有
289
- // 真正处于注意状态的那几秒才跟。
290
- - (void)releaseAttention {
291
- if (self.lookDirection < 0) return;
292
- self.lookDirection = -1;
293
- self.attentionCooldownUntil = CFAbsoluteTimeGetCurrent() +
294
- 4.0 + 8.0 * (arc4random_uniform(1000) / 1000.0);
295
- [self playRow:0 throughFrame:5 oneShot:NO];
296
- }
297
- - (void)updateLookForScreenPoint:(NSPoint)screenPoint {
298
- if (!self.hasLookRows || self.draggingPet || self.oneShot || self.agentActive ||
299
- self.microActive || !self.window) return;
300
- NSTimeInterval now = CFAbsoluteTimeGetCurrent();
301
- if (self.lookDirection < 0) {
302
- if (now < self.attentionCooldownUntil) return;
303
- // 绝大多数移动都不理会。这一条就是"惰性"本身。
304
- if (arc4random_uniform(100) >= 12) return;
305
- self.attentionUntil = now + 3.0 + 5.0 * (arc4random_uniform(1000) / 1000.0);
306
- }
307
-
308
- NSPoint windowPoint = [self.window convertPointFromScreen:screenPoint];
309
- NSPoint localPoint = [self convertPoint:windowPoint fromView:nil];
310
- if (NSPointInRect(localPoint, self.bounds)) return;
311
-
312
- NSPoint center = [self convertPoint:NSMakePoint(NSMidX(self.bounds), NSMidY(self.bounds)) toView:nil];
313
- center = [self.window convertPointToScreen:center];
314
- CGFloat dx = screenPoint.x - center.x;
315
- CGFloat dy = screenPoint.y - center.y;
316
- if (hypot(dx, dy) <= 1.0) return;
317
-
318
- CGFloat degrees = fmod(atan2(dx, dy) * 180.0 / M_PI + 360.0, 360.0);
319
- NSInteger direction = ((NSInteger)llround(degrees / 22.5)) % 16;
320
- if (direction == self.lookDirection) return;
321
-
322
- self.lookDirection = direction;
323
- self.rowIndex = 9 + direction / 8;
324
- self.frameIndex = direction % 8;
325
- self.needsDisplay = YES;
326
- }
327
- - (NSArray<NSNumber *> *)framesFromZeroThrough:(NSInteger)last {
328
- NSMutableArray<NSNumber *> *result = [NSMutableArray arrayWithCapacity:last + 1];
329
- for (NSInteger index = 0; index <= last; index++) [result addObject:@(index)];
330
- return result;
331
- }
332
- // 全 1 的停留表 = 原来的匀速播放。
333
- - (NSArray<NSNumber *> *)uniformHoldsForCount:(NSUInteger)count {
334
- NSMutableArray<NSNumber *> *result = [NSMutableArray arrayWithCapacity:count];
335
- for (NSUInteger index = 0; index < count; index++) [result addObject:@1];
336
- return result;
337
- }
338
- // 待机的停留表:整轮统一放慢或加快,**绝不定格某一帧**。
339
- //
340
- // 试过"随机挑一帧长停 8~18 拍"做发呆,实测很别扭,别改回去。原因是素材不受控:
341
- // 每套素材的待机行内容都不一样,第 0 帧也不保证是自然站姿,随便定格一帧经常停在
342
- // 动作做到一半的姿势上,读起来是"动画卡住了"而不是"它在休息"。
343
- // 改成只调速度:慢下来同样能读出"它安静了",而且因为始终在动,任何素材都不会翻车。
344
- //
345
- // 速度在 1~3 拍/帧之间随机游走(0.22~0.66s 一帧),并在一轮之内从上一档平滑过渡到
346
- // 新一档,避免在循环接缝处突然变速。上限压在 3 拍,再慢就接近定格了。
347
- // 现在返回匀速,等于关掉了这个行为。frameHolds 机制本身保留:微动层要用它做
348
- // "慢放一个已有动作"和"定格朝向若干拍",而且全 1 时行为和改造前完全一致,留着零成本。
349
- //
350
- // 两版都试过,都不行,别再往回走:
351
- // 1. 随机挑一帧长停 8~18 拍做"发呆"——素材不受控,第 0 帧也不保证是自然站姿,
352
- // 经常停在动作做到一半的姿势上,读起来是"动画卡住了"。
353
- // 2. 整轮 1~3 拍随机游走做"慢下来"——同样是在改一条连续动画的播放节奏,
354
- // 观感是掉帧,不是休息。
355
- // 结论:待机行本身已经是完整循环,动它的节奏一律读成故障。待机的活物感要靠
356
- // **往流里插入有始有终的动作**(微动层),而不是改流本身的速度。
357
- - (NSArray<NSNumber *> *)idleHoldsForCount:(NSUInteger)count {
358
- return [self uniformHoldsForCount:count];
359
- }
360
- - (BOOL)isIdleRow:(NSInteger)row {
361
- return row == 0;
362
- }
363
- - (void)playRow:(NSInteger)row throughFrame:(NSInteger)last oneShot:(BOOL)oneShot {
364
- if (!oneShot && !self.oneShot && self.rowIndex == row) return;
365
- // 任何外部动作(悬停、拖动、agent 事件)都直接接管,微动无条件让位。
366
- if (self.microActive) {
367
- self.microActive = NO;
368
- [self scheduleNextMicroBehavior];
369
- }
370
- self.lookDirection = -1;
371
- self.frameRows = nil;
372
- self.rowIndex = row;
373
- self.frames = [self framesFromZeroThrough:last];
374
- self.frameHolds = [self isIdleRow:row] && !oneShot
375
- ? [self idleHoldsForCount:self.frames.count]
376
- : [self uniformHoldsForCount:self.frames.count];
377
- self.holdTicks = 0;
378
- self.sequenceIndex = 0;
379
- self.frameIndex = 0;
380
- self.oneShot = oneShot;
381
- self.needsDisplay = YES;
382
- }
383
- - (BOOL)isPocketPoint:(NSPoint)point {
384
- CGFloat centerX = NSMidX(self.bounds);
385
- CGFloat centerY = NSHeight(self.bounds) * 0.32;
386
- CGFloat dx = (point.x - centerX) / (NSWidth(self.bounds) * 0.22);
387
- CGFloat dy = (point.y - centerY) / (NSHeight(self.bounds) * 0.16);
388
- return dx * dx + dy * dy <= 1.0;
389
- }
390
- - (BOOL)updatePocketHoverForPoint:(NSPoint)point {
391
- BOOL overPocket = [self isPocketPoint:point];
392
- if (self.pocketHoverChanged) self.pocketHoverChanged(overPocket);
393
- if (overPocket) [NSCursor.pointingHandCursor set];
394
- else [NSCursor.arrowCursor set];
395
- return overPocket;
396
- }
397
- - (void)updateHoverForPoint:(NSPoint)point {
398
- [self noteActivity];
399
- BOOL overPocket = [self updatePocketHoverForPoint:point];
400
- if (overPocket) {
401
- [self playRow:5 throughFrame:7 oneShot:NO];
402
- } else if (point.y >= NSHeight(self.bounds) * 0.58) {
403
- [NSCursor.pointingHandCursor set];
404
- [self playRow:4 throughFrame:4 oneShot:NO];
405
- } else if (point.y <= NSHeight(self.bounds) * 0.20) {
406
- [NSCursor.pointingHandCursor set];
407
- [self playRow:6 throughFrame:5 oneShot:NO];
408
- } else if (point.x >= NSWidth(self.bounds) * 0.66) {
409
- [NSCursor.arrowCursor set];
410
- [self playRow:3 throughFrame:3 oneShot:NO];
411
- } else if (point.x <= NSWidth(self.bounds) * 0.34) {
412
- [NSCursor.arrowCursor set];
413
- [self playRow:8 throughFrame:5 oneShot:NO];
414
- } else {
415
- [NSCursor.arrowCursor set];
416
- [self playRow:0 throughFrame:5 oneShot:NO];
417
- }
418
- }
419
- - (void)mouseEntered:(NSEvent *)event {
420
- [self mouseMoved:event];
421
- }
422
- - (void)mouseMoved:(NSEvent *)event {
423
- if (self.draggingPet) return;
424
- NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
425
- // 一次性动作只锁定动画,不应锁住面板热区。否则鼠标在动作期间进入后停住,
426
- // oneShot 结束时不会再收到 mouseMoved,额度面板就一直没有机会展示。
427
- if (self.oneShot || self.agentActive) {
428
- [self updatePocketHoverForPoint:point];
429
- return;
430
- }
431
- [self updateHoverForPoint:point];
432
- }
433
- - (void)mouseExited:(NSEvent *)event {
434
- if (self.draggingPet) return;
435
- if (self.pocketHoverChanged) self.pocketHoverChanged(NO);
436
- [NSCursor.arrowCursor set];
437
- if (self.agentActive || self.oneShot) return;
438
- [self playRow:0 throughFrame:5 oneShot:NO];
439
- }
440
- - (void)nextFrame:(NSTimer *)timer {
441
- if (self.lookDirection >= 0) {
442
- if (CFAbsoluteTimeGetCurrent() >= self.attentionUntil) [self releaseAttention];
443
- return;
444
- }
445
- // performWindowDragWithEvent: 会立即返回,且窗口服务器可能吞掉 mouseUp。
446
- // 动画时钟同时作为释放兜底,避免拖动状态永久停留在 running 行。
447
- if (self.draggingPet &&
448
- !CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, kCGMouseButtonLeft)) {
449
- [self endPetDrag];
450
- return;
451
- }
452
- // 用力程度随时间衰减,掉档时把呼吸调回慢档。
453
- if (self.breathLevel != 0) [self updateBreathingIfExertionChanged];
454
-
455
- // 微动调度:只在待机且无人打扰时倒数,到点起一个小动作。
456
- if ([self canStartMicroBehavior]) {
457
- self.microCountdown -= 1;
458
- if (self.microCountdown <= 0) {
459
- [self startMicroBehavior];
460
- return;
461
- }
462
- }
463
-
464
- // 当前帧还没停够拍数就原地不动。停留期间连 needsDisplay 都不置,这一拍是纯空转。
465
- self.holdTicks += 1;
466
- if (self.holdTicks < [self holdForSequenceIndex:self.sequenceIndex]) return;
467
- self.holdTicks = 0;
468
-
469
- self.sequenceIndex += 1;
470
- if (self.sequenceIndex >= self.frames.count) {
471
- if (self.oneShot) {
472
- self.rowIndex = 0;
473
- self.frames = [self framesFromZeroThrough:5];
474
- self.frameHolds = [self idleHoldsForCount:self.frames.count];
475
- self.oneShot = NO;
476
- self.agentActive = NO;
477
- self.microActive = NO;
478
- [self scheduleNextMicroBehavior];
479
- } else if (self.microActive) {
480
- // 微动播完就回待机。这条分支独立于 oneShot,所以不会清 agentActive。
481
- [self endMicroBehavior];
482
- self.needsDisplay = YES;
483
- return;
484
- }
485
- self.sequenceIndex = 0;
486
- }
487
- self.frameIndex = self.frames[self.sequenceIndex].integerValue;
488
- self.needsDisplay = YES;
489
- }
490
- #pragma mark - 微动层
491
-
492
- - (void)noteActivity {
493
- self.lastActivityTime = CFAbsoluteTimeGetCurrent();
494
- [self scheduleNextMicroBehavior];
495
- [self persistLastActivityThrottled];
496
- }
497
- // 落盘限流:noteActivity 在鼠标划过宠物时会被高频调用,每次都写 defaults 没必要。
498
- - (void)persistLastActivityThrottled {
499
- if (self.lastActivityTime - self.lastActivitySavedAt < PetActivitySaveInterval) return;
500
- self.lastActivitySavedAt = self.lastActivityTime;
501
- [NSUserDefaults.standardUserDefaults setDouble:self.lastActivityTime
502
- forKey:PetLastActivityKey];
503
- }
504
- - (void)restoreLastActivity {
505
- double saved = [NSUserDefaults.standardUserDefaults doubleForKey:PetLastActivityKey];
506
- NSTimeInterval now = CFAbsoluteTimeGetCurrent();
507
- // 只认过去的时间戳:系统时钟被调过或 defaults 被写坏时,宁可当成"刚刚活动过",
508
- // 也不能让宠物一启动就以为闲置了几十年直接进打盹。
509
- if (saved > 0 && saved <= now) self.lastActivityTime = saved;
510
- else self.lastActivityTime = now;
511
- self.lastActivitySavedAt = self.lastActivityTime;
512
- [self scheduleNextMicroBehavior];
513
- }
514
- // 当前用力程度,按半衰期衰减。
515
- - (double)currentExertion {
516
- NSTimeInterval elapsed = CFAbsoluteTimeGetCurrent() - self.exertionUpdatedAt;
517
- if (elapsed <= 0) return self.exertion;
518
- return self.exertion * pow(0.5, elapsed / PetExertionHalfLife);
519
- }
520
- - (void)bumpExertion {
521
- self.exertion = MIN(1.0, [self currentExertion] + PetExertionPerEvent);
522
- self.exertionUpdatedAt = CFAbsoluteTimeGetCurrent();
523
- [self updateBreathingIfExertionChanged];
524
- }
525
- // 分档而不是连续调:改呼吸快慢要重加 CA 动画,相位会跳一下(最多 1.5px)。
526
- // 分成三档之后一次任务里只会重加两三次,跳动察觉不到;连续调就是每拍都跳。
527
- - (NSInteger)exertionLevel {
528
- double exertion = [self currentExertion];
529
- if (exertion < 0.2) return 0;
530
- if (exertion < 0.6) return 1;
531
- return 2;
532
- }
533
- - (void)updateBreathingIfExertionChanged {
534
- NSInteger level = [self exertionLevel];
535
- if (level == self.breathLevel) return;
536
- self.breathLevel = level;
537
- [self.spriteLayer removeAnimationForKey:@"breath"];
538
- [self updateBreathingAnimation];
539
- }
540
- // 无聊曲线:闲久了先躁动(微动变频繁)、再倦、最后几乎不动。
541
- // 这条曲线是非单调的,本身就是叙事——"闲得发慌"和"待久了发蔫"是两种不同的状态。
542
- // 调试用:把无聊曲线的三个拐点整体缩放,好在几十秒内走完本来要半小时的过程。
543
- // defaults write com.universewang.cc-pets CCPetsBoredomScale -float 0.25
544
- // defaults delete com.universewang.cc-pets CCPetsBoredomScale # 恢复正常
545
- // 域名必须是 bundle identifier,写成 "cc-pets" 会落到另一个 plist,桌宠读不到。
546
- // 每次排期都现读,改完立刻生效,不用重启桌宠。缺省 1.0,也就是不缩放。
547
- - (double)boredomScale {
548
- id value = [NSUserDefaults.standardUserDefaults objectForKey:@"CCPetsBoredomScale"];
549
- if (![value isKindOfClass:NSNumber.class]) return 1.0;
550
- double scale = [value doubleValue];
551
- if (!(scale > 0)) return 1.0;
552
- return MIN(scale, 10.0);
553
- }
554
- - (double)microIntervalScale {
555
- NSTimeInterval idle = (CFAbsoluteTimeGetCurrent() - self.lastActivityTime) / [self boredomScale];
556
- if (idle < PetBoredomRestless) return 1.0;
557
- if (idle < PetBoredomTired) return 0.5; // 躁动:间隔减半
558
- if (idle < PetBoredomDrowsy) return 2.0; // 倦
559
- return 6.0; // 打盹
560
- }
561
- - (void)scheduleNextMicroBehavior {
562
- double scale = [self microIntervalScale];
563
- double span = PetMicroIntervalMax - PetMicroIntervalMin;
564
- double seconds = (PetMicroIntervalMin + span * (arc4random_uniform(1000) / 1000.0)) * scale;
565
- self.microCountdown = (NSInteger)llround(seconds / PetFrameInterval);
566
- }
567
- // 待机之外一律不做:agent 在干活、正在拖、正在播一次性动作、十六向跟随中都不打断。
568
- - (BOOL)canStartMicroBehavior {
569
- return !self.microActive && !self.agentActive && !self.oneShot && !self.draggingPet &&
570
- !self.animationSuspended && self.lookDirection < 0 && self.window != nil &&
571
- [self isIdleRow:self.rowIndex];
572
- }
573
- // 微动只用"有始有终的动作",不改待机流本身的节奏。
574
- //
575
- // 9 行素材只有 row 3(观察)语义足够中性——它是一个独立动作,读起来是"它张望了一下"。
576
- // 强语义行(row 1 跑/bash、row 7 工作/edit)绝不能用:待机时冒出来,用户会以为
577
- // agent 在干活。
578
- // 11 行素材额外可以用 row 9/10 的十六向定格:那是素材本来就设计成静止的格子,
579
- // 定格不违和,且语义纯粹是"朝某个方向看"。
580
- // 鼠标当前在哪个方向。算法和 updateLookForScreenPoint: 同源,-1 表示算不出来。
581
- - (NSInteger)directionTowardScreenPoint:(NSPoint)screenPoint {
582
- if (!self.window) return -1;
583
- NSPoint center = [self convertPoint:NSMakePoint(NSMidX(self.bounds), NSMidY(self.bounds)) toView:nil];
584
- center = [self.window convertPointToScreen:center];
585
- CGFloat dx = screenPoint.x - center.x;
586
- CGFloat dy = screenPoint.y - center.y;
587
- if (hypot(dx, dy) <= 1.0) return -1;
588
- CGFloat degrees = fmod(atan2(dx, dy) * 180.0 / M_PI + 360.0, 360.0);
589
- return ((NSInteger)llround(degrees / 22.5)) % 16;
590
- }
591
- // 十六向是绕一圈排的,两个方向之间要走近的那一侧,否则会绕远大半圈。
592
- - (NSInteger)directionStepFrom:(NSInteger)from to:(NSInteger)to {
593
- NSInteger forward = ((to - from) + 16) % 16;
594
- return forward <= 8 ? 1 : -1;
595
- }
596
- // 转头:从目标方向的前几格逐格扫过去 → 停一下 → 再逐格扫回来。
597
- //
598
- // 素材里 row 9/10 那 16 格本来只是"朝某个方向的静止姿势",但按角度顺序连着播,
599
- // 白捡一个转头动画——不需要任何新素材。这是十六向素材最值钱的用法。
600
- - (BOOL)startGlanceMicroBehavior {
601
- NSInteger target = [self directionTowardScreenPoint:NSEvent.mouseLocation];
602
- if (target < 0) return NO;
603
-
604
- const NSInteger sweep = 3;
605
- NSInteger step = [self directionStepFrom:(target - sweep + 16) % 16 to:target];
606
- NSTimeInterval hold = PetGlanceHoldMin +
607
- (PetGlanceHoldMax - PetGlanceHoldMin) * (arc4random_uniform(1000) / 1000.0);
608
- NSUInteger holdTicks = MAX((NSUInteger)1, (NSUInteger)llround(hold / PetFrameInterval));
609
-
610
- NSMutableArray<NSNumber *> *rows = [NSMutableArray array];
611
- NSMutableArray<NSNumber *> *cols = [NSMutableArray array];
612
- NSMutableArray<NSNumber *> *holds = [NSMutableArray array];
613
- // 转过去
614
- for (NSInteger index = sweep; index >= 0; index--) {
615
- NSInteger direction = ((target - index * step) % 16 + 16) % 16;
616
- [rows addObject:@(9 + direction / 8)];
617
- [cols addObject:@(direction % 8)];
618
- [holds addObject:index == 0 ? @(holdTicks) : @1];
619
- }
620
- // 转回来。最后一格不重复停在目标上,直接从倒数第二格开始退。
621
- for (NSInteger index = 1; index <= sweep; index++) {
622
- NSInteger direction = ((target - index * step) % 16 + 16) % 16;
623
- [rows addObject:@(9 + direction / 8)];
624
- [cols addObject:@(direction % 8)];
625
- [holds addObject:@1];
626
- }
627
-
628
- // 不动 lookDirection:那个字段一旦 >=0 就进注意力模式,nextFrame: 只做到期检查,
629
- // 这段序列就没人推进了。
630
- self.frameRows = rows;
631
- self.frames = cols;
632
- self.frameHolds = holds;
633
- self.holdTicks = 0;
634
- self.sequenceIndex = 0;
635
- self.rowIndex = rows.firstObject.integerValue;
636
- self.frameIndex = cols.firstObject.integerValue;
637
- self.fadeNextContents = YES;
638
- self.needsDisplay = YES;
639
- return YES;
640
- }
641
- // 能力集在换素材时算一次。未知行数(比如第三方给了 10 行)自动落到无朝向档,
642
- // 是安全的降级方向。
643
- - (void)rebuildCapabilities {
644
- self.hasLookRows = self.spriteRowCount >= 11;
645
- NSMutableArray<NSDictionary *> *table = [NSMutableArray array];
646
- // 两档的行为密度要接近,只让表现形式不同。11 行档不该因为花样多就动得更频繁——
647
- // 用户切素材时该读作"这只性格不一样",而不是"这只功能残缺"。
648
- if (self.hasLookRows) {
649
- [table addObject:@{@"kind": @(PetMicroBehaviorGlance), @"weight": @6}];
650
- }
651
- [table addObject:@{@"kind": @(PetMicroBehaviorScan), @"weight": @4}];
652
- self.microBehaviorTable = table;
653
- }
654
- - (void)startScanMicroBehavior {
655
- self.frameRows = nil;
656
- self.rowIndex = 3;
657
- self.frames = [self framesFromZeroThrough:3];
658
- self.frameHolds = [self uniformHoldsForCount:self.frames.count];
659
- self.holdTicks = 0;
660
- self.sequenceIndex = 0;
661
- self.frameIndex = 0;
662
- self.fadeNextContents = YES;
663
- self.needsDisplay = YES;
664
- }
665
- - (void)startMicroBehavior {
666
- self.microActive = YES;
667
- NSInteger total = 0;
668
- for (NSDictionary *entry in self.microBehaviorTable) total += [entry[@"weight"] integerValue];
669
- NSInteger roll = total > 0 ? (NSInteger)arc4random_uniform((uint32_t)total) : 0;
670
- for (NSDictionary *entry in self.microBehaviorTable) {
671
- roll -= [entry[@"weight"] integerValue];
672
- if (roll >= 0) continue;
673
- // 转头要拿得到鼠标方向,拿不到就顺势退到张望,不算失败。
674
- if ([entry[@"kind"] integerValue] == PetMicroBehaviorGlance &&
675
- [self startGlanceMicroBehavior]) {
676
- return;
677
- }
678
- break;
679
- }
680
- [self startScanMicroBehavior];
681
- }
682
- // 收尾只回待机,绝不碰 agentActive。
683
- - (void)endMicroBehavior {
684
- self.microActive = NO;
685
- self.frameRows = nil;
686
- self.fadeNextContents = YES;
687
- self.rowIndex = 0;
688
- self.frames = [self framesFromZeroThrough:5];
689
- self.frameHolds = [self uniformHoldsForCount:self.frames.count];
690
- self.holdTicks = 0;
691
- self.sequenceIndex = 0;
692
- self.frameIndex = 0;
693
- [self scheduleNextMicroBehavior];
694
- }
695
- - (NSUInteger)holdForSequenceIndex:(NSUInteger)index {
696
- if (index >= self.frameHolds.count) return 1;
697
- NSUInteger hold = self.frameHolds[index].unsignedIntegerValue;
698
- return hold > 0 ? hold : 1;
699
- }
700
- - (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed {
701
- [self noteActivity];
702
- [self bumpExertion];
703
- if ([event isEqualToString:@"SessionStart"]) {
704
- self.agentActive = YES;
705
- [self playRow:4 throughFrame:4 oneShot:YES];
706
- } else if ([event isEqualToString:@"UserPromptSubmit"]) {
707
- self.agentActive = YES;
708
- [self playRow:5 throughFrame:7 oneShot:NO];
709
- } else if ([event isEqualToString:@"PermissionRequest"]) {
710
- self.agentActive = YES;
711
- [self playRow:4 throughFrame:4 oneShot:NO];
712
- } else if ([event isEqualToString:@"AutoReviewRequest"]) {
713
- self.agentActive = YES;
714
- [self playRow:8 throughFrame:5 oneShot:NO];
715
- } else if ([event isEqualToString:@"PreToolUse"]) {
716
- self.agentActive = YES;
717
- NSString *lower = tool.lowercaseString;
718
- if ([lower containsString:@"bash"] || [lower containsString:@"exec"]) {
719
- [self playRow:1 throughFrame:7 oneShot:NO];
720
- } else if ([lower containsString:@"patch"] || [lower containsString:@"edit"] || [lower containsString:@"write"]) {
721
- [self playRow:7 throughFrame:5 oneShot:NO];
722
- } else if ([lower containsString:@"read"] || [lower containsString:@"search"] || [lower containsString:@"find"] ||
723
- [lower containsString:@"grep"] || [lower containsString:@"glob"] || [lower containsString:@"web"] ||
724
- [lower hasPrefix:@"mcp__"]) {
725
- [self playRow:3 throughFrame:3 oneShot:NO];
726
- } else if ([lower isEqualToString:@"task"] || [lower containsString:@"agent"]) {
727
- [self playRow:6 throughFrame:5 oneShot:NO];
728
- } else {
729
- [self playRow:8 throughFrame:5 oneShot:NO];
730
- }
731
- } else if ([event isEqualToString:@"SubagentStart"] || [event isEqualToString:@"TaskCreated"]) {
732
- self.agentActive = YES;
733
- [self playRow:6 throughFrame:5 oneShot:NO];
734
- } else if ([event isEqualToString:@"PostToolUse"] || [event isEqualToString:@"PostToolUseFailure"]) {
735
- self.agentActive = YES;
736
- [self playRow:failed ? 5 : 7 throughFrame:failed ? 7 : 5 oneShot:YES];
737
- } else if ([event isEqualToString:@"StopFailure"]) {
738
- self.agentActive = YES;
739
- [self playRow:5 throughFrame:7 oneShot:YES];
740
- } else if ([event isEqualToString:@"Notification"]) {
741
- self.agentActive = YES;
742
- [self playRow:4 throughFrame:4 oneShot:YES];
743
- } else if ([event isEqualToString:@"Stop"] || [event isEqualToString:@"SubagentStop"] ||
744
- [event isEqualToString:@"TaskCompleted"] || [event isEqualToString:@"SessionEnd"]) {
745
- self.agentActive = YES;
746
- [self playRow:3 throughFrame:3 oneShot:YES];
747
- }
748
- }
749
- // 桌宠是 LSUIElement + NSNonactivatingPanel,几乎永远不是活跃应用。不接受 first mouse
750
- // 的话,AppKit 会把点击非活跃应用窗口的第一次 mouseDown 当成"激活点击"消耗掉,视图
751
- // 根本收不到——表现为要点两下才拖得动。以前靠 movableByWindowBackground 拖动时不受
752
- // 影响(窗口背景拖动在窗口服务器层处理,不走视图的 first mouse 判定),关掉它之后
753
- // 这个缺陷才暴露出来。
754
- - (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
755
- // 精灵区的拖动由 runWindowDragWithEvent: 自己发起,不让 AppKit 的窗口背景拖动同时
756
- // 介入同一次按下;窗口透明区没有这个覆写,继续走 movableByWindowBackground。
757
- // 两条路径底层都是窗口服务器拖动,手感一致。
758
- - (BOOL)mouseDownCanMoveWindow { return NO; }
759
- // 阈值起点取事件自带的坐标,不用 NSEvent.mouseLocation(那是"处理这条事件时"鼠标的实时
760
- // 位置)。主线程被别的活儿占住时,mouseDown 会晚一截才被处理,实时位置早已跟着手滑走,
761
- // 起点于是落在远处,后面要多走同样的距离才够过阈值——表现为按住之后宠物迟迟不动。
762
- // 阈值判定发生在窗口服务器接手拖动之前,窗口此刻还没动,所以窗口坐标是稳定的参照系。
763
- - (void)mouseDown:(NSEvent *)event {
764
- [self noteActivity];
765
- self.agentActive = NO;
766
- self.dragStartMouse = event.locationInWindow;
767
- }
768
- - (void)mouseDragged:(NSEvent *)event {
769
- if (self.draggingPet) return;
770
- NSPoint current = event.locationInWindow;
771
- CGFloat horizontal = current.x - self.dragStartMouse.x;
772
- CGFloat vertical = current.y - self.dragStartMouse.y;
773
- if (hypot(horizontal, vertical) < PetDragThreshold) return;
774
- [self runWindowDragWithEvent:event movingRight:horizontal >= 0];
775
- }
776
- // 拖动交给窗口服务器:它不依赖应用事件流,所以掠过其他窗口、拖出屏幕、
777
- // 应用非活跃都不会中断。这个 API 会立即返回,且 mouseUp 可能不会发回应用,
778
- // 因此不能在调用后立刻恢复 idle;释放兜底由 nextFrame: 检查物理按键状态。
779
- - (void)runWindowDragWithEvent:(NSEvent *)event movingRight:(BOOL)movingRight {
780
- self.draggingPet = YES;
781
- if (self.pocketHoverChanged) self.pocketHoverChanged(NO);
782
- if (self.dragStateChanged) self.dragStateChanged(YES);
783
- [self playRow:movingRight ? 1 : 2 throughFrame:7 oneShot:NO];
784
- [self startObservingWindowMove];
785
-
786
- [self.window performWindowDragWithEvent:event];
787
- }
788
- - (void)startObservingWindowMove {
789
- if (self.observingWindowMove || !self.window) return;
790
- self.lastDragWindowOrigin = self.window.frame.origin;
791
- self.observingWindowMove = YES;
792
- [NSNotificationCenter.defaultCenter addObserver:self
793
- selector:@selector(petWindowMovedWhileDragging:)
794
- name:NSWindowDidMoveNotification object:self.window];
795
- }
796
- - (void)stopObservingWindowMove {
797
- if (!self.observingWindowMove) return;
798
- self.observingWindowMove = NO;
799
- [NSNotificationCenter.defaultCenter removeObserver:self
800
- name:NSWindowDidMoveNotification object:self.window];
801
- }
802
- // 精灵在窗口内往反方向落后一点,看着就有了重量。滞后量跟这一帧的位移走,
803
- // 停手不动时位移为 0,会自然归位。
804
- - (void)petWindowMovedWhileDragging:(NSNotification *)notification {
805
- if (!self.draggingPet || self.reduceMotion) return;
806
- NSPoint origin = self.window.frame.origin;
807
- CGFloat dx = origin.x - self.lastDragWindowOrigin.x;
808
- self.lastDragWindowOrigin = origin;
809
-
810
- CGFloat lag = -dx * PetDragLagFactor;
811
- lag = MAX(-PetDragLagMax, MIN(PetDragLagMax, lag));
812
- // 缩短隐式动画时长:默认 0.25s 追不上手,看着是糊而不是滞后。0.12s 既平滑又跟手。
813
- [CATransaction begin];
814
- [CATransaction setAnimationDuration:0.12];
815
- [CATransaction setAnimationTimingFunction:
816
- [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
817
- self.spriteLayer.transform = CATransform3DMakeTranslation(lag, 0, 0);
818
- [CATransaction commit];
819
- }
820
- - (void)endPetDrag {
821
- if (!self.draggingPet) return;
822
- self.draggingPet = NO;
823
- [self stopObservingWindowMove];
824
- if (self.dragStateChanged) self.dragStateChanged(NO);
825
- [self playRow:0 throughFrame:5 oneShot:NO];
826
- [self playSettleAnimation];
827
- }
828
- // 落脚:从当前滞后位置 → 压扁 → 轻微回弹过冲 → 静止。
829
- // 整段只动 transform 一个属性,和挂在 position.y 上的呼吸互不干扰。
830
- - (void)playSettleAnimation {
831
- CALayer *layer = self.spriteLayer;
832
- if (!layer) return;
833
- if (self.reduceMotion) {
834
- layer.transform = CATransform3DIdentity;
835
- return;
836
- }
837
- CATransform3D current = ((CALayer *)layer.presentationLayer ?: layer).transform;
838
- CAKeyframeAnimation *settle = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
839
- settle.values = @[
840
- [NSValue valueWithCATransform3D:current],
841
- [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.07, 0.92, 1.0)],
842
- [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.97, 1.04, 1.0)],
843
- [NSValue valueWithCATransform3D:CATransform3DIdentity]
844
- ];
845
- settle.keyTimes = @[@0.0, @0.34, @0.68, @1.0];
846
- settle.duration = PetSettleDuration;
847
- settle.timingFunction = [CAMediaTimingFunction
848
- functionWithName:kCAMediaTimingFunctionEaseOut];
849
- // 先把 model 值落到静止态且不触发隐式动画,否则它会和下面的关键帧同时跑。
850
- [CATransaction begin];
851
- [CATransaction setDisableActions:YES];
852
- layer.transform = CATransform3DIdentity;
853
- [CATransaction commit];
854
- [layer addAnimation:settle forKey:@"settle"];
855
- }
856
- - (void)mouseUp:(NSEvent *)event {
857
- if (self.draggingPet) {
858
- [self endPetDrag];
859
- return;
860
- }
861
- [self handleInteractionClick];
862
- }
863
- - (void)handleInteractionClick {
864
- NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
865
- if (![defaults boolForKey:PetInteractionEnabledKey]) {
866
- [self playRow:7 throughFrame:5 oneShot:YES];
867
- return;
868
- }
869
- NSTimeInterval interval = [defaults doubleForKey:PetInteractionIntervalKey];
870
- interval = MAX(0.4, MIN(3.0, interval));
871
- NSInteger heartThreshold = MAX((NSInteger)2,
872
- [defaults integerForKey:PetInteractionHeartThresholdKey]);
873
- NSInteger annoyedThreshold = MAX(heartThreshold + 1,
874
- [defaults integerForKey:PetInteractionAnnoyedThresholdKey]);
875
- NSTimeInterval now = CFAbsoluteTimeGetCurrent();
876
- if (now - self.lastInteractionClickAt > interval) {
877
- self.interactionClickCount = 0;
878
- }
879
- self.lastInteractionClickAt = now;
880
- self.interactionClickCount++;
881
-
882
- if (self.interactionClickCount >= annoyedThreshold) {
883
- [self spawnInteractionSymbols:@[@"💢", @"╬", @"!"]
884
- color:NSColor.systemOrangeColor];
885
- [self playRow:5 throughFrame:7 oneShot:YES];
886
- if (self.interactionPhraseRequested) {
887
- self.interactionPhraseRequested(@"click_annoyed");
888
- }
889
- return;
890
- }
891
- if (self.interactionClickCount >= heartThreshold) {
892
- [self spawnInteractionSymbols:@[@"♥︎", @"♥︎", @"♥︎"]
893
- color:NSColor.systemPinkColor];
894
- [self playRow:3 throughFrame:3 oneShot:YES];
895
- if (self.interactionPhraseRequested) {
896
- self.interactionPhraseRequested(@"click_heart");
897
- }
898
- return;
899
- }
900
- [self playRow:7 throughFrame:5 oneShot:YES];
901
- }
902
- - (void)spawnInteractionSymbols:(NSArray<NSString *> *)symbols color:(NSColor *)color {
903
- NSTimeInterval duration = self.reduceMotion ? 0.45 : 0.95;
904
- for (NSUInteger index = 0; index < symbols.count; index++) {
905
- CGFloat x = 34.0 + arc4random_uniform(66);
906
- CGFloat y = 104.0 + arc4random_uniform(12);
907
- NSTextField *label = [NSTextField labelWithString:symbols[index]];
908
- label.alignment = NSTextAlignmentCenter;
909
- label.font = [NSFont systemFontOfSize:index == 0 ? 21 : 17
910
- weight:NSFontWeightBold];
911
- label.textColor = color;
912
- label.frame = NSMakeRect(x, y, 30, 28);
913
- label.wantsLayer = YES;
914
- label.layer.zPosition = 20;
915
- [self addSubview:label];
916
-
917
- CFTimeInterval delay = index * 0.08;
918
- CGPoint start = label.layer.position;
919
- CGPoint end = CGPointMake(start.x + ((NSInteger)index - 1) * 10,
920
- start.y + (self.reduceMotion ? 0 : 34 + index * 5));
921
- CAKeyframeAnimation *position = [CAKeyframeAnimation animationWithKeyPath:@"position"];
922
- position.values = @[[NSValue valueWithPoint:start], [NSValue valueWithPoint:end]];
923
- CAKeyframeAnimation *opacity = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
924
- opacity.values = @[@0.0, @1.0, @1.0, @0.0];
925
- opacity.keyTimes = @[@0.0, @0.18, @0.68, @1.0];
926
- CAKeyframeAnimation *scale = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
927
- scale.values = @[@0.65, @1.12, @1.0];
928
- scale.keyTimes = @[@0.0, @0.35, @1.0];
929
- CAAnimationGroup *group = [CAAnimationGroup animation];
930
- group.animations = @[position, opacity, scale];
931
- group.duration = duration;
932
- group.beginTime = CACurrentMediaTime() + delay;
933
- group.fillMode = kCAFillModeBoth;
934
- group.removedOnCompletion = NO;
935
- [label.layer addAnimation:group forKey:@"interactionFloat"];
936
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
937
- (int64_t)((duration + delay + 0.05) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
938
- [label removeFromSuperview];
939
- });
940
- }
941
- }
942
- // 每一格都用**原来 drawRect: 那一次绘制**预先栅格化成位图,再交给 layer。
943
- //
944
- // 试过两条更"聪明"的路,都不行,别改回去:
945
- // 1. CGImageCreateWithImageInRect 预裁——素材经 LoadPetSpriteImage 缩略后不保证能被
946
- // 8 列 rowCount 行整除(超大素材缩略后可能得到小数尺寸的源格),
947
- // 小数矩形会被取整,采样相位偏掉,边缘整行错位。
948
- // 2. 整表交给 layer + contentsRect 选帧——CA 自己的最近邻缩放相位同样和 NSImage 对不上,
949
- // 实测形状吻合度反而从 99.4% 掉到 93.5%。
950
- // 照搬原来的 drawInRect:fromRect: 才能保证逐像素等价:栅格化的是同一段代码,只是从
951
- // 每帧执行挪到了每格一次。
952
- - (void)rebuildSpriteCache {
953
- [self.cellCache removeAllObjects];
954
- CGFloat scale = self.spriteScale;
955
- self.spriteLayer.contentsScale = scale;
956
- // 上限按倍率和行数定,不能写死:11 行素材光十六向朝向就占 16 格,加上待机和动作帧,
957
- // 固定 6MB(视网膜下约 18 格)会卡在淘汰边缘,鼠标绕着宠物转就不停重栅格化。
958
- //
959
- // 但也不能给太多。实测这一块是常驻内存最大的单一新增项:视网膜下每格 328KB,
960
- // 原来给 48 格 = 15.4MB,而真实活跃工作集只有待机 6 帧 + 当前动作 ≤8 帧 +
961
- // 偶尔几个朝向格,20 格足够,超出的部分纯粹是白占着。
962
- NSSize pointSize = NSInsetRect(self.bounds, 2, 0).size;
963
- self.spriteCacheSize = pointSize;
964
- NSUInteger cellCost = (NSUInteger)(ceil(pointSize.width * scale) *
965
- ceil(pointSize.height * scale) * 4);
966
- NSUInteger affordable = MIN((NSUInteger)(self.spriteRowCount * 8), (NSUInteger)20);
967
- self.cellCache.totalCostLimit = MAX(cellCost * affordable, (NSUInteger)(2 * 1024 * 1024));
968
- [self updateSpriteContents];
969
- }
970
- // 视网膜屏上必须按 backingScaleFactor 栅格化。原来 drawRect: 是直接画进 2x 的后备存储,
971
- // 等于按实际屏幕分辨率采样源格;预栅格化成 1x 位图再让 layer 放大,
972
- // 会比改造前糊一档。
973
- - (CGFloat)spriteScale {
974
- CGFloat scale = self.window.backingScaleFactor;
975
- return scale > 0 ? scale : 1.0;
976
- }
977
- - (void)viewDidChangeBackingProperties {
978
- [super viewDidChangeBackingProperties];
979
- // 换显示器会改 backingScaleFactor,缓存里全是按旧倍率栅格化的位图,必须整体作废。
980
- [self rebuildSpriteCache];
981
- }
982
- - (CGImageRef)cellImageForRow:(NSInteger)row frame:(NSInteger)frame {
983
- if (!self.sheet || self.spriteRowCount <= 0) return NULL;
984
- NSNumber *key = @(row * 8 + frame);
985
- id cached = [self.cellCache objectForKey:key];
986
- if (cached) return (__bridge CGImageRef)cached;
987
-
988
- NSRect target = NSInsetRect(self.bounds, 2, 0);
989
- NSSize pointSize = target.size;
990
- if (pointSize.width <= 0 || pointSize.height <= 0) return NULL;
991
- CGFloat scale = self.spriteScale;
992
- NSInteger pixelWidth = (NSInteger)ceil(pointSize.width * scale);
993
- NSInteger pixelHeight = (NSInteger)ceil(pointSize.height * scale);
994
-
995
- NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
996
- initWithBitmapDataPlanes:NULL pixelsWide:pixelWidth pixelsHigh:pixelHeight
997
- bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
998
- colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
999
- rep.size = pointSize;
1000
-
1001
- CGFloat cellWidth = self.sheet.size.width / 8.0;
1002
- CGFloat cellHeight = self.sheet.size.height / self.spriteRowCount;
1003
- NSRect source = NSMakeRect(frame * cellWidth,
1004
- self.sheet.size.height - (row + 1) * cellHeight, cellWidth, cellHeight);
1005
-
1006
- NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:rep];
1007
- [NSGraphicsContext saveGraphicsState];
1008
- NSGraphicsContext.currentContext = context;
1009
- [self.sheet drawInRect:NSMakeRect(0, 0, pointSize.width, pointSize.height) fromRect:source
1010
- operation:NSCompositingOperationSourceOver fraction:1.0
1011
- respectFlipped:NO hints:@{NSImageHintInterpolation: @(NSImageInterpolationNone)}];
1012
- [NSGraphicsContext restoreGraphicsState];
1013
-
1014
- CGImageRef cell = rep.CGImage;
1015
- if (!cell) return NULL;
1016
- [self.cellCache setObject:(__bridge id)cell forKey:key
1017
- cost:(NSUInteger)(pixelWidth * pixelHeight * 4)];
1018
- return cell;
1019
- }
1020
- // 只打标记,真正换图交给 AppKit 的显示周期。
1021
- //
1022
- // 不要改回"在 setter 里同步换 contents":十六向跟随装的是全局鼠标监听,屏幕上每个
1023
- // 鼠标移动事件都会写 rowIndex/frameIndex(一次方向变化还是连写两个)。同步更新等于
1024
- // 几百次/秒一次不落,实测疯狂动鼠标时 CPU 6~8%,冷缓存期峰值 12.5%。改造前那两个是
1025
- // 无副作用的纯属性 + needsDisplay,由 AppKit 合并成每刷新周期最多一次——这里要还原的
1026
- // 就是那个语义。
1027
- - (void)updateSpriteContents {
1028
- self.needsDisplay = YES;
1029
- }
1030
- // layer-backed 视图走 updateLayer 而不是 drawRect:,AppKit 每个显示周期最多调一次。
1031
- - (BOOL)wantsUpdateLayer {
1032
- return YES;
1033
- }
1034
- // 换 contents 会触发 CA 默认的 0.25s 淡入。逐帧动画上那就是一层永久的拖影,必须关掉。
1035
- - (void)updateLayer {
1036
- CGImageRef cell = [self cellImageForRow:self.rowIndex frame:self.frameIndex];
1037
- if (!cell) return;
1038
- // 逐帧动画默认必须关掉隐式动画,否则每一帧都带 0.25s 淡入,等于一层永久拖影。
1039
- // 只有进出微动那一下例外:那是两个不相干姿势之间的硬切,给一次短淡化才不突兀。
1040
- if (self.fadeNextContents) {
1041
- self.fadeNextContents = NO;
1042
- CATransition *fade = [CATransition animation];
1043
- fade.type = kCATransitionFade;
1044
- fade.duration = 0.13;
1045
- [self.spriteLayer addAnimation:fade forKey:@"contentsFade"];
1046
- }
1047
- [CATransaction begin];
1048
- [CATransaction setDisableActions:YES];
1049
- self.spriteLayer.contents = (__bridge id)cell;
1050
- [CATransaction commit];
1051
- }
1052
- - (void)layout {
1053
- [super layout];
1054
- [self refreshSpriteSize];
1055
- }
1056
- - (void)refreshSpriteSize {
1057
- [self layoutSpriteLayer];
1058
- // 每格缓存的键只包含行/帧,尺寸改变后必须清掉旧尺寸的位图。
1059
- if (!NSEqualSizes(self.spriteCacheSize, NSInsetRect(self.bounds, 2, 0).size)) {
1060
- [self rebuildSpriteCache];
1061
- }
1062
- }
1063
- - (void)setFrame:(NSRect)newFrame {
1064
- [super setFrame:newFrame];
1065
- [self refreshSpriteSize];
1066
- }
1067
- - (void)setFrameSize:(NSSize)newSize {
1068
- [super setFrameSize:newSize];
1069
- [self refreshSpriteSize];
1070
- }
1071
- // 锚点是脚底 (0.5, 0),所以不能直接设 frame——那会把锚点当左下角算。改用 bounds + position。
1072
- - (void)layoutSpriteLayer {
1073
- NSRect target = NSInsetRect(self.bounds, 2, 0);
1074
- [CATransaction begin];
1075
- [CATransaction setDisableActions:YES];
1076
- self.spriteLayer.bounds = CGRectMake(0, 0, NSWidth(target), NSHeight(target));
1077
- self.spriteLayer.position = CGPointMake(NSMidX(target), NSMinY(target));
1078
- [CATransaction commit];
1079
- }
1080
- // 呼吸是常驻 CA 动画:插值和合成都在 render server 侧,主进程零唤醒。
1081
- // 用 byValue 而不是 toValue,动画相对当前 model 值走,换素材或重新布局都不用重设。
1082
- - (void)updateBreathingAnimation {
1083
- // reduceMotion 下彻底不做。这不是省电问题——系统开了减弱动效,持续浮动本身就是
1084
- // 用户明确不想要的东西。
1085
- BOOL shouldBreathe = self.window != nil && !self.reduceMotion;
1086
- if (!shouldBreathe) {
1087
- [self.spriteLayer removeAnimationForKey:@"breath"];
1088
- return;
1089
- }
1090
- if ([self.spriteLayer animationForKey:@"breath"]) return;
1091
- // 越用力呼吸越快、起伏越大。平复回基线是自然衰减出来的,不用单独写过渡。
1092
- NSInteger level = [self exertionLevel];
1093
- double tempo = level == 0 ? 1.0 : (level == 1 ? 0.72 : 0.52);
1094
- double rise = level == 0 ? PetBreathRise : PetBreathRise * (level == 1 ? 1.3 : 1.7);
1095
- CABasicAnimation *breath = [CABasicAnimation animationWithKeyPath:@"position.y"];
1096
- breath.byValue = @(rise);
1097
- breath.duration = PetBreathPeriod * tempo / 2.0;
1098
- breath.autoreverses = YES;
1099
- breath.repeatCount = HUGE_VALF;
1100
- breath.timingFunction = [CAMediaTimingFunction
1101
- functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
1102
- [self.spriteLayer addAnimation:breath forKey:@"breath"];
1103
- }
1104
- - (void)viewDidMoveToWindow {
1105
- [super viewDidMoveToWindow];
1106
- // 进窗口才知道 backingScaleFactor,缓存要按真实倍率重建;呼吸也从这里起步。
1107
- [self rebuildSpriteCache];
1108
- [self updateBreathingAnimation];
1109
- [self restoreLastActivity];
1110
- }
1111
- - (void)setRowIndex:(NSInteger)value {
1112
- if (_rowIndex == value) return;
1113
- _rowIndex = value;
1114
- [self updateSpriteContents];
1115
- }
1116
- - (void)setFrameIndex:(NSInteger)value {
1117
- if (_frameIndex == value) return;
1118
- _frameIndex = value;
1119
- [self updateSpriteContents];
1120
- }
1121
- - (void)setSheet:(NSImage *)sheet {
1122
- if (_sheet == sheet) return;
1123
- _sheet = sheet;
1124
- [self rebuildSpriteCache];
1125
- }
1126
- - (void)setSpriteRowCount:(NSInteger)count {
1127
- if (_spriteRowCount == count) return;
1128
- _spriteRowCount = count;
1129
- [self rebuildSpriteCache];
1130
- }
1131
- - (void)applySheet:(NSImage *)sheet petID:(NSString *)petID rowCount:(NSInteger)rowCount {
1132
- // 直接写 ivar 再统一重建:走 setter 会因为 sheet 和 rowCount 分两次设置而拿旧行数
1133
- // 白裁一遍缓存。
1134
- _sheet = sheet;
1135
- _spriteRowCount = rowCount;
1136
- _rowIndex = 0;
1137
- _frameIndex = 0;
1138
- self.lookDirection = -1;
1139
- self.currentPetID = petID;
1140
- self.sequenceIndex = 0;
1141
- self.frames = [self framesFromZeroThrough:5];
1142
- self.frameHolds = [self idleHoldsForCount:self.frames.count];
1143
- self.holdTicks = 0;
1144
- self.oneShot = NO;
1145
- self.interactionClickCount = 0;
1146
- self.lastInteractionClickAt = 0;
1147
- [self rebuildSpriteCache];
1148
- [self rebuildCapabilities];
1149
- [self updateLookTracking];
1150
- }
1151
- - (void)selectPetFromButton:(NSButton *)sender {
1152
- NSString *petID = sender.identifier;
1153
- if (petID.length == 0) return;
1154
- [self resetPendingDeleteButton];
1155
- if (self.switchPetRequested) self.switchPetRequested(petID);
1156
- [self refreshPetMenuRows];
1157
- }
1158
- - (void)deletePetFromButton:(NSButton *)sender {
1159
- NSString *petID = sender.identifier;
1160
- if (petID.length == 0) return;
1161
- if (![self.pendingDeletePetID isEqualToString:petID]) {
1162
- [self resetPendingDeleteButton];
1163
- self.pendingDeletePetID = petID;
1164
- [self configureDeleteButton:sender confirming:YES];
1165
- return;
1166
- }
1167
-
1168
- BOOL deleted = self.deletePetRequested && self.deletePetRequested(petID);
1169
- if (!deleted) {
1170
- [self resetPendingDeleteButton];
1171
- return;
1172
- }
1173
- self.pendingDeletePetID = nil;
1174
- for (NSMenuItem *item in self.activePetSwitchMenu.itemArray.copy) {
1175
- NSDictionary *pet = [item.representedObject isKindOfClass:NSDictionary.class]
1176
- ? item.representedObject : nil;
1177
- if ([pet[@"id"] isEqualToString:petID]) {
1178
- [self.activePetSwitchMenu removeItem:item];
1179
- break;
1180
- }
1181
- }
1182
- [self refreshPetMenuRows];
1183
- }
1184
- - (void)configureDeleteButton:(NSButton *)button confirming:(BOOL)confirming {
1185
- button.bordered = confirming;
1186
- button.title = @"";
1187
- button.attributedTitle = confirming
1188
- ? [[NSAttributedString alloc] initWithString:L(@"Confirm") attributes:@{
1189
- NSFontAttributeName: [NSFont systemFontOfSize:11 weight:NSFontWeightMedium],
1190
- NSForegroundColorAttributeName: NSColor.systemRedColor,
1191
- }]
1192
- : [[NSAttributedString alloc] initWithString:@""];
1193
- button.image = confirming ? nil : [NSImage imageNamed:NSImageNameTrashEmpty];
1194
- button.imagePosition = confirming ? NSNoImage : NSImageOnly;
1195
- button.contentTintColor = nil;
1196
- button.bezelStyle = NSBezelStyleRounded;
1197
- button.hasDestructiveAction = YES;
1198
- button.toolTip = confirming ? L(@"Click again to delete") : L(@"Delete pet");
1199
- [button setAccessibilityLabel:button.toolTip];
1200
- }
1201
- - (void)resetPendingDeleteButton {
1202
- if (self.pendingDeletePetID.length == 0) return;
1203
- for (NSMenuItem *item in self.activePetSwitchMenu.itemArray) {
1204
- NSButton *button = (NSButton *)[item.view viewWithTag:PetMenuDeleteButtonTag];
1205
- if ([button isKindOfClass:NSButton.class] &&
1206
- [button.identifier isEqualToString:self.pendingDeletePetID]) {
1207
- [self configureDeleteButton:button confirming:NO];
1208
- break;
1209
- }
1210
- }
1211
- self.pendingDeletePetID = nil;
1212
- }
1213
- - (void)refreshPetMenuRows {
1214
- for (NSMenuItem *item in self.activePetSwitchMenu.itemArray) {
1215
- NSDictionary *pet = [item.representedObject isKindOfClass:NSDictionary.class]
1216
- ? item.representedObject : nil;
1217
- NSString *petID = [pet[@"id"] isKindOfClass:NSString.class] ? pet[@"id"] : @"";
1218
- BOOL selected = [petID isEqualToString:self.currentPetID];
1219
- item.state = selected ? NSControlStateValueOn : NSControlStateValueOff;
1220
-
1221
- NSTextField *check = (NSTextField *)[item.view viewWithTag:PetMenuCheckViewTag];
1222
- if ([check isKindOfClass:NSTextField.class]) check.stringValue = selected ? @"✓" : @"";
1223
-
1224
- NSButton *deleteButton = (NSButton *)[item.view viewWithTag:PetMenuDeleteButtonTag];
1225
- if (![deleteButton isKindOfClass:NSButton.class]) continue;
1226
- BOOL deletable = [petID hasPrefix:@"external:"] && !selected;
1227
- deleteButton.hidden = !deletable;
1228
- deleteButton.enabled = deletable;
1229
- if (!deletable && [self.pendingDeletePetID isEqualToString:petID]) {
1230
- [self configureDeleteButton:deleteButton confirming:NO];
1231
- self.pendingDeletePetID = nil;
1232
- }
1233
- }
1234
- }
1235
- - (NSString *)displayNameForPetName:(NSString *)name font:(NSFont *)font maxWidth:(CGFloat)maxWidth {
1236
- if (![name isKindOfClass:NSString.class]) return @"";
1237
- NSDictionary<NSAttributedStringKey, id> *attributes = @{NSFontAttributeName: font};
1238
- if ([name sizeWithAttributes:attributes].width <= maxWidth) return name;
1239
-
1240
- NSString *suffix = @"...";
1241
- NSMutableString *prefix = [NSMutableString string];
1242
- [name enumerateSubstringsInRange:NSMakeRange(0, name.length)
1243
- options:NSStringEnumerationByComposedCharacterSequences
1244
- usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
1245
- NSString *candidate = [NSString stringWithFormat:@"%@%@%@", prefix, substring, suffix];
1246
- if ([candidate sizeWithAttributes:attributes].width > maxWidth) {
1247
- *stop = YES;
1248
- return;
1249
- }
1250
- [prefix appendString:substring];
1251
- }];
1252
- return [prefix stringByAppendingString:suffix];
1253
- }
1254
- - (NSMenuItem *)addPetOption:(NSDictionary *)pet toMenu:(NSMenu *)menu {
1255
- NSString *petID = [pet[@"id"] isKindOfClass:NSString.class] ? pet[@"id"] : @"";
1256
- NSString *name = [pet[@"name"] isKindOfClass:NSString.class] ? pet[@"name"] : @"";
1257
- BOOL selected = [petID isEqualToString:self.currentPetID];
1258
- BOOL deletable = [petID hasPrefix:@"external:"];
1259
-
1260
- NSFont *font = [NSFont menuFontOfSize:13];
1261
- CGFloat nameWidth = ceil([L(@"Pet sprite name...") sizeWithAttributes:@{NSFontAttributeName: font}].width);
1262
- NSString *displayName = [self displayNameForPetName:name font:font maxWidth:nameWidth];
1263
- const CGFloat checkWidth = 14;
1264
- const CGFloat leadingInset = 6;
1265
- const CGFloat nameX = leadingInset + checkWidth;
1266
- const CGFloat deleteWidth = 40;
1267
- const CGFloat trailingInset = 2;
1268
- CGFloat deleteX = nameX + nameWidth + PetMenuControlGap;
1269
- CGFloat rowWidth = deleteX + deleteWidth + trailingInset;
1270
-
1271
- NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:displayName action:nil keyEquivalent:@""];
1272
- item.representedObject = pet;
1273
- item.state = selected ? NSControlStateValueOn : NSControlStateValueOff;
1274
- NSView *row = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, rowWidth, 28)];
1275
-
1276
- NSTextField *check = [NSTextField labelWithString:selected ? @"✓" : @""];
1277
- check.frame = NSMakeRect(leadingInset, 5, checkWidth, 18);
1278
- check.tag = PetMenuCheckViewTag;
1279
- check.font = font;
1280
- check.textColor = NSColor.labelColor;
1281
- [row addSubview:check];
1282
-
1283
- NSTextField *nameLabel = [NSTextField labelWithString:displayName];
1284
- nameLabel.frame = NSMakeRect(nameX, 5, nameWidth, 18);
1285
- nameLabel.font = font;
1286
- nameLabel.textColor = NSColor.labelColor;
1287
- nameLabel.lineBreakMode = NSLineBreakByClipping;
1288
- nameLabel.toolTip = name;
1289
- [row addSubview:nameLabel];
1290
-
1291
- // 透明按钮覆盖勾选和名称区域,既让整块都能点击,也避免 NSButton 自带的标题
1292
- // 内边距破坏“最大文案末尾到删除按钮 8pt”的精确间距。
1293
- NSButton *selectButton = [[NSButton alloc]
1294
- initWithFrame:NSMakeRect(0, 0, nameX + nameWidth, 28)];
1295
- selectButton.bordered = NO;
1296
- selectButton.title = @"";
1297
- selectButton.identifier = petID;
1298
- selectButton.target = self;
1299
- selectButton.action = @selector(selectPetFromButton:);
1300
- selectButton.focusRingType = NSFocusRingTypeNone;
1301
- selectButton.toolTip = name;
1302
- [selectButton setAccessibilityLabel:[NSString stringWithFormat:L(@"Switch to %@"), name]];
1303
- [row addSubview:selectButton];
1304
-
1305
- NSButton *deleteButton = [[NSButton alloc] initWithFrame:NSMakeRect(deleteX, 3, deleteWidth, 22)];
1306
- deleteButton.tag = PetMenuDeleteButtonTag;
1307
- deleteButton.imageScaling = NSImageScaleProportionallyDown;
1308
- deleteButton.identifier = petID;
1309
- deleteButton.target = self;
1310
- deleteButton.action = @selector(deletePetFromButton:);
1311
- deleteButton.enabled = deletable && !selected;
1312
- deleteButton.hidden = !deleteButton.enabled;
1313
- [self configureDeleteButton:deleteButton confirming:NO];
1314
- deleteButton.toolTip = [NSString stringWithFormat:L(@"Delete %@"), name];
1315
- [deleteButton setAccessibilityLabel:deleteButton.toolTip];
1316
- [row addSubview:deleteButton];
1317
-
1318
- item.view = row;
1319
- [menu addItem:item];
1320
- return item;
1321
- }
1322
- - (NSImage *)menuPreviewForPet:(NSDictionary *)pet {
1323
- NSString *path = [pet[@"path"] isKindOfClass:NSString.class] ? pet[@"path"] : nil;
1324
- NSInteger rowCount = [pet[@"spriteRowCount"] integerValue];
1325
- if (path.length == 0 || rowCount <= 0) return nil;
1326
-
1327
- NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
1328
- NSTimeInterval modifiedAt = [attributes[NSFileModificationDate] timeIntervalSince1970];
1329
- unsigned long long fileSize = [attributes[NSFileSize] unsignedLongLongValue];
1330
- NSString *cacheKey = [NSString stringWithFormat:@"%@:%ld:%.6f:%llu",
1331
- path, (long)rowCount, modifiedAt, fileSize];
1332
- NSImage *cached = [self.petMenuPreviewCache objectForKey:cacheKey];
1333
- if (cached) return cached;
1334
-
1335
- NSImage *sheet = LoadPetSpriteImage(path, NSMakeSize(92, 76), rowCount);
1336
- if (!sheet || sheet.size.width <= 0 || sheet.size.height <= 0) return nil;
1337
-
1338
- CGFloat cellWidth = sheet.size.width / 8.0;
1339
- CGFloat cellHeight = sheet.size.height / rowCount;
1340
- NSRect firstFrame = NSMakeRect(0, sheet.size.height - cellHeight, cellWidth, cellHeight);
1341
- CGFloat previewHeight = 76.0;
1342
- CGFloat previewWidth = round(previewHeight * cellWidth / cellHeight);
1343
- NSImage *preview = [[NSImage alloc] initWithSize:NSMakeSize(previewWidth, previewHeight)];
1344
- [preview lockFocus];
1345
- [sheet drawInRect:NSMakeRect(0, 0, previewWidth, previewHeight) fromRect:firstFrame
1346
- operation:NSCompositingOperationSourceOver fraction:1.0
1347
- respectFlipped:NO hints:@{NSImageHintInterpolation: @(NSImageInterpolationNone)}];
1348
- [preview unlockFocus];
1349
- NSUInteger cost = (NSUInteger)ceil(previewWidth * previewHeight * 4.0);
1350
- [self.petMenuPreviewCache setObject:preview forKey:cacheKey cost:cost];
1351
- return preview;
1352
- }
1353
- - (void)preparePetMenuPreviewPanel {
1354
- if (self.petMenuPreviewPanel) return;
1355
-
1356
- NSRect panelFrame = NSMakeRect(0, 0, 92, 100);
1357
- self.petMenuPreviewPanel = [[NSPanel alloc] initWithContentRect:panelFrame
1358
- styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
1359
- backing:NSBackingStoreBuffered defer:NO];
1360
- self.petMenuPreviewPanel.opaque = NO;
1361
- self.petMenuPreviewPanel.backgroundColor = NSColor.clearColor;
1362
- self.petMenuPreviewPanel.hasShadow = YES;
1363
- self.petMenuPreviewPanel.ignoresMouseEvents = YES;
1364
- self.petMenuPreviewPanel.level = NSPopUpMenuWindowLevel + 1;
1365
- self.petMenuPreviewPanel.collectionBehavior = NSWindowCollectionBehaviorTransient |
1366
- NSWindowCollectionBehaviorMoveToActiveSpace;
1367
-
1368
- NSVisualEffectView *background = [[NSVisualEffectView alloc] initWithFrame:panelFrame];
1369
- background.material = NSVisualEffectMaterialMenu;
1370
- background.blendingMode = NSVisualEffectBlendingModeBehindWindow;
1371
- background.state = NSVisualEffectStateActive;
1372
- background.wantsLayer = YES;
1373
- background.layer.cornerRadius = 10.0;
1374
- background.layer.masksToBounds = YES;
1375
-
1376
- self.petMenuPreviewImageView = [[NSImageView alloc] initWithFrame:NSInsetRect(panelFrame, 8, 8)];
1377
- self.petMenuPreviewImageView.imageScaling = NSImageScaleProportionallyUpOrDown;
1378
- self.petMenuPreviewImageView.animates = NO;
1379
- [background addSubview:self.petMenuPreviewImageView];
1380
- self.petMenuPreviewPanel.contentView = background;
1381
- }
1382
- - (void)showMenuPreviewForPet:(NSDictionary *)pet item:(NSMenuItem *)item menu:(NSMenu *)menu {
1383
- NSImage *preview = [self menuPreviewForPet:pet];
1384
- if (!preview) {
1385
- [self.petMenuPreviewPanel orderOut:nil];
1386
- return;
1387
- }
1388
- [self preparePetMenuPreviewPanel];
1389
- self.petMenuPreviewImageView.image = preview;
1390
-
1391
- NSRect itemFrame = item.accessibilityFrame;
1392
- NSRect menuFrame = menu.accessibilityFrame;
1393
- if (NSIsEmptyRect(menuFrame)) {
1394
- NSPoint mouse = NSEvent.mouseLocation;
1395
- menuFrame = NSMakeRect(mouse.x - menu.size.width / 2.0,
1396
- mouse.y - menu.size.height / 2.0, menu.size.width, menu.size.height);
1397
- }
1398
- if (NSIsEmptyRect(itemFrame)) {
1399
- NSPoint mouse = NSEvent.mouseLocation;
1400
- itemFrame = NSMakeRect(menuFrame.origin.x, mouse.y - 11.0, menuFrame.size.width, 22.0);
1401
- }
1402
-
1403
- // 子菜单可能根据屏幕空间展开到主菜单左侧。预览应放在整组菜单外侧,
1404
- // 不能只按当前子菜单定位,否则会覆盖它右边的主菜单。
1405
- NSRect menuGroupFrame = menuFrame;
1406
- for (NSMenu *ancestor = menu.supermenu; ancestor; ancestor = ancestor.supermenu) {
1407
- NSRect ancestorFrame = ancestor.accessibilityFrame;
1408
- if (!NSIsEmptyRect(ancestorFrame)) menuGroupFrame = NSUnionRect(menuGroupFrame, ancestorFrame);
1409
- }
1410
-
1411
- NSPoint menuCenter = NSMakePoint(NSMidX(menuGroupFrame), NSMidY(menuGroupFrame));
1412
- NSScreen *targetScreen = NSScreen.mainScreen ?: NSScreen.screens.firstObject;
1413
- for (NSScreen *screen in NSScreen.screens) {
1414
- if (NSPointInRect(menuCenter, screen.frame)) {
1415
- targetScreen = screen;
1416
- break;
1417
- }
1418
- }
1419
- NSRect screenFrame = targetScreen.visibleFrame;
1420
- NSSize previewSize = self.petMenuPreviewPanel.frame.size;
1421
- CGFloat x = NSMaxX(menuGroupFrame) + 8.0;
1422
- if (x + previewSize.width > NSMaxX(screenFrame)) {
1423
- x = NSMinX(menuGroupFrame) - previewSize.width - 8.0;
1424
- }
1425
- CGFloat y = NSMidY(itemFrame) - previewSize.height / 2.0;
1426
- y = MIN(MAX(y, NSMinY(screenFrame)), NSMaxY(screenFrame) - previewSize.height);
1427
- [self.petMenuPreviewPanel setFrameOrigin:NSMakePoint(x, y)];
1428
- [self.petMenuPreviewPanel orderFront:nil];
1429
- }
1430
- - (void)menu:(NSMenu *)menu willHighlightItem:(NSMenuItem *)item {
1431
- NSDictionary *pet = [item.representedObject isKindOfClass:NSDictionary.class]
1432
- ? item.representedObject : nil;
1433
- if (pet) [self showMenuPreviewForPet:pet item:item menu:menu];
1434
- else [self.petMenuPreviewPanel orderOut:nil];
1435
- // 自绘行的说明由 MenuHintRowView 自己的进出事件管,这里不能去取消它。
1436
- if (item.view) return;
1437
- NSString *hint = [item.representedObject isKindOfClass:NSString.class] ? item.representedObject : nil;
1438
- NSRect itemFrame = item.accessibilityFrame;
1439
- if (hint && !NSIsEmptyRect(itemFrame)) [MenuHint scheduleText:hint belowScreenRect:itemFrame];
1440
- else [MenuHint cancel];
1441
- }
1442
- - (void)menuDidClose:(NSMenu *)menu {
1443
- [MenuHint cancel];
1444
- // CC Bridge 子菜单也以 self 为代理(为了悬停说明),删除确认和预览只属于"管理桌宠"。
1445
- if (menu != self.activePetSwitchMenu) return;
1446
- [self resetPendingDeleteButton];
1447
- [self.petMenuPreviewPanel orderOut:nil];
1448
- }
1449
- // 主菜单的行要撑满 menu.minimumWidth;子菜单只有自己这几项,撑到 194 会让短标题和开关
1450
- // 之间空出一大段。调用方给的是最小宽度,标题放不下时按标题撑宽;行设成可横向拉伸、
1451
- // 开关贴右,菜单会把同一子菜单里的行统一拉到最宽那一行。行内边距左 12 / 右 8。
1452
- - (NSMenuItem *)addPersistentSwitchToMenu:(NSMenu *)menu
1453
- title:(NSString *)title
1454
- checked:(BOOL)checked
1455
- action:(SEL)action
1456
- width:(CGFloat)width
1457
- tag:(NSInteger)tag {
1458
- const CGFloat toggleWidth = 36;
1459
- const CGFloat trailingInset = PetMenuControlGap;
1460
- const CGFloat leadingInset = 12;
1461
- NSTextField *label = [NSTextField labelWithString:title];
1462
- label.font = [NSFont menuFontOfSize:13];
1463
- width = MAX(width, ceil(label.intrinsicContentSize.width) + leadingInset + trailingInset * 2 +
1464
- toggleWidth);
1465
- CGFloat toggleX = width - trailingInset - toggleWidth;
1466
- NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
1467
- NSView *row = [[MenuHintRowView alloc] initWithFrame:NSMakeRect(0, 0, width, 28)];
1468
- row.autoresizingMask = NSViewWidthSizable;
1469
- label.frame = NSMakeRect(leadingInset, 5, toggleX - leadingInset - trailingInset, 18);
1470
- label.autoresizingMask = NSViewWidthSizable;
1471
- label.textColor = NSColor.labelColor;
1472
- label.lineBreakMode = NSLineBreakByTruncatingTail;
1473
- [row addSubview:label];
1474
- MenuToggleSwitch *toggle = [[MenuToggleSwitch alloc]
1475
- initWithFrame:NSMakeRect(toggleX, 3, toggleWidth, 22)];
1476
- toggle.target = NSApp.delegate;
1477
- toggle.action = action;
1478
- toggle.state = checked ? NSControlStateValueOn : NSControlStateValueOff;
1479
- toggle.tag = tag;
1480
- toggle.autoresizingMask = NSViewMinXMargin;
1481
- [toggle setAccessibilityLabel:title];
1482
- [row addSubview:toggle];
1483
- item.view = row;
1484
- [menu addItem:item];
1485
- return item;
1486
- }
1487
- - (NSMenuItem *)addUsageModeControlToMenu:(NSMenu *)menu
1488
- provider:(NSString *)provider
1489
- preferenceKey:(NSString *)preferenceKey
1490
- tag:(NSInteger)tag {
1491
- NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
1492
- NSView *row = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 134, 28)];
1493
- NSTextField *label = [NSTextField labelWithString:provider];
1494
- label.frame = NSMakeRect(12, 5, 48, 18);
1495
- label.font = [NSFont menuFontOfSize:13];
1496
- label.textColor = NSColor.labelColor;
1497
- [row addSubview:label];
1498
-
1499
- MenuUsageModeButton *control = [[MenuUsageModeButton alloc] initWithFrame:NSMakeRect(68, 3, 58, 22)];
1500
- control.target = NSApp.delegate;
1501
- control.action = @selector(setUsageDisplayModeFromControl:);
1502
- control.state = [[NSUserDefaults.standardUserDefaults stringForKey:preferenceKey]
1503
- isEqualToString:@"api"] ? NSControlStateValueOn : NSControlStateValueOff;
1504
- control.tag = tag;
1505
- [control setAccessibilityLabel:[NSString stringWithFormat:L(@"%@ usage display"), provider]];
1506
- [row addSubview:control];
1507
- item.view = row;
1508
- [menu addItem:item];
1509
- return item;
1510
- }
1511
- // CC Bridge 开关组。状态每次打开菜单时现读(开关文件 / 选项),不在视图里缓存。
1512
- // 除"消息角标 / 新消息通知"这两项只影响桌宠外,其余开关都通过 cc-pets bridge enable / configure
1513
- // 落到 Claude Code / Codex 的配置里。
1514
- - (void)addBridgeSwitchToMenu:(NSMenu *)menu title:(NSString *)title checked:(BOOL)checked
1515
- action:(SEL)action tag:(NSInteger)tag toolTip:(NSString *)toolTip {
1516
- // 与其他子菜单同宽。菜单宽度取最宽的一行:标题都控制在 5 个字以内,说明性文字放进悬停提示,
1517
- // 否则长文字行会把菜单撑宽,而自绘开关行是固定宽度,开关就不再贴右边。
1518
- // 说明不用系统 toolTip:它只在 App 激活时显示,见 MenuHintView.h。
1519
- NSMenuItem *item = [self addPersistentSwitchToMenu:menu title:title checked:checked
1520
- action:action width:PetSubmenuRowWidth tag:tag];
1521
- ((MenuHintRowView *)item.view).hint = toolTip;
1522
- }
1523
- // 一级子菜单只放启用和最常动的两个开关(开关在上、二级菜单在下);免审批(设一次就不动)和只影响桌宠的提醒各收进二级菜单。
1524
- // 未开启时只留"启用"一行:其余开关此时都不生效,列出来只是占地方。开启是异步的,
1525
- // 菜单停留期间不会自己长出其余项,下次打开时按实际状态重建。
1526
- - (void)addBridgeMenuToMenu:(NSMenu *)menu {
1527
- NSMenuItem *bridgeItem = [menu addItemWithTitle:@"CC Bridge" action:nil keyEquivalent:@""];
1528
- NSMenu *bridgeMenu = [NSMenu new];
1529
- // 免审批 / 桌宠提醒 是普通菜单项,悬停说明走 menu:willHighlightItem:。
1530
- bridgeMenu.delegate = self;
1531
- bridgeItem.submenu = bridgeMenu;
1532
- BOOL enabled = CCBridgeEnabled();
1533
- [self addBridgeSwitchToMenu:bridgeMenu title:L(@"Enable") checked:enabled
1534
- action:@selector(toggleBridgeEnabled:) tag:0
1535
- toolTip:L(@"Let local Claude Code / Codex sessions message and wake each other and reserve files")];
1536
- if (!enabled) return;
1537
-
1538
- // 状态放在"启用"行的第二行,省掉底部单独的状态行和分隔线。开关上移与标题对齐,
1539
- // 状态文字才能占满整行宽度,不被开关截断。
1540
- NSDictionary *sessions = CCBridgeSessions();
1541
- NSUInteger reservations = CCBridgeActiveReservationCount([NSSet setWithArray:sessions.allKeys]);
1542
- MenuHintRowView *enableRow = (MenuHintRowView *)bridgeMenu.itemArray.lastObject.view;
1543
- enableRow.hint = [enableRow.hint stringByAppendingString:L(@"\nBelow: online sessions · active file reservations")];
1544
- const CGFloat statusHeight = 14;
1545
- [enableRow setFrameSize:NSMakeSize(NSWidth(enableRow.frame), NSHeight(enableRow.frame) + statusHeight)];
1546
- for (NSView *subview in enableRow.subviews) {
1547
- [subview setFrameOrigin:NSMakePoint(NSMinX(subview.frame), NSMinY(subview.frame) + statusHeight - 2)];
1548
- }
1549
- NSTextField *status = [NSTextField labelWithString:[NSString stringWithFormat:L(@"%lu sessions · %lu reserved"),
1550
- (unsigned long)sessions.count, (unsigned long)reservations]];
1551
- status.frame = NSMakeRect(12, 4, NSWidth(enableRow.frame) - 12 - PetMenuControlGap, statusHeight);
1552
- status.font = [NSFont menuFontOfSize:11];
1553
- status.textColor = NSColor.secondaryLabelColor;
1554
- status.lineBreakMode = NSLineBreakByTruncatingTail;
1555
- status.autoresizingMask = NSViewWidthSizable;
1556
- [enableRow addSubview:status];
1557
-
1558
- [bridgeMenu addItem:NSMenuItem.separatorItem];
1559
- NSDictionary *options = CCBridgeOptions();
1560
- [self addBridgeSwitchToMenu:bridgeMenu title:L(@"Auto-wake") checked:[options[@"wake"] boolValue]
1561
- action:@selector(toggleBridgeWake:) tag:0
1562
- toolTip:L(@"Wake idle sessions automatically. When off, messages wait in the inbox until that session's next input, which saves tokens. Codex needs a session restart")];
1563
- [self addBridgeSwitchToMenu:bridgeMenu title:L(@"Edit guard") checked:[options[@"editGuard"] boolValue]
1564
- action:@selector(toggleBridgeEditGuard:) tag:0
1565
- toolTip:L(@"Pause once with an explanation when editing a file another session reserved; retrying goes through. Codex needs a session restart")];
1566
-
1567
- NSMenuItem *approvalItem = [bridgeMenu addItemWithTitle:L(@"Auto-approve") action:nil keyEquivalent:@""];
1568
- approvalItem.representedObject = L(@"Each group applies to both Codex approvals and Claude permissions. Codex needs a session restart");
1569
- NSMenu *approvalMenu = [NSMenu new];
1570
- NSArray<NSDictionary *> *groups = @[
1571
- @{@"title": L(@"Read"), @"group": @"view", @"tag": @1,
1572
- @"tip": L(@"Listing sessions, viewing reservations and reading the inbox. Read-only and safe")},
1573
- @{@"title": L(@"Send"), @"group": @"send", @"tag": @2,
1574
- @"tip": L(@"When on, Agents can message other sessions without asking")},
1575
- @{@"title": L(@"Reserve"), @"group": @"reserve", @"tag": @3,
1576
- @"tip": L(@"Reserving and releasing files")},
1577
- @{@"title": L(@"Rename"), @"group": @"name", @"tag": @4,
1578
- @"tip": L(@"Renaming the current session in CC Bridge")}
1579
- ];
1580
- NSSet *codex = [NSSet setWithArray:options[@"codexApprove"]];
1581
- NSSet *claude = [NSSet setWithArray:options[@"claudeAllow"]];
1582
- for (NSDictionary *group in groups) {
1583
- NSSet *tools = [NSSet setWithArray:CCBridgeToolGroup(group[@"group"])];
1584
- BOOL checked = tools.count > 0 && [tools isSubsetOfSet:codex] && [tools isSubsetOfSet:claude];
1585
- [self addBridgeSwitchToMenu:approvalMenu title:group[@"title"] checked:checked
1586
- action:@selector(toggleBridgeApproval:) tag:[group[@"tag"] integerValue] toolTip:group[@"tip"]];
1587
- }
1588
- approvalItem.submenu = approvalMenu;
1589
-
1590
- NSMenuItem *alertItem = [bridgeMenu addItemWithTitle:L(@"Pet alerts") action:nil keyEquivalent:@""];
1591
- alertItem.representedObject = L(@"Only affects the pet, not Claude Code / Codex settings");
1592
- NSMenu *alertMenu = [NSMenu new];
1593
- [self addBridgeSwitchToMenu:alertMenu title:L(@"Badge")
1594
- checked:[NSUserDefaults.standardUserDefaults boolForKey:BridgeBadgeEnabledKey]
1595
- action:@selector(toggleBridgeBadge:) tag:0
1596
- toolTip:L(@"Bottom-right of the status icon: blue for new deliveries, orange for a backed-up inbox")];
1597
- [self addBridgeSwitchToMenu:alertMenu title:L(@"Notify")
1598
- checked:[NSUserDefaults.standardUserDefaults boolForKey:BridgeNotificationKey]
1599
- action:@selector(toggleBridgeNotification:) tag:0
1600
- toolTip:L(@"Send a notification when a message is delivered between sessions (sender and recipient only, no content)")];
1601
- alertItem.submenu = alertMenu;
1602
- }
1603
- - (void)rightMouseDown:(NSEvent *)event {
1604
- NSArray<NSDictionary *> *availablePets = self.petOptionsRequested ? self.petOptionsRequested() : @[];
1605
- NSMenu *menu = [NSMenu new];
1606
- menu.minimumWidth = 194.0;
1607
- NSMenuItem *switchItem = [menu addItemWithTitle:L(@"Pets") action:nil keyEquivalent:@""];
1608
- NSMenu *switchMenu = [NSMenu new];
1609
- switchMenu.delegate = self;
1610
- for (NSDictionary *pet in availablePets) {
1611
- [self addPetOption:pet toMenu:switchMenu];
1612
- }
1613
- self.activePetSwitchMenu = switchMenu;
1614
- switchItem.submenu = switchMenu;
1615
- NSMenuItem *sizeItem = [menu addItemWithTitle:L(@"Pet Size") action:nil keyEquivalent:@""];
1616
- NSMenu *sizeMenu = [[NSMenu alloc] initWithTitle:L(@"Pet Size")];
1617
- NSMenuItem *sizeControl = [[NSMenuItem alloc] initWithTitle:L(@"Pet Size")
1618
- action:nil keyEquivalent:@""];
1619
- sizeControl.view = [[MenuPetSizeView alloc] initWithScale:CCPetsPetScalePreference()
1620
- target:NSApp.delegate action:@selector(setPetSizeFromSlider:)];
1621
- [sizeMenu addItem:sizeControl];
1622
- sizeItem.submenu = sizeMenu;
1623
- [menu addItem:NSMenuItem.separatorItem];
1624
- [self addPersistentSwitchToMenu:menu
1625
- title:L(@"Show Status Card")
1626
- checked:[NSUserDefaults.standardUserDefaults boolForKey:StatusBubbleExpandedKey]
1627
- action:@selector(toggleStatusBubbleFromMenu:)
1628
- width:PetMenuRowWidth
1629
- tag:0];
1630
- [self addPersistentSwitchToMenu:menu
1631
- title:L(@"Import Codex Pets")
1632
- checked:[NSUserDefaults.standardUserDefaults boolForKey:ImportCodexPetsKey]
1633
- action:@selector(toggleImportCodexPets:)
1634
- width:PetMenuRowWidth
1635
- tag:0];
1636
- NSMenuItem *usageModeItem = [menu addItemWithTitle:L(@"Usage Display") action:nil keyEquivalent:@""];
1637
- NSMenu *usageModeMenu = [NSMenu new];
1638
- [self addUsageModeControlToMenu:usageModeMenu provider:@"Codex"
1639
- preferenceKey:CodexUsageDisplayModeKey tag:1];
1640
- [self addUsageModeControlToMenu:usageModeMenu provider:@"Claude"
1641
- preferenceKey:ClaudeUsageDisplayModeKey tag:2];
1642
- usageModeItem.submenu = usageModeMenu;
1643
- NSMenuItem *themeItem = [menu addItemWithTitle:L(@"Panel Theme") action:nil keyEquivalent:@""];
1644
- NSMenu *themeMenu = [[NSMenu alloc] initWithTitle:L(@"Panel Theme")];
1645
- // 两组都用自绘单选行:点了立即生效且菜单不收起,方便连着对比主题和压暗档位。
1646
- NSString *selectedTheme = CCPetsPanelTheme();
1647
- for (NSArray<NSString *> *option in @[
1648
- @[L(@"Classic"), @"classic"], @[@"Liquid Glass", @"liquid"]]) {
1649
- NSMenuItem *item = [MenuChoiceRowView addToMenu:themeMenu title:option[0] group:@"theme"
1650
- representedObject:option[1] checked:[selectedTheme isEqualToString:option[1]]
1651
- target:NSApp.delegate action:@selector(setPanelTheme:) width:PetSubmenuRowWidth];
1652
- if ([option[1] isEqualToString:@"liquid"] && !CCPetsLiquidGlassAvailable()) {
1653
- ((MenuChoiceRowView *)item.view).enabled = NO;
1654
- [item.view setAccessibilityHelp:L(@"Requires macOS 26 or later")];
1655
- }
1656
- }
1657
- // 压暗作用于额度面板、状态卡和说话气泡的原生玻璃;经典主题下没有这层,置灰。切主题时当场联动。
1658
- [themeMenu addItem:NSMenuItem.separatorItem];
1659
- NSMenuItem *dimHeader = [themeMenu addItemWithTitle:L(@"Glass Dimming") action:nil keyEquivalent:@""];
1660
- dimHeader.enabled = NO;
1661
- BOOL (^dimApplies)(void) = ^BOOL {
1662
- return [CCPetsPanelTheme() isEqualToString:@"liquid"] && CCPetsLiquidGlassAvailable();
1663
- };
1664
- NSDictionary<NSNumber *, NSString *> *dimTitles = @{
1665
- @0: L(@"Clear (0%)"), @15: L(@"Light (15%)"), @25: L(@"Standard (25%)"), @45: L(@"Legible (45%)")};
1666
- NSInteger selectedDim = CCPetsGlassDimLevel();
1667
- for (NSNumber *level in CCPetsGlassDimLevels()) {
1668
- NSMenuItem *item = [MenuChoiceRowView addToMenu:themeMenu title:dimTitles[level] group:@"dim"
1669
- representedObject:level checked:level.integerValue == selectedDim
1670
- target:NSApp.delegate action:@selector(setGlassDimLevel:) width:PetSubmenuRowWidth];
1671
- MenuChoiceRowView *row = (MenuChoiceRowView *)item.view;
1672
- row.indentation = 10;
1673
- row.enabledHandler = dimApplies;
1674
- row.enabled = dimApplies();
1675
- }
1676
- themeItem.submenu = themeMenu;
1677
- NSMenuItem *notificationItem = [menu addItemWithTitle:L(@"Notifications") action:nil keyEquivalent:@""];
1678
- NSMenu *notificationMenu = [NSMenu new];
1679
- NSArray<NSDictionary *> *notificationOptions = @[
1680
- @{@"title": L(@"Task done"), @"key": NotificationCompletionKey, @"tag": @1},
1681
- @{@"title": L(@"Task failed"), @"key": NotificationFailureKey, @"tag": @2},
1682
- @{@"title": L(@"Awaiting approval"), @"key": NotificationApprovalKey, @"tag": @3},
1683
- @{@"title": L(@"Stalled"), @"key": NotificationStallKey, @"tag": @4}
1684
- ];
1685
- for (NSDictionary *option in notificationOptions) {
1686
- [self addPersistentSwitchToMenu:notificationMenu
1687
- title:option[@"title"]
1688
- checked:[NSUserDefaults.standardUserDefaults boolForKey:option[@"key"]]
1689
- action:@selector(toggleNotification:)
1690
- width:PetSubmenuRowWidth
1691
- tag:[option[@"tag"] integerValue]];
1692
- }
1693
- notificationItem.submenu = notificationMenu;
1694
- [self addBridgeMenuToMenu:menu];
1695
- NSMenuItem *interactionItem = [menu addItemWithTitle:L(@"Click Reactions") action:nil keyEquivalent:@""];
1696
- NSMenu *interactionMenu = [NSMenu new];
1697
- [self addPersistentSwitchToMenu:interactionMenu
1698
- title:L(@"Enable reactions")
1699
- checked:[NSUserDefaults.standardUserDefaults boolForKey:PetInteractionEnabledKey]
1700
- action:@selector(togglePetInteraction:)
1701
- width:PetSubmenuRowWidth
1702
- tag:1];
1703
- NSArray<NSDictionary *> *interactionGroups = @[
1704
- @{@"title": L(@"Hearts After"), @"key": PetInteractionHeartThresholdKey,
1705
- @"action": NSStringFromSelector(@selector(setPetInteractionHeartThreshold:)),
1706
- @"values": @[@3, @5, @7], @"suffix": L(@" clicks")},
1707
- @{@"title": L(@"Annoyed After"), @"key": PetInteractionAnnoyedThresholdKey,
1708
- @"action": NSStringFromSelector(@selector(setPetInteractionAnnoyedThreshold:)),
1709
- @"values": @[@10, @12, @15], @"suffix": L(@" clicks")},
1710
- @{@"title": L(@"Click Window"), @"key": PetInteractionIntervalKey,
1711
- @"action": NSStringFromSelector(@selector(setPetInteractionInterval:)),
1712
- @"values": @[@0.8, @1.2, @1.8], @"suffix": L(@" s")},
1713
- ];
1714
- for (NSDictionary *group in interactionGroups) {
1715
- NSMenuItem *groupItem = [interactionMenu addItemWithTitle:group[@"title"]
1716
- action:nil keyEquivalent:@""];
1717
- NSMenu *options = [NSMenu new];
1718
- NSNumber *current = [NSUserDefaults.standardUserDefaults objectForKey:group[@"key"]];
1719
- for (NSNumber *value in group[@"values"]) {
1720
- NSString *number = value.doubleValue == value.integerValue ?
1721
- [NSString stringWithFormat:@"%ld", (long)value.integerValue] :
1722
- [NSString stringWithFormat:@"%.1f", value.doubleValue];
1723
- [MenuChoiceRowView addToMenu:options
1724
- title:[number stringByAppendingString:group[@"suffix"]] group:group[@"key"]
1725
- representedObject:value checked:fabs(current.doubleValue - value.doubleValue) < 0.001
1726
- target:NSApp.delegate action:NSSelectorFromString(group[@"action"])
1727
- width:PetSubmenuRowWidth];
1728
- }
1729
- groupItem.submenu = options;
1730
- }
1731
- [interactionMenu addItem:NSMenuItem.separatorItem];
1732
- NSMenuItem *editInteractionPhrases = [interactionMenu addItemWithTitle:L(@"Edit Reaction Lines…")
1733
- action:@selector(editPhrasesFile:) keyEquivalent:@""];
1734
- editInteractionPhrases.target = NSApp.delegate;
1735
- interactionItem.submenu = interactionMenu;
1736
- NSMenuItem *systemStatusItem = [menu addItemWithTitle:L(@"System Status") action:nil keyEquivalent:@""];
1737
- NSMenu *systemStatusMenu = [NSMenu new];
1738
- NSArray<NSDictionary *> *systemStatusOptions = @[
1739
- @{@"title": L(@"CPU usage"), @"key": SystemCPUEnabledKey, @"tag": @1},
1740
- @{@"title": L(@"CPU temp"), @"key": SystemTemperatureEnabledKey, @"tag": @2},
1741
- @{@"title": L(@"Memory"), @"key": SystemMemoryEnabledKey, @"tag": @3}
1742
- ];
1743
- for (NSDictionary *option in systemStatusOptions) {
1744
- [self addPersistentSwitchToMenu:systemStatusMenu
1745
- title:option[@"title"]
1746
- checked:[NSUserDefaults.standardUserDefaults boolForKey:option[@"key"]]
1747
- action:@selector(toggleSystemMetric:)
1748
- width:PetSubmenuRowWidth
1749
- tag:[option[@"tag"] integerValue]];
1750
- }
1751
- systemStatusItem.submenu = systemStatusMenu;
1752
- NSMenuItem *speechItem = [menu addItemWithTitle:L(@"Chatter") action:nil keyEquivalent:@""];
1753
- NSMenu *speechMenu = [NSMenu new];
1754
- id speechValue = [NSUserDefaults.standardUserDefaults objectForKey:@"CCPetsSpeechEnabled"];
1755
- [self addPersistentSwitchToMenu:speechMenu
1756
- title:L(@"Enable chatter")
1757
- checked:speechValue == nil ? YES : [speechValue boolValue]
1758
- action:@selector(toggleSpeech:)
1759
- width:PetSubmenuRowWidth
1760
- tag:1];
1761
- // 频率是四道闸的组合,单调任何一道都不会真的变频繁,所以只给一个档位。
1762
- // 单选行负责互斥勾选,鼠标点击后保持菜单展开。
1763
- NSMenuItem *frequencyItem = [speechMenu addItemWithTitle:L(@"Frequency") action:nil keyEquivalent:@""];
1764
- NSMenu *frequencyMenu = [NSMenu new];
1765
- NSString *frequency = [NSUserDefaults.standardUserDefaults
1766
- stringForKey:PetSpeechFrequencyKey] ?: @"normal";
1767
- NSArray<NSDictionary *> *frequencyOptions = @[
1768
- @{@"title": L(@"Rarely"), @"value": @"low"},
1769
- @{@"title": L(@"Normal"), @"value": @"normal"},
1770
- @{@"title": L(@"Often"), @"value": @"high"},
1771
- @{@"title": L(@"Chatty"), @"value": @"chatty"},
1772
- ];
1773
- for (NSDictionary *option in frequencyOptions) {
1774
- [MenuChoiceRowView addToMenu:frequencyMenu title:option[@"title"] group:@"speechFrequency"
1775
- representedObject:option[@"value"] checked:[frequency isEqualToString:option[@"value"]]
1776
- target:NSApp.delegate action:@selector(setSpeechFrequency:) width:PetSubmenuRowWidth];
1777
- }
1778
- frequencyItem.submenu = frequencyMenu;
1779
- NSMenuItem *sourceItem = [speechMenu addItemWithTitle:L(@"Line Source")
1780
- action:nil keyEquivalent:@""];
1781
- NSMenu *sourceMenu = [NSMenu new];
1782
- NSString *source = PetPhrasesSource();
1783
- for (NSArray<NSString *> *option in @[
1784
- @[L(@"Pet-specific Lines"), PetPhrasesSourcePet],
1785
- @[L(@"Default Lines"), PetPhrasesSourceDefault]]) {
1786
- [MenuChoiceRowView addToMenu:sourceMenu title:option[0] group:@"phrasesSource"
1787
- representedObject:option[1] checked:[source isEqualToString:option[1]]
1788
- target:NSApp.delegate action:@selector(setPhrasesSource:) width:PetSubmenuRowWidth];
1789
- }
1790
- sourceItem.submenu = sourceMenu;
1791
- // 没有这个入口,九成用户不会知道台词可以自己改。
1792
- NSMenuItem *editPhrases = [speechMenu addItemWithTitle:L(@"Edit Lines…")
1793
- action:@selector(editPhrasesFile:) keyEquivalent:@""];
1794
- editPhrases.target = NSApp.delegate;
1795
- speechItem.submenu = speechMenu;
1796
- // 检查更新和关于收进「帮助」;有新版本时在顶层临时多一项「更新到 x.y.z…」,一步就能更新,
1797
- // 不必展开子菜单。气泡和角标错过了,这里仍是醒目的入口。
1798
- NSString *pendingVersion = self.pendingUpdateVersionRequested ? self.pendingUpdateVersionRequested() : nil;
1799
- if (pendingVersion.length > 0) {
1800
- NSMenuItem *installItem = [menu addItemWithTitle:
1801
- [NSString stringWithFormat:L(@"Update to %@…"), pendingVersion]
1802
- action:@selector(showPendingUpdate:) keyEquivalent:@""];
1803
- installItem.target = NSApp.delegate;
1804
- }
1805
- // 语言名用各自的写法,不跟着界面语言翻译:切错了语言的人也要认得出回去的那一项。
1806
- NSMenuItem *languageItem = [menu addItemWithTitle:L(@"Language") action:nil keyEquivalent:@""];
1807
- NSMenu *languageMenu = [NSMenu new];
1808
- NSString *languagePreference = CCPetsLanguagePreference();
1809
- NSMutableArray<NSArray<NSString *> *> *languageOptions =
1810
- [NSMutableArray arrayWithObject:@[L(@"System Default"), CCPetsLanguageSystem]];
1811
- // 有哪些语言由打包进来的 .lproj 决定,加一种语言不用改这里。
1812
- for (NSString *language in CCPetsSupportedLanguages()) {
1813
- [languageOptions addObject:@[CCPetsLanguageDisplayName(language), language]];
1814
- }
1815
- for (NSArray<NSString *> *option in languageOptions) {
1816
- NSMenuItem *item = [languageMenu addItemWithTitle:option[0]
1817
- action:@selector(setLanguagePreferenceFromMenu:) keyEquivalent:@""];
1818
- item.target = NSApp.delegate;
1819
- item.representedObject = option[1];
1820
- item.state = [languagePreference isEqualToString:option[1]] ?
1821
- NSControlStateValueOn : NSControlStateValueOff;
1822
- }
1823
- languageItem.submenu = languageMenu;
1824
- NSMenuItem *helpItem = [menu addItemWithTitle:L(@"Help") action:nil keyEquivalent:@""];
1825
- NSMenu *helpMenu = [NSMenu new];
1826
- NSMenuItem *updateItem = [helpMenu addItemWithTitle:L(@"Check for Updates…") action:@selector(checkForUpdates:) keyEquivalent:@""];
1827
- updateItem.target = NSApp.delegate;
1828
- NSMenuItem *aboutItem = [helpMenu addItemWithTitle:L(@"About CC Pets") action:@selector(showAboutPanel:) keyEquivalent:@""];
1829
- aboutItem.target = NSApp.delegate;
1830
- helpItem.submenu = helpMenu;
1831
- [menu addItem:NSMenuItem.separatorItem];
1832
- NSMenuItem *quitItem = [menu addItemWithTitle:L(@"Quit CC Pets") action:@selector(terminate:) keyEquivalent:@"q"];
1833
- quitItem.target = NSApp;
1834
- [NSMenu popUpContextMenu:menu withEvent:event forView:self];
1835
- [MenuHint cancel];
1836
- self.activePetSwitchMenu = nil;
1837
- [self.petMenuPreviewPanel orderOut:nil];
1838
- }
1839
- @end