cc-pets 1.3.3 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,369 @@
1
+ #import "CCPetsPhrasesEditor.h"
2
+ #import "CCPetsPhrases.h"
3
+
4
+ static void (^PetPhrasesSpeakHandler)(NSString *);
5
+
6
+ @interface PetPhrasesEditorController () <NSTextViewDelegate>
7
+ @property NSTextView *textView;
8
+ @property NSPopUpButton *tagPicker;
9
+ @property NSTextField *statusLabel;
10
+ @property NSButton *saveButton;
11
+ @property NSButton *saveAndCloseButton;
12
+ // 载入时文件的 mtime。保存前比一次,防止把外部编辑器的改动直接盖掉。
13
+ @property NSDate *loadedStamp;
14
+ @end
15
+
16
+ @implementation PetPhrasesEditorController
17
+
18
+ + (instancetype)shared {
19
+ static PetPhrasesEditorController *shared;
20
+ static dispatch_once_t once;
21
+ dispatch_once(&once, ^{ shared = [PetPhrasesEditorController new]; });
22
+ return shared;
23
+ }
24
+
25
+ + (void)setSpeakHandler:(void (^)(NSString *))handler {
26
+ PetPhrasesSpeakHandler = [handler copy];
27
+ }
28
+
29
+ + (void)present {
30
+ PetPhrasesEditorController *controller = [self shared];
31
+ [controller buildWindowIfNeeded];
32
+ [controller reloadFromDisk];
33
+ [NSApp activateIgnoringOtherApps:YES];
34
+ [controller.window makeKeyAndOrderFront:nil];
35
+ [controller.window makeFirstResponder:controller.textView];
36
+ [controller offerToRemoveLegacyFile];
37
+ }
38
+
39
+ // 老词库在启动时已经合并进新文件了(见 PetPhrasesEnsureFileExists),但老文件还留着。
40
+ // 在这里问一次要不要收起来:合并是我们替用户做的,动他的文件必须他自己点头。
41
+ //
42
+ // 他选"先留着"的话下次打开还会问。留着原名不动有两个坑:改它不会有任何效果;
43
+ // 而且哪天 speech.txt 丢了,启动时会再从它合并一遍,把迁移之后写的台词全冲掉。
44
+ - (void)offerToRemoveLegacyFile {
45
+ if (!PetPhrasesLegacyFileExists()) return;
46
+
47
+ NSString *legacy = PetPhrasesLegacyFilePath();
48
+ NSAlert *alert = [NSAlert new];
49
+ alert.messageText = @"旧的台词文件已更新";
50
+ alert.informativeText = [NSString stringWithFormat:
51
+ @"正在使用的台词全部保留并合并到 %@。\n\n"
52
+ "旧文件 %@ 已经失效,后续修改不会有任何效果。"
53
+ "可以把它改名成 %@.bak 收起来,内容还留在原地。",
54
+ PetPhrasesFilePath(), legacy, legacy.lastPathComponent];
55
+ [alert addButtonWithTitle:@"改名收起来"];
56
+ [alert addButtonWithTitle:@"先留着"];
57
+ if ([alert runModal] != NSAlertFirstButtonReturn) return;
58
+ if (PetPhrasesArchiveLegacyFile()) {
59
+ [self showStatus:[NSString stringWithFormat:@"旧文件已改名成 %@.bak。",
60
+ legacy.lastPathComponent] warning:NO];
61
+ } else {
62
+ [self showStatus:@"旧文件改名失败,可以手动改。" warning:YES];
63
+ }
64
+ }
65
+
66
+ #pragma mark - 界面
67
+
68
+ - (void)buildWindowIfNeeded {
69
+ if (self.window) return;
70
+
71
+ NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 620, 640)
72
+ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
73
+ NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
74
+ backing:NSBackingStoreBuffered defer:NO];
75
+ window.title = @"桌宠台词";
76
+ window.releasedWhenClosed = NO;
77
+ window.minSize = NSMakeSize(460, 400);
78
+ [window center];
79
+
80
+ NSView *root = window.contentView;
81
+
82
+ NSScrollView *scroll = [[NSScrollView alloc] initWithFrame:NSZeroRect];
83
+ scroll.hasVerticalScroller = YES;
84
+ scroll.autohidesScrollers = YES;
85
+ scroll.borderType = NSNoBorder;
86
+ scroll.translatesAutoresizingMaskIntoConstraints = NO;
87
+
88
+ NSTextView *textView = [[NSTextView alloc] initWithFrame:NSZeroRect];
89
+ textView.minSize = NSMakeSize(0, 0);
90
+ textView.maxSize = NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX);
91
+ textView.verticallyResizable = YES;
92
+ textView.horizontallyResizable = NO;
93
+ textView.autoresizingMask = NSViewWidthSizable;
94
+ textView.textContainer.widthTracksTextView = YES;
95
+ textView.font = [NSFont monospacedSystemFontOfSize:13 weight:NSFontWeightRegular];
96
+ // 台词是纯文本:富文本会把粘贴进来的字体样式一起带进文件。
97
+ textView.richText = NO;
98
+ textView.allowsUndo = YES;
99
+ // 智能引号会把英文引号换成弯引号、破折号会被合并——台词里无所谓,
100
+ // 但 {slot} 这类记号一旦被"智能"处理过就再也对不上白名单了。
101
+ textView.automaticQuoteSubstitutionEnabled = NO;
102
+ textView.automaticDashSubstitutionEnabled = NO;
103
+ textView.automaticTextReplacementEnabled = NO;
104
+ textView.automaticSpellingCorrectionEnabled = NO;
105
+ textView.textContainerInset = NSMakeSize(8, 10);
106
+ textView.delegate = self;
107
+ scroll.documentView = textView;
108
+ self.textView = textView;
109
+
110
+ NSTextField *status = [NSTextField labelWithString:@""];
111
+ status.font = [NSFont systemFontOfSize:11];
112
+ status.textColor = NSColor.secondaryLabelColor;
113
+ status.lineBreakMode = NSLineBreakByTruncatingTail;
114
+ status.translatesAutoresizingMaskIntoConstraints = NO;
115
+ self.statusLabel = status;
116
+
117
+ NSPopUpButton *picker = [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO];
118
+ picker.translatesAutoresizingMaskIntoConstraints = NO;
119
+ for (NSString *tag in PetPhraseAllTags()) {
120
+ [picker addItemWithTitle:[NSString stringWithFormat:@"%@(%@)",
121
+ PetPhraseTagDescription(tag), tag]];
122
+ picker.lastItem.representedObject = tag;
123
+ }
124
+ self.tagPicker = picker;
125
+
126
+ NSButton *speak = [NSButton buttonWithTitle:@"试说一句" target:self
127
+ action:@selector(speakSample:)];
128
+ speak.translatesAutoresizingMaskIntoConstraints = NO;
129
+
130
+ NSButton *save = [NSButton buttonWithTitle:@"保存" target:self action:@selector(save:)];
131
+ // ⌘S 而不是回车:这是个多行文本编辑器,回车要用来换行。
132
+ save.keyEquivalent = @"s";
133
+ save.keyEquivalentModifierMask = NSEventModifierFlagCommand;
134
+ save.translatesAutoresizingMaskIntoConstraints = NO;
135
+ self.saveButton = save;
136
+
137
+ NSButton *saveAndClose = [NSButton buttonWithTitle:@"保存并关闭" target:self
138
+ action:@selector(saveAndClose:)];
139
+ saveAndClose.keyEquivalent = @"\r";
140
+ saveAndClose.translatesAutoresizingMaskIntoConstraints = NO;
141
+ self.saveAndCloseButton = saveAndClose;
142
+
143
+ NSButton *revert = [NSButton buttonWithTitle:@"恢复出厂台词…" target:self
144
+ action:@selector(revertToDefault:)];
145
+ revert.translatesAutoresizingMaskIntoConstraints = NO;
146
+
147
+ for (NSView *view in @[scroll, status, picker, speak, save, saveAndClose, revert]) {
148
+ [root addSubview:view];
149
+ }
150
+
151
+ [NSLayoutConstraint activateConstraints:@[
152
+ [scroll.topAnchor constraintEqualToAnchor:root.topAnchor],
153
+ [scroll.leadingAnchor constraintEqualToAnchor:root.leadingAnchor],
154
+ [scroll.trailingAnchor constraintEqualToAnchor:root.trailingAnchor],
155
+ [scroll.bottomAnchor constraintEqualToAnchor:status.topAnchor constant:-8],
156
+
157
+ [status.leadingAnchor constraintEqualToAnchor:root.leadingAnchor constant:16],
158
+ [status.trailingAnchor constraintEqualToAnchor:root.trailingAnchor constant:-16],
159
+ [status.bottomAnchor constraintEqualToAnchor:picker.topAnchor constant:-8],
160
+
161
+ [picker.leadingAnchor constraintEqualToAnchor:root.leadingAnchor constant:16],
162
+ [picker.bottomAnchor constraintEqualToAnchor:root.bottomAnchor constant:-14],
163
+ [picker.widthAnchor constraintLessThanOrEqualToConstant:240],
164
+ [speak.leadingAnchor constraintEqualToAnchor:picker.trailingAnchor constant:8],
165
+ [speak.centerYAnchor constraintEqualToAnchor:picker.centerYAnchor],
166
+ [revert.leadingAnchor constraintGreaterThanOrEqualToAnchor:speak.trailingAnchor constant:8],
167
+ [revert.trailingAnchor constraintEqualToAnchor:save.leadingAnchor constant:-8],
168
+ [revert.centerYAnchor constraintEqualToAnchor:picker.centerYAnchor],
169
+ [save.trailingAnchor constraintEqualToAnchor:saveAndClose.leadingAnchor constant:-8],
170
+ [save.centerYAnchor constraintEqualToAnchor:picker.centerYAnchor],
171
+ [saveAndClose.trailingAnchor constraintEqualToAnchor:root.trailingAnchor constant:-16],
172
+ [saveAndClose.centerYAnchor constraintEqualToAnchor:picker.centerYAnchor],
173
+ ]];
174
+
175
+ self.window = window;
176
+ }
177
+
178
+ #pragma mark - 读写
179
+
180
+ - (void)reloadFromDisk {
181
+ PetPhrasesEnsureFileExists();
182
+ NSString *path = PetPhrasesFilePath();
183
+ NSString *text = [NSString stringWithContentsOfFile:path
184
+ encoding:NSUTF8StringEncoding error:nil] ?: @"";
185
+ self.textView.string = text;
186
+ self.loadedStamp = [NSFileManager.defaultManager attributesOfItemAtPath:path
187
+ error:nil][NSFileModificationDate];
188
+ [self showStatus:[NSString stringWithFormat:@"%@", path] warning:NO];
189
+ }
190
+
191
+ - (void)showStatus:(NSString *)message warning:(BOOL)warning {
192
+ self.statusLabel.stringValue = message ?: @"";
193
+ self.statusLabel.textColor = warning ? NSColor.systemOrangeColor :
194
+ NSColor.secondaryLabelColor;
195
+ }
196
+
197
+ - (void)save:(id)sender {
198
+ [self performSave];
199
+ }
200
+
201
+ // 保存成功才关窗。失败或被用户取消时留在原地,否则用户的改动会连同窗口一起消失。
202
+ - (void)saveAndClose:(id)sender {
203
+ if (![self performSave]) return;
204
+ [self.window close];
205
+ }
206
+
207
+ // 保存时校验,不做实时校验——边打边标红只会干扰输入,而且写到一半的行必然是"错"的。
208
+ // 返回是否真的写进了文件(被校验拦下、被 mtime 冲突取消都算没写)。
209
+ - (BOOL)performSave {
210
+ // 标签被删掉时先补回原位再校验。
211
+ //
212
+ // 只报错是把人卡死:编辑器里已经看不到那一行了,用户既不知道少的是哪个,也不知道
213
+ // 该写成什么样,只能去翻文档或者点"恢复出厂"把自己的改动全丢掉。
214
+ NSArray<NSString *> *restored = nil;
215
+ NSString *text = self.textView.string ?: @"";
216
+ NSString *repaired = PetPhraseTextWithRestoredTags(text, &restored);
217
+ if (restored.count > 0) {
218
+ // 走 shouldChangeTextInRange: 让这一步能被 ⌘Z 撤销,用户不满意可以退回去。
219
+ NSRange all = NSMakeRange(0, text.length);
220
+ if ([self.textView shouldChangeTextInRange:all replacementString:repaired]) {
221
+ [self.textView.textStorage replaceCharactersInRange:all withString:repaired];
222
+ [self.textView didChangeText];
223
+ text = repaired;
224
+ }
225
+ }
226
+
227
+ NSArray<PetPhraseIssue *> *issues = PetPhraseValidateText(text);
228
+ if (PetPhraseIssuesHaveError(issues)) {
229
+ [self presentIssues:issues blocking:YES restored:restored];
230
+ return NO;
231
+ }
232
+ if (![self confirmNoExternalChange]) return NO;
233
+
234
+ NSString *path = PetPhrasesFilePath();
235
+ NSError *error = nil;
236
+ // 结尾补一个换行:没有的话下次追加小节会直接粘在最后一句后面。
237
+ NSString *normalized = [text hasSuffix:@"\n"] ? text : [text stringByAppendingString:@"\n"];
238
+ if (![normalized writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
239
+ [self showStatus:[NSString stringWithFormat:@"保存失败:%@",
240
+ error.localizedDescription ?: @"未知原因"] warning:YES];
241
+ return NO;
242
+ }
243
+ self.loadedStamp = [NSFileManager.defaultManager attributesOfItemAtPath:path
244
+ error:nil][NSFileModificationDate];
245
+
246
+ if (issues.count > 0 || restored.count > 0) {
247
+ [self presentIssues:issues blocking:NO restored:restored];
248
+ [self showStatus:restored.count > 0 ?
249
+ [NSString stringWithFormat:@"已保存,补回了 %lu 个标签", (unsigned long)restored.count] :
250
+ [NSString stringWithFormat:@"已保存,有 %lu 处提示", (unsigned long)issues.count]
251
+ warning:YES];
252
+ return YES;
253
+ }
254
+ [self showStatus:@"已保存,立刻生效。" warning:NO];
255
+ return YES;
256
+ }
257
+
258
+ // 外部编辑器可能同时改了这个文件。直接覆盖会静默吃掉别人的改动,所以问一次。
259
+ - (BOOL)confirmNoExternalChange {
260
+ NSDate *current = [NSFileManager.defaultManager
261
+ attributesOfItemAtPath:PetPhrasesFilePath() error:nil][NSFileModificationDate];
262
+ if (!current || !self.loadedStamp || [current isEqualToDate:self.loadedStamp]) return YES;
263
+
264
+ NSAlert *alert = [NSAlert new];
265
+ alert.messageText = @"文件在外部被改过";
266
+ alert.informativeText = @"打开编辑器之后,台词文件被别的程序修改了。"
267
+ "继续保存会覆盖掉那些改动。";
268
+ [alert addButtonWithTitle:@"覆盖"];
269
+ [alert addButtonWithTitle:@"取消"];
270
+ [alert addButtonWithTitle:@"重新载入"];
271
+ NSModalResponse response = [alert runModal];
272
+ if (response == NSAlertSecondButtonReturn) return NO;
273
+ if (response == NSAlertThirdButtonReturn) {
274
+ [self reloadFromDisk];
275
+ return NO;
276
+ }
277
+ return YES;
278
+ }
279
+
280
+ - (void)presentIssues:(NSArray<PetPhraseIssue *> *)issues blocking:(BOOL)blocking
281
+ restored:(NSArray<NSString *> *)restored {
282
+ NSMutableArray<NSString *> *lines = [NSMutableArray array];
283
+ // 补回标签这件事必须说在最前面:用户看到的文本被我们改过了,不说清楚就是偷偷动手。
284
+ if (restored.count > 0) {
285
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
286
+ for (NSString *tag in restored) {
287
+ [names addObject:[NSString stringWithFormat:@"[%@](%@)", tag,
288
+ PetPhraseTagDescription(tag)]];
289
+ }
290
+ [lines addObject:[NSString stringWithFormat:
291
+ @"标签不能删,已经帮你把 %@ 加回原位了(⌘Z 可撤销)。",
292
+ [names componentsJoinedByString:@"、"]]];
293
+ [lines addObject:@""];
294
+ }
295
+ for (PetPhraseIssue *issue in issues) {
296
+ NSString *prefix = issue.level == PetPhraseIssueLevelError ? @"必须改:" : @"提示:";
297
+ NSString *where = issue.line > 0 ?
298
+ [NSString stringWithFormat:@"第 %ld 行 ", (long)issue.line] : @"";
299
+ [lines addObject:[NSString stringWithFormat:@"%@%@%@", prefix, where, issue.message]];
300
+ // 一屏放不下就没人看了,剩下的等改完这批再报。
301
+ if (lines.count >= 12) {
302
+ [lines addObject:[NSString stringWithFormat:@"…另有 %lu 条",
303
+ (unsigned long)(issues.count - lines.count + 1)]];
304
+ break;
305
+ }
306
+ }
307
+ NSAlert *alert = [NSAlert new];
308
+ if (blocking) {
309
+ alert.messageText = @"还不能保存";
310
+ } else {
311
+ alert.messageText = issues.count > 0 ? @"已保存,但有几处不会生效" : @"已保存";
312
+ }
313
+ alert.informativeText = [lines componentsJoinedByString:@"\n"];
314
+ alert.alertStyle = blocking ? NSAlertStyleWarning : NSAlertStyleInformational;
315
+ [alert addButtonWithTitle:@"好"];
316
+ [alert runModal];
317
+ if (blocking) {
318
+ [self showStatus:@"有必须改的地方,还没保存。" warning:YES];
319
+ }
320
+ }
321
+
322
+ #pragma mark - 试说一句
323
+
324
+ // 对着编辑器里【还没保存】的文本取,这样用户改完不用先保存就能听到效果。
325
+ - (void)speakSample:(id)sender {
326
+ NSString *tag = self.tagPicker.selectedItem.representedObject;
327
+ NSString *text = PetPhraseForTagInText(tag, self.textView.string ?: @"", [self sampleSlots]);
328
+ if (text.length == 0) {
329
+ [self showStatus:[NSString stringWithFormat:@"[%@] 里没有能说的句子。", tag] warning:YES];
330
+ return;
331
+ }
332
+ if (PetPhrasesSpeakHandler) PetPhrasesSpeakHandler(text);
333
+ [self showStatus:[NSString stringWithFormat:@"试说:%@", text] warning:NO];
334
+ }
335
+
336
+ // 预览用的假数据。用真实数据的话,没在跑 agent 时 {toolName} 之类全是空的,
337
+ // 带槽位的句子会被整条跳过,用户会以为自己写错了。
338
+ - (NSDictionary<NSString *, NSString *> *)sampleSlots {
339
+ return @{
340
+ @"quota5h": @"12%", @"resetTime": @"18:30", @"toolName": @"Bash",
341
+ @"sessionMin": @"95", @"failCount": @"3", @"hour": @"2",
342
+ };
343
+ }
344
+
345
+ #pragma mark - 恢复出厂
346
+
347
+ - (void)revertToDefault:(id)sender {
348
+ NSAlert *alert = [NSAlert new];
349
+ alert.messageText = @"恢复出厂台词?";
350
+ alert.informativeText = @"编辑器里的内容会被出厂台词替换。还没保存,可以按 ⌘Z 撤销。";
351
+ [alert addButtonWithTitle:@"恢复"];
352
+ [alert addButtonWithTitle:@"取消"];
353
+ if ([alert runModal] != NSAlertFirstButtonReturn) return;
354
+
355
+ NSString *text = [NSString stringWithContentsOfFile:PetPhrasesDefaultFilePath()
356
+ encoding:NSUTF8StringEncoding error:nil];
357
+ if (text.length == 0) {
358
+ [self showStatus:@"找不到出厂台词文件。" warning:YES];
359
+ return;
360
+ }
361
+ // 走 shouldChangeTextInRange: 而不是直接设 string,这样这一步能被 ⌘Z 撤销。
362
+ NSRange all = NSMakeRange(0, self.textView.string.length);
363
+ if (![self.textView shouldChangeTextInRange:all replacementString:text]) return;
364
+ [self.textView.textStorage replaceCharactersInRange:all withString:text];
365
+ [self.textView didChangeText];
366
+ [self showStatus:@"已填入出厂台词,按保存才会写进文件。" warning:NO];
367
+ }
368
+
369
+ @end
@@ -4,3 +4,6 @@
4
4
  int RenderQuotaDashboard(NSString *path);
5
5
  int RenderAgentStatusCard(NSString *path);
6
6
  int RenderMenuSwitches(NSString *path);
7
+ // 把 PetView 的每一格(rowCount 行 × 8 帧)逐格渲染拼成一张大图,用于渲染改造的
8
+ // 逐字节等价校验。上面三个命令一格宠物都不画,改坏 PetView 它们照样一致。
9
+ int RenderPetSheet(NSString *path, NSString *sheetPath, NSInteger rowCount);
@@ -2,6 +2,8 @@
2
2
  #import "QuotaDashboardView.h"
3
3
  #import "MenuToggleSwitch.h"
4
4
  #import "CCPetsUsage.h"
5
+ #import "PetView.h"
6
+ #import "CCPetsImageLoader.h"
5
7
  #import <Cocoa/Cocoa.h>
6
8
 
7
9
  int RenderQuotaDashboard(NSString *path) {
@@ -199,3 +201,61 @@ int RenderMenuSwitches(NSString *path) {
199
201
  NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
200
202
  return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
201
203
  }
204
+
205
+ // 逐格渲染 PetView,用于 M1 渲染层改造的等价校验。
206
+ // 尺寸取运行时真实值:视图 144×150(AppDelegate 建 PetView 用的就是这个),
207
+ // 素材按 NSMakeSize(140, 150) 装载——两处任何一个写错,改造后的图都会对不上。
208
+ // 走 cacheDisplayInRect: 而不是 displayRectIgnoringOpacity:,因为改成 layer-backed
209
+ // 之后内容在 layer 里,后者抓不到。宿主窗口是必需的:无窗口的视图 cacheDisplay 行为
210
+ // 不保证。
211
+ int RenderPetSheet(NSString *path, NSString *sheetPath, NSInteger rowCount) {
212
+ [NSApplication sharedApplication];
213
+ if (rowCount <= 0) rowCount = 9;
214
+ NSImage *sheet = LoadPetSpriteImage(sheetPath, NSMakeSize(140, 150), rowCount);
215
+ if (!sheet) {
216
+ fprintf(stderr, "无法装载素材: %s\n", sheetPath.UTF8String);
217
+ return EXIT_FAILURE;
218
+ }
219
+
220
+ const NSInteger columns = 8;
221
+ NSRect cellFrame = NSMakeRect(0, 0, 144, 150);
222
+ PetView *view = [[PetView alloc] initWithFrame:cellFrame sheet:sheet rowCount:rowCount];
223
+ view.animationSuspended = YES;
224
+
225
+ NSWindow *host = [[NSWindow alloc] initWithContentRect:cellFrame
226
+ styleMask:NSWindowStyleMaskBorderless backing:NSBackingStoreBuffered defer:NO];
227
+ host.contentView = view;
228
+
229
+ NSSize size = NSMakeSize(NSWidth(cellFrame) * columns, NSHeight(cellFrame) * rowCount);
230
+ NSBitmapImageRep *canvas = [[NSBitmapImageRep alloc]
231
+ initWithBitmapDataPlanes:NULL pixelsWide:(NSInteger)size.width pixelsHigh:(NSInteger)size.height
232
+ bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
233
+ colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
234
+ canvas.size = size;
235
+ NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:canvas];
236
+ [NSGraphicsContext saveGraphicsState];
237
+ NSGraphicsContext.currentContext = context;
238
+
239
+ for (NSInteger row = 0; row < rowCount; row++) {
240
+ for (NSInteger frame = 0; frame < columns; frame++) {
241
+ view.rowIndex = row;
242
+ view.frameIndex = frame;
243
+ view.needsDisplay = YES;
244
+ [view displayIfNeeded];
245
+
246
+ NSBitmapImageRep *cell = [view bitmapImageRepForCachingDisplayInRect:view.bounds];
247
+ if (!cell) continue;
248
+ [view cacheDisplayInRect:view.bounds toBitmapImageRep:cell];
249
+ // 行 0 画在最上面,和素材表本身的排列一致,肉眼比对时不用换算。
250
+ NSPoint origin = NSMakePoint(frame * NSWidth(cellFrame),
251
+ size.height - (row + 1) * NSHeight(cellFrame));
252
+ [cell drawInRect:NSMakeRect(origin.x, origin.y, NSWidth(cellFrame), NSHeight(cellFrame))
253
+ fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0
254
+ respectFlipped:NO hints:@{NSImageHintInterpolation: @(NSImageInterpolationNone)}];
255
+ }
256
+ }
257
+
258
+ [NSGraphicsContext restoreGraphicsState];
259
+ NSData *png = [canvas representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
260
+ return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
261
+ }
@@ -1,12 +1,17 @@
1
1
  #import <Cocoa/Cocoa.h>
2
2
 
3
3
  @interface PetView : NSView <NSMenuDelegate>
4
- @property NSImage *sheet;
5
- @property NSInteger spriteRowCount;
4
+ @property(nonatomic) NSImage *sheet;
5
+ @property(nonatomic) NSInteger spriteRowCount;
6
6
  @property(nonatomic) NSInteger lookDirection;
7
- @property NSInteger frameIndex;
8
- @property NSInteger rowIndex;
7
+ @property(nonatomic) NSInteger frameIndex;
8
+ @property(nonatomic) NSInteger rowIndex;
9
9
  @property NSArray<NSNumber *> *frames;
10
+ // 与 frames 等长,每项是该帧要停留几个动画节拍。全 1 就是原来的匀速播放。
11
+ @property NSArray<NSNumber *> *frameHolds;
12
+ // 与 frames 等长的行号。为 nil 时整段都用 rowIndex;转头要横跨 row 9/10 两行,
13
+ // 只有逐帧带行号才播得出来。
14
+ @property NSArray<NSNumber *> *frameRows;
10
15
  @property NSUInteger sequenceIndex;
11
16
  @property BOOL oneShot;
12
17
  @property BOOL draggingPet;