文件
dayu-color/大鱼调色/Wrapper Application/AppDelegate.m
T

513 行
39 KiB
Objective-C

#import "AppDelegate.h"
#import "DYBetaUpdater.h"
#import "../Shared/DYBetaDiagnostics.h"
#import "../Shared/DYCodeIntegrity.h"
static NSString *const DYPluginID = @"com.dayu.color.XPC";
static NSString *const DYReleaseAddress = @"https://dayu.media";
static dispatch_queue_t DYPluginRegistrationQueue(void) {
static dispatch_queue_t queue;
static dispatch_once_t once;
dispatch_once(&once, ^{ queue = dispatch_queue_create("com.dayu.color.registration", DISPATCH_QUEUE_SERIAL); });
return queue;
}
static NSColor *DYColor(CGFloat r, CGFloat g, CGFloat b) { return [NSColor colorWithSRGBRed:r green:g blue:b alpha:1]; }
static NSColor *DYBlue(void) { return DYColor(.36,.65,1); }
static NSColor *DYGreen(void) { return DYColor(.26,.86,.53); }
static NSColor *DYSecondary(void) { return DYColor(.70,.74,.81); }
// Static opaque surfaces preserve the reference palette without expensive blur or motion.
@interface DYSurface : NSView
@property(retain) NSColor *tint;
@property BOOL backdrop;
@end
@implementation DYSurface
- (BOOL)isFlipped { return YES; }
- (void)drawRect:(NSRect)dirty {
BOOL contrast = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast;
NSBezierPath *shape = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds,1,1) xRadius:self.backdrop ? 0 : 22 yRadius:self.backdrop ? 0 : 22];
NSColor *base = DYColor(.105,.115,.14);
NSColor *start = self.backdrop ? DYColor(.105,.14,.20) : [base blendedColorWithFraction:.17 ofColor:self.tint];
NSColor *end = self.backdrop ? DYColor(.105,.115,.115) : base;
NSGradient *gradient = [[[NSGradient alloc] initWithStartingColor:start endingColor:end] autorelease];
[gradient drawInBezierPath:shape angle:35];
if (!self.backdrop) {
[[self.tint blendedColorWithFraction:contrast ? .15 : .62 ofColor:base] setStroke];
shape.lineWidth = contrast ? 2 : 1; [shape stroke];
}
}
- (void)dealloc { [_tint release]; [super dealloc]; }
@end
@interface DYActionButton : NSButton
@property(retain) NSColor *tint;
@property BOOL prominent;
@end
@implementation DYActionButton
- (void)drawRect:(NSRect)dirty {
NSRect rect = NSInsetRect(self.bounds,2,2);
NSBezierPath *shape = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:rect.size.height/2 yRadius:rect.size.height/2];
NSColor *base = self.prominent ? self.tint : [DYColor(.10,.12,.16) blendedColorWithFraction:.18 ofColor:self.tint];
if (self.highlighted) base = [base blendedColorWithFraction:.2 ofColor:NSColor.blackColor];
[base setFill]; [shape fill];
[[self.tint blendedColorWithFraction:.35 ofColor:NSColor.whiteColor] setStroke];
shape.lineWidth = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast ? 2 : 1; [shape stroke];
NSColor *text = self.enabled ? (self.prominent ? NSColor.whiteColor : self.tint) : DYSecondary();
NSDictionary *attrs = @{NSFontAttributeName:[NSFont systemFontOfSize:13 weight:NSFontWeightSemibold],NSForegroundColorAttributeName:text};
NSSize size = [self.title sizeWithAttributes:attrs];
[self.title drawAtPoint:NSMakePoint((NSWidth(self.bounds)-size.width)/2,(NSHeight(self.bounds)-size.height)/2) withAttributes:attrs];
}
- (void)drawFocusRingMask { [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds,2,2) xRadius:20 yRadius:20] fill]; }
- (NSRect)focusRingMaskBounds { return self.bounds; }
- (void)dealloc { [_tint release]; [super dealloc]; }
@end
static NSTextField *DYLabel(NSString *text, CGFloat size, NSFontWeight weight, NSColor *color) {
NSTextField *label = [NSTextField wrappingLabelWithString:text];
label.font = [NSFont systemFontOfSize:size weight:weight]; label.textColor = color;
label.translatesAutoresizingMaskIntoConstraints = NO;
[label setContentCompressionResistancePriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationVertical];
return label;
}
static NSStackView *DYStack(NSArray *views, NSUserInterfaceLayoutOrientation orientation, CGFloat spacing) {
NSStackView *stack = [NSStackView stackViewWithViews:views];
stack.orientation = orientation; stack.spacing = spacing;
stack.alignment = orientation == NSUserInterfaceLayoutOrientationVertical ? NSLayoutAttributeLeading : NSLayoutAttributeTop;
stack.translatesAutoresizingMaskIntoConstraints = NO;
if (orientation == NSUserInterfaceLayoutOrientationHorizontal) stack.distribution = NSStackViewDistributionFillEqually;
return stack;
}
static void DYPin(NSView *child, NSView *parent, CGFloat inset) {
child.translatesAutoresizingMaskIntoConstraints = NO; [parent addSubview:child];
[NSLayoutConstraint activateConstraints:@[
[child.leadingAnchor constraintEqualToAnchor:parent.leadingAnchor constant:inset],
[child.trailingAnchor constraintEqualToAnchor:parent.trailingAnchor constant:-inset],
[child.topAnchor constraintEqualToAnchor:parent.topAnchor constant:inset],
[child.bottomAnchor constraintEqualToAnchor:parent.bottomAnchor constant:-inset]]];
}
static DYActionButton *DYButton(NSString *title, NSColor *tint, BOOL prominent, id target, SEL action) {
DYActionButton *button = [DYActionButton buttonWithTitle:title target:target action:action];
button.tint = tint; button.prominent = prominent; button.bordered = NO;
button.translatesAutoresizingMaskIntoConstraints = NO;
[button.heightAnchor constraintEqualToConstant:42].active = YES;
[button.widthAnchor constraintGreaterThanOrEqualToConstant:124].active = YES;
return button;
}
static DYSurface *DYCard(NSColor *tint, NSStackView *content) {
DYSurface *card = [[[DYSurface alloc] initWithFrame:NSZeroRect] autorelease];
card.tint = tint; card.translatesAutoresizingMaskIntoConstraints = NO; DYPin(content,card,22);
for (NSView *view in content.arrangedSubviews) [view.widthAnchor constraintEqualToAnchor:content.widthAnchor].active = YES;
return card;
}
static NSTextField *DYHeading(NSString *symbol, NSString *text, NSColor *color) {
NSTextField *label = DYLabel(text,15,NSFontWeightSemibold,color);
NSImage *image = [NSImage imageWithSystemSymbolName:symbol accessibilityDescription:nil];
if (image) {
NSTextAttachment *attachment = [[[NSTextAttachment alloc] init] autorelease];
attachment.image = image; attachment.bounds = NSMakeRect(0,-3,18,18);
NSMutableAttributedString *value = [[[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]] autorelease];
[value appendAttributedString:[[[NSAttributedString alloc] initWithString:[@" " stringByAppendingString:text]
attributes:@{NSFontAttributeName:label.font,NSForegroundColorAttributeName:color}] autorelease]];
label.attributedStringValue = value; label.accessibilityLabel = text;
}
return label;
}
typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYReady, DYFailed };
@interface AppDelegate ()
@property(weak) IBOutlet NSWindow *window;
@property(assign) NSTextField *statusTitle, *statusDetail, *exitDetail;
@property(assign) DYActionButton *retryButton, *keepButton, *confirmationButton;
@property(assign) NSProgressIndicator *progress;
@property(assign) DYSurface *registrationCard;
@property DYRegistrationState registrationState;
@property BOOL terminating;
@property(retain) NSStatusItem *statusItem;
@property(retain) NSMutableDictionary *diagnostics;
@property(retain) DYBetaUpdater *updater;
@property(assign) NSTextField *updateTitle, *updateDetail, *diagnosticDetail, *reportID;
@property(assign) DYActionButton *updateCheckButton, *updateInstallButton, *updateCancelButton, *sendSummaryButton;
@property(assign) NSButton *diagnosticToggle;
@property(assign) NSProgressIndicator *updateProgress;
@property(retain) NSTimer *updateProgressTimer;
@property BOOL updateCheckDone;
@property BOOL integrityRejected;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
self.window.title = @"大鱼调色";
self.window.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
self.window.titlebarAppearsTransparent = YES; self.window.backgroundColor = DYColor(.105,.14,.20);
self.window.contentMinSize = NSMakeSize(760,620); [self.window setContentSize:NSMakeSize(920,850)]; [self.window center];
DYBetaStart();
[self buildInterface]; [self buildMenu]; [self buildStatusItem];
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(refreshDiagnostics:) name:DYBetaDiagnosticsChanged object:nil];
self.updater = [[[DYBetaUpdater alloc] init] autorelease];
__block AppDelegate *owner = self;
self.updater.changed = ^(NSDictionary *state) { [owner updateChanged:state]; };
NSInteger expected=[NSUserDefaults.standardUserDefaults integerForKey:@"betaPendingUpdateBuild"];
if(expected>0 && [NSBundle.mainBundle.infoDictionary[@"CFBundleVersion"]integerValue]>=expected){
DYBetaEvent(@"update_installer",@{@"status":@"completed",@"count":@(expected)});
[NSUserDefaults.standardUserDefaults removeObjectForKey:@"betaPendingUpdateBuild"];
}
[NSWorkspace.sharedWorkspace.notificationCenter addObserver:self selector:@selector(accessibilityChanged:)
name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
[self.window makeKeyAndOrderFront:nil]; [self refreshDiagnostics:nil]; [self checkRegistration:nil]; [self.updater check];
// Explicit QA opt-in on the signed, installed wrapper only. Never stalls the host.
if([NSProcessInfo.processInfo.arguments containsObject:@"--diagnostics-probe"])
[self performSelector:@selector(runDiagnosticsProbe) withObject:nil afterDelay:5];
}
- (void)runDiagnosticsProbe {
DYBetaEvent(@"diagnostic_summary",@{@"status":@"probe_begin"});
[NSThread sleepForTimeInterval:12];
DYBetaEvent(@"diagnostic_summary",@{@"status":@"probe_recovered"});
}
- (void)buildMenu {
NSMenu *menu = [[[NSMenu alloc] initWithTitle:@"大鱼调色"] autorelease];
NSMenuItem *root = [[[NSMenuItem alloc] initWithTitle:@"大鱼调色" action:NULL keyEquivalent:@""] autorelease]; [menu addItem:root];
NSMenu *app = [[[NSMenu alloc] initWithTitle:@"大鱼调色"] autorelease]; root.submenu = app;
for (NSArray *entry in @[@[@"关于大鱼调色",NSStringFromSelector(@selector(orderFrontStandardAboutPanel:)),@""],
@[@"查看功能介绍",NSStringFromSelector(@selector(keepIntroduction:)),@"i"],
@[@"重新检查插件",NSStringFromSelector(@selector(checkRegistration:)),@"r"],
@[@"检查公测更新",NSStringFromSelector(@selector(checkUpdate:)),@"u"],
@[@"访问发布地址",NSStringFromSelector(@selector(openWebsite:)),@""],
@[@"关闭窗口",NSStringFromSelector(@selector(closeWindow:)),@"w"],
@[@"退出大鱼调色",NSStringFromSelector(@selector(terminate:)),@"q"]]) {
NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:entry[0] action:NSSelectorFromString(entry[1]) keyEquivalent:entry[2]] autorelease];
item.target = [entry[0] isEqualToString:@"退出大鱼调色"] || [entry[0] isEqualToString:@"关于大鱼调色"] ? NSApp : self; [app addItem:item];
}
NSApp.mainMenu = menu;
}
- (void)buildInterface {
DYSurface *backdrop = [[[DYSurface alloc] initWithFrame:NSZeroRect] autorelease]; backdrop.backdrop = YES; self.window.contentView = backdrop;
NSScrollView *scroll = [[[NSScrollView alloc] initWithFrame:NSZeroRect] autorelease];
scroll.drawsBackground = NO; scroll.hasVerticalScroller = YES; scroll.autohidesScrollers = YES; DYPin(scroll,backdrop,0);
DYSurface *document = [[[DYSurface alloc] initWithFrame:NSZeroRect] autorelease];
document.backdrop = YES; document.translatesAutoresizingMaskIntoConstraints = NO; scroll.documentView = document;
[NSLayoutConstraint activateConstraints:@[
[document.leadingAnchor constraintEqualToAnchor:scroll.contentView.leadingAnchor],
[document.topAnchor constraintEqualToAnchor:scroll.contentView.topAnchor],
[document.widthAnchor constraintEqualToAnchor:scroll.contentView.widthAnchor]]];
NSButton *website = [NSButton buttonWithTitle:@"发布地址 https://dayu.media ↗" target:self action:@selector(openWebsite:)];
website.bordered = NO; website.translatesAutoresizingMaskIntoConstraints = NO;
website.attributedTitle = [[[NSAttributedString alloc] initWithString:website.title attributes:@{
NSFontAttributeName:[NSFont systemFontOfSize:13 weight:NSFontWeightMedium],NSForegroundColorAttributeName:DYBlue()}] autorelease];
[website.heightAnchor constraintEqualToConstant:28].active = YES;
NSDictionary *info = NSBundle.mainBundle.infoDictionary;
NSArray *heroLabels = @[DYLabel(@"FINAL CUT PRO / MOTION",11,NSFontWeightSemibold,DYBlue()),
DYLabel(@"大鱼调色",42,NSFontWeightBold,NSColor.whiteColor),
DYLabel(@"从色彩还原到胶片质感,让每一次调色更从容。",15,NSFontWeightRegular,DYSecondary()),
DYLabel([NSString stringWithFormat:@"v%@ · 构建 %@ / 原生 FxPlug 4 · Apple Silicon",info[@"CFBundleShortVersionString"],info[@"CFBundleVersion"]],11,NSFontWeightMedium,DYSecondary())];
NSStackView *hero = DYStack(heroLabels,NSUserInterfaceLayoutOrientationVertical,8);
for (NSTextField *label in heroLabels) { label.alignment = NSTextAlignmentCenter; [label.widthAnchor constraintEqualToAnchor:hero.widthAnchor].active = YES; }
self.statusTitle = DYLabel(@"正在检查插件…",22,NSFontWeightSemibold,NSColor.whiteColor);
self.statusDetail = DYLabel(@"正在检查本机插件登记,随后自动提交注册。",13,NSFontWeightRegular,DYSecondary());
[self.statusDetail.heightAnchor constraintGreaterThanOrEqualToConstant:42].active = YES;
self.progress = [[[NSProgressIndicator alloc] initWithFrame:NSZeroRect] autorelease];
self.progress.style = NSProgressIndicatorStyleBar; self.progress.indeterminate = YES; self.progress.translatesAutoresizingMaskIntoConstraints = NO;
self.retryButton = DYButton(@"检查中…",DYBlue(),NO,self,@selector(checkRegistration:));
self.keepButton = DYButton(@"查看功能介绍",DYColor(.20,.46,.94),YES,self,@selector(keepIntroduction:));
self.exitDetail = DYLabel(@"应用会保持运行,关闭窗口后继续后台诊断。",15,NSFontWeightSemibold,DYGreen());
[self.exitDetail.heightAnchor constraintGreaterThanOrEqualToConstant:38].active = YES;
NSStackView *registration = DYStack(@[DYHeading(@"puzzlepiece.extension",@"插件连接",DYBlue()),self.statusTitle,self.statusDetail,self.progress,
self.exitDetail,DYStack(@[self.retryButton,self.keepButton],NSUserInterfaceLayoutOrientationHorizontal,8)],NSUserInterfaceLayoutOrientationVertical,13);
self.registrationCard = DYCard(DYBlue(),registration);
self.confirmationButton = DYButton(@"已确认,后台运行",DYGreen(),NO,self,@selector(confirmHost:));
self.confirmationButton.enabled = NO;
self.confirmationButton.toolTip = @"请先在 Final Cut Pro 中应用大鱼调色并确认效果正常,再点击此按钮。";
NSStackView *host = DYStack(@[DYHeading(@"play.rectangle",@"在 Final Cut Pro 中检查",DYGreen()),
DYLabel(@"调色,留在时间线里。",22,NSFontWeightSemibold,NSColor.whiteColor),
DYLabel(@"Final Cut Pro:效果 → 大鱼调色\n将效果应用到片段,确认画面与调节正常。\n打开宿主检查会保留本窗口,等待你确认。",13,NSFontWeightRegular,DYSecondary()),
DYStack(@[DYButton(@"打开 FCP 检查",DYColor(.20,.46,.94),YES,self,@selector(openFinalCut:)),DYButton(@"打开 Motion",DYGreen(),NO,self,@selector(openMotion:))],NSUserInterfaceLayoutOrientationHorizontal,8),
self.confirmationButton],NSUserInterfaceLayoutOrientationVertical,13);
DYSurface *hostCard = DYCard(DYGreen(),host);
NSStackView *top = DYStack(@[self.registrationCard,hostCard],NSUserInterfaceLayoutOrientationHorizontal,14);
[self.registrationCard.heightAnchor constraintEqualToAnchor:hostCard.heightAnchor].active = YES;
self.updateTitle = DYLabel(@"公测更新",20,NSFontWeightSemibold,NSColor.whiteColor);
self.updateDetail = DYLabel(@"启动时自动检查,新版本由你确认安装。",13,NSFontWeightRegular,DYSecondary());
[self.updateDetail.heightAnchor constraintGreaterThanOrEqualToConstant:42].active = YES;
self.updateProgress = [[[NSProgressIndicator alloc] initWithFrame:NSZeroRect] autorelease];
self.updateProgress.style=NSProgressIndicatorStyleBar; self.updateProgress.indeterminate=NO;
self.updateProgress.minValue=0; self.updateProgress.maxValue=1; self.updateProgress.translatesAutoresizingMaskIntoConstraints=NO;
self.updateCheckButton=DYButton(@"检查更新",DYBlue(),NO,self,@selector(checkUpdate:));
self.updateInstallButton=DYButton(@"下载更新",DYColor(.20,.46,.94),YES,self,@selector(installUpdate:));
self.updateInstallButton.enabled=NO;
self.updateCancelButton=DYButton(@"取消下载",DYBlue(),NO,self,@selector(cancelUpdate:)); self.updateCancelButton.hidden=YES;
DYSurface *updateCard=DYCard(DYBlue(),DYStack(@[DYHeading(@"arrow.triangle.2.circlepath",@"持续改进,及时更新",DYBlue()),self.updateTitle,self.updateDetail,self.updateProgress,
DYStack(@[self.updateCheckButton,self.updateInstallButton],NSUserInterfaceLayoutOrientationHorizontal,8),self.updateCancelButton],NSUserInterfaceLayoutOrientationVertical,10));
self.diagnosticToggle=[NSButton checkboxWithTitle:@"参与公测诊断" target:self action:@selector(toggleDiagnostics:)];
self.diagnosticToggle.font=[NSFont systemFontOfSize:16 weight:NSFontWeightSemibold]; self.diagnosticToggle.state=DYBetaEnabled()?NSControlStateValueOn:NSControlStateValueOff;
self.diagnosticDetail=DYLabel(@"诊断准备中…",12,NSFontWeightRegular,DYSecondary());
self.reportID=DYLabel(@"报告标识准备中…",10,NSFontWeightRegular,DYSecondary());self.reportID.selectable=YES;
self.sendSummaryButton=DYButton(@"发送诊断摘要",DYColor(.67,.59,1),NO,self,@selector(sendSummary:));
DYSurface *diagnosticCard=DYCard(DYColor(.67,.59,1),DYStack(@[DYHeading(@"waveform.path.ecg",@"一起完善大鱼调色",DYColor(.67,.59,1)),self.diagnosticToggle,
DYLabel(@"后台自动发送版本、系统环境、阶段耗时、内存及本产品崩溃/卡顿调用栈摘要到 dayu.media;不发送素材、预设或账号。可随时关闭,保留 30 天。",12,NSFontWeightRegular,DYSecondary()),
self.reportID,self.diagnosticDetail,self.sendSummaryButton],NSUserInterfaceLayoutOrientationVertical,10));
NSStackView *beta=DYStack(@[updateCard,diagnosticCard],NSUserInterfaceLayoutOrientationHorizontal,14);
[updateCard.heightAnchor constraintEqualToAnchor:diagnosticCard.heightAnchor].active=YES;
NSArray *features = @[
@[@"slider.horizontal.3",@"完整调色",@"精准还原,自由塑造",@"CST 色彩管理、光影与曲线\nHSL、色轮、蜘蛛盘与白平衡",DYBlue()],
@[@"square.grid.2x2",@"LUT 与风格",@"灵感,所见即所得",@"LUT 缩略图浏览与实时预览\n快速收藏,管理常用风格",DYColor(.67,.59,1)],
@[@"film",@"胶片质感",@"让画面更有温度",@"八种印片外观、颗粒与晕光\n辉光、暗角及通道混合器",DYColor(1,.67,.30)],
@[@"square.on.circle",@"局部与叠层",@"每个细节,都有层次",@"独立工具层、逐层蒙版\n画面控件与关键帧跟踪",DYGreen()]];
NSMutableArray *cards = [NSMutableArray array];
for (NSArray *feature in features) [cards addObject:DYCard(feature[4],DYStack(@[DYHeading(feature[0],feature[1],feature[4]),
DYLabel(feature[2],17,NSFontWeightSemibold,NSColor.whiteColor),DYLabel(feature[3],13,NSFontWeightRegular,DYSecondary())],NSUserInterfaceLayoutOrientationVertical,12))];
NSStackView *row1 = DYStack(@[cards[0],cards[1]],NSUserInterfaceLayoutOrientationHorizontal,14);
NSStackView *row2 = DYStack(@[cards[2],cards[3]],NSUserInterfaceLayoutOrientationHorizontal,14);
[((NSView *)cards[0]).heightAnchor constraintEqualToAnchor:((NSView *)cards[1]).heightAnchor].active = YES;
[((NSView *)cards[2]).heightAnchor constraintEqualToAnchor:((NSView *)cards[3]).heightAnchor].active = YES;
NSStackView *content = DYStack(@[website,hero,top,beta,DYHeading(@"sparkles",@"一套工具,完成你的色彩表达",NSColor.whiteColor),row1,row2],NSUserInterfaceLayoutOrientationVertical,18);
DYPin(content,document,30);
for (NSView *view in content.arrangedSubviews) [view.widthAnchor constraintEqualToAnchor:content.widthAnchor].active = YES;
[document.heightAnchor constraintGreaterThanOrEqualToAnchor:scroll.contentView.heightAnchor].active = YES;
}
// PluginKit runs on a worker queue. Arguments are never interpreted as shell commands.
- (NSDictionary *)runPluginKit:(NSArray *)arguments {
NSTask *task = [[[NSTask alloc] init] autorelease]; task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/pluginkit"]; task.arguments = arguments;
NSPipe *pipe = [NSPipe pipe]; task.standardOutput = pipe; task.standardError = pipe;
NSError *error = nil;
if (![task launchAndReturnError:&error]) return @{@"code":@(-1),@"output":error.localizedDescription ?: @"无法启动插件登记服务"};
NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:8];
while (task.running && deadline.timeIntervalSinceNow > 0) [NSThread sleepForTimeInterval:.05];
if (task.running) { [task terminate]; return @{@"code":@(-2),@"output":@"插件登记服务响应超时"}; }
NSData *data = [pipe.fileHandleForReading readDataToEndOfFile];
NSString *output = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease] ?: @"";
return @{@"code":@(task.terminationStatus),@"output":output};
}
- (BOOL)registry:(NSDictionary *)query containsPlugin:(NSString *)path {
if ([query[@"code"] intValue] != 0) return NO;
for (NSString *line in [query[@"output"] componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
NSArray *fields = [line componentsSeparatedByString:@"\t"]; if (fields.count < 4) continue;
NSString *identity = [fields[0] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
if ([identity hasPrefix:@"+"]) identity = [[identity substringFromIndex:1] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
NSString *registered = [[fields lastObject] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
// 1.1 is the registration protocol, not the APP version.
NSString *expected = [DYPluginID stringByAppendingString:@"(1.1)"];
if ([identity isEqualToString:expected] &&
[registered.stringByResolvingSymlinksInPath isEqualToString:path.stringByResolvingSymlinksInPath]) return YES;
}
return NO;
}
- (BOOL)registry:(NSDictionary *)query listsExactPath:(NSString *)path {
NSString *suffix = [@"\t" stringByAppendingString:path];
for (NSString *line in [query[@"output"] componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
if ([line hasSuffix:suffix]) return YES;
}
return NO;
}
- (NSString *)removeRejectedPluginRegistration:(NSString *)path {
NSArray *arguments = @[@"-m",@"-A",@"-D",@"-v",@"-i",DYPluginID];
NSDictionary *before = [self runPluginKit:arguments];
if ([before[@"code"] intValue] != 0) return @"query-failed";
if (![self registry:before listsExactPath:path]) return @"not-registered";
if (![path.stringByStandardizingPath isEqualToString:path.stringByResolvingSymlinksInPath]) return @"skipped-symlink";
[self runPluginKit:@[@"-r",path]];
NSDictionary *after = [self runPluginKit:arguments];
if ([after[@"code"] intValue] != 0 || [self registry:after listsExactPath:path]) return @"removal-unverified";
return @"removed";
}
- (void)rejectModifiedInstallation:(NSDictionary *)results {
if (self.integrityRejected || self.terminating) return;
self.integrityRejected = YES;
[self.updater stopForIntegrityFailure];
[self finishRegistration:NO details:DYIntegrityRecoveryMessage results:results];
self.retryButton.enabled = NO;
self.exitDetail.stringValue = @"此副本的自动更新已停用。请安装原始安装包后重新打开。";
NSString *path = [NSBundle.mainBundle.bundlePath stringByAppendingPathComponent:DYPluginRelativePath];
dispatch_async(DYPluginRegistrationQueue(), ^{
@autoreleasepool {
NSString *removal = [self removeRejectedPluginRegistration:path];
dispatch_async(dispatch_get_main_queue(), ^{
self.diagnostics[@"registrationRevocation"] = removal;
[self writeDiagnostics];
});
}
});
}
- (void)checkRegistration:(id)sender {
if (self.integrityRejected) return;
if (self.diagnostics && (self.registrationState == DYChecking || self.registrationState == DYRegistering)) return;
self.registrationState = DYChecking;
self.retryButton.enabled = NO; self.retryButton.title = @"检查中…";
self.statusTitle.stringValue = @"正在检查插件…"; self.statusTitle.textColor = NSColor.whiteColor;
self.statusDetail.stringValue = @"正在检查本机插件登记,随后自动提交注册。";
self.progress.indeterminate = YES; [self.progress startAnimation:nil];
NSString *path = [NSBundle.mainBundle.bundlePath stringByAppendingPathComponent:DYPluginRelativePath];
self.diagnostics = [NSMutableDictionary dictionaryWithDictionary:@{
@"bundleID":NSBundle.mainBundle.bundleIdentifier ?: @"",@"version":[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"] ?: @"",
@"build":[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"] ?: @"",@"executable":NSBundle.mainBundle.executablePath ?: @"",
@"pid":@(NSProcessInfo.processInfo.processIdentifier),@"plugin":path,@"status":@"checking"}];
dispatch_async(DYPluginRegistrationQueue(), ^{
@autoreleasepool {
NSString *failedComponent = nil;
OSStatus status = DYValidateRunningInstallation(DYCodeRoleWrapper, &failedComponent);
if (status != errSecSuccess) {
NSDictionary *results = @{@"integrity":@"rejected", @"integrityComponent":failedComponent,
@"integrityOSStatus":@(status)};
dispatch_async(dispatch_get_main_queue(), ^{
[self rejectModifiedInstallation:results];
});
return;
}
NSBundle *plugin = [NSBundle bundleWithPath:path];
NSDictionary *attributes = [plugin objectForInfoDictionaryKey:@"PlugInKit"][@"Attributes"];
BOOL validComponent = [plugin.bundleIdentifier isEqualToString:DYPluginID] &&
[[plugin objectForInfoDictionaryKey:@"CFBundleVersion"] isEqual:[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]] &&
[attributes[@"com.apple.protocol"] isEqual:@"FxPlug"] && [attributes[@"com.apple.version"] isEqual:@"1.1"];
if (!validComponent) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!self.integrityRejected)
[self finishRegistration:NO details:@"未找到完整的插件组件。请从发布地址重新安装大鱼调色。" results:@{}];
}); return;
}
// The stand-alone wrapper can inspect the registry directly. Registration
// and actual host rendering remain separate states; the user confirms FCP.
NSDictionary *before = [self runPluginKit:@[@"-m",@"-v",@"-i",DYPluginID]];
dispatch_async(dispatch_get_main_queue(), ^{
if (self.integrityRejected) return;
self.registrationState = DYRegistering; self.statusTitle.stringValue = @"正在注册插件…";
self.statusDetail.stringValue = @"正在向系统提交插件注册,并核对当前安装位置。";
});
NSDictionary *add = [self runPluginKit:@[@"-a",path]];
NSDictionary *after = nil; BOOL registered = NO;
for (NSInteger attempt=0; attempt<4; attempt++) {
if (attempt) [NSThread sleepForTimeInterval:.35];
after = [self runPluginKit:@[@"-m",@"-v",@"-i",DYPluginID]];
registered = [self registry:after containsPlugin:path]; if (registered) break;
}
BOOL submissionAccepted = [add[@"code"] intValue] == 0;
NSString *message = registered ?
@"已确认当前插件登记。请在 Final Cut Pro 中实际应用并确认效果正常;若宿主已打开,请保存后重新打开。" :
@"插件注册尚未完成。请点击“重新检查”,或重新安装后再试。窗口将保持打开。";
NSDictionary *results = @{@"integrity":@"verified",@"before":before,@"submission":add,@"after":after ?: @{},@"registered":@(registered),
@"discoveryVerified":@(registered),@"submissionAccepted":@(submissionAccepted),@"hostVerification":@"awaiting-user-confirmation",
@"confirmationMethod":registered ? @"exact-path-discovery" : @"unconfirmed"};
dispatch_async(dispatch_get_main_queue(), ^{
if (!self.integrityRejected) [self finishRegistration:registered details:message results:results];
});
}
});
}
- (void)finishRegistration:(BOOL)success details:(NSString *)details results:(NSDictionary *)results {
if (self.terminating) return;
self.registrationState = success ? DYReady : DYFailed;
[self.progress stopAnimation:nil]; self.progress.indeterminate = NO; self.progress.doubleValue = success ? 100 : 0;
self.registrationCard.tint = success ? DYGreen() : DYColor(1,.67,.30); [self.registrationCard setNeedsDisplay:YES];
self.statusTitle.stringValue = success ? @"✓ 插件注册成功" : (self.integrityRejected ? @"安装完整性验证失败" : @"需要重新检查");
self.statusTitle.textColor = success ? DYGreen() : DYColor(1,.75,.4); self.statusDetail.stringValue = details;
self.retryButton.title = @"重新检查"; self.retryButton.enabled = YES;
self.confirmationButton.enabled = success;
[self.diagnostics addEntriesFromDictionary:results]; self.diagnostics[@"status"] = success ? @"registered" : @"failed"; [self writeDiagnostics];
NSAccessibilityPostNotificationWithUserInfo(self.window,NSAccessibilityAnnouncementRequestedNotification,
@{NSAccessibilityAnnouncementKey:self.statusTitle.stringValue,NSAccessibilityPriorityKey:@(NSAccessibilityPriorityHigh)});
DYBetaEvent(@"registration",@{@"status":success?@"registered":@"failed"});
if(success)[self refreshBackgroundState];
else self.exitDetail.stringValue=@"注册尚未完成,应用会保留此窗口以便重试。";
}
- (void)refreshBackgroundState {
if(self.registrationState==DYReady)self.exitDetail.stringValue=DYBetaEnabled()?@"后台诊断已开启。关闭窗口后继续运行,可从菜单栏重新打开或退出。":@"诊断已关闭。应用保持运行,可从菜单栏退出。";
}
- (void)buildStatusItem {
self.statusItem=[NSStatusBar.systemStatusBar statusItemWithLength:NSVariableStatusItemLength];
self.statusItem.button.image=[NSImage imageWithSystemSymbolName:@"slider.horizontal.3" accessibilityDescription:@"大鱼调色后台诊断"];
self.statusItem.button.toolTip=@"大鱼调色 · 后台运行";
NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"大鱼调色"]autorelease];
NSMenuItem *show=[menu addItemWithTitle:@"打开大鱼调色" action:@selector(showMainWindow:) keyEquivalent:@""];show.target=self;
NSMenuItem *send=[menu addItemWithTitle:@"发送诊断摘要" action:@selector(sendSummary:) keyEquivalent:@""];send.target=self;
[menu addItem:NSMenuItem.separatorItem];
NSMenuItem *quit=[menu addItemWithTitle:@"退出大鱼调色" action:@selector(terminate:) keyEquivalent:@""];quit.target=NSApp;
self.statusItem.menu=menu;
}
- (void)showMainWindow:(id)sender { [self.window makeKeyAndOrderFront:nil];[NSApp activateIgnoringOtherApps:YES]; }
- (BOOL)applicationShouldHandleReopen:(NSApplication *)app hasVisibleWindows:(BOOL)visible { if(!visible)[self showMainWindow:nil];return YES; }
- (void)updateChanged:(NSDictionary *)state {
if(self.terminating)return;
NSString *phase=state[@"phase"];
BOOL rejected = [phase isEqual:@"integrity_rejected"];
if (rejected) [self rejectModifiedInstallation:@{@"integrity":@"rejected"}];
BOOL busy=[@[@"checking",@"downloading",@"validating"]containsObject:phase];
BOOL available=[@[@"available",@"ready",@"host_wait",@"installer"]containsObject:phase];
if(![phase isEqual:@"checking"]){self.updateCheckDone=YES;if(available)[self keepIntroduction:nil];}
self.updateTitle.stringValue=[phase isEqual:@"available"]?state[@"message"]:@"公测更新";
self.updateDetail.stringValue=state[@"message"]?:@"";
self.updateCheckButton.enabled=!busy && !rejected;
self.updateInstallButton.enabled=[@[@"available",@"ready",@"host_wait",@"installer"]containsObject:phase];
self.updateInstallButton.title=[phase isEqual:@"available"]?@"下载更新":@"安装更新";
self.updateCancelButton.hidden=![phase isEqual:@"downloading"];
[self.updateProgressTimer invalidate];self.updateProgressTimer=nil;
if([phase isEqual:@"downloading"])self.updateProgressTimer=[NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(refreshUpdateProgress:) userInfo:nil repeats:YES];
self.updateProgress.indeterminate=[@[@"checking",@"validating"]containsObject:phase];
if(self.updateProgress.indeterminate)[self.updateProgress startAnimation:nil];else [self.updateProgress stopAnimation:nil];
self.updateProgress.doubleValue=[@[@"ready",@"host_wait",@"installer"]containsObject:phase]?1:0;
[self refreshBackgroundState];
}
- (void)refreshUpdateProgress:(NSTimer *)timer {
if([self.updater.state[@"phase"]isEqual:@"downloading"])self.updateProgress.doubleValue=self.updater.downloadFraction;
}
- (void)checkUpdate:(id)sender { [self keepIntroduction:nil]; [self.updater check]; }
- (void)installUpdate:(id)sender {
[self keepIntroduction:nil];NSString *phase=self.updater.state[@"phase"];
if([phase isEqual:@"available"])[self.updater download];else [self.updater install];
}
- (void)cancelUpdate:(id)sender { [self keepIntroduction:nil];[self.updater cancel]; }
- (void)refreshDiagnostics:(NSNotification *)note {
NSDictionary *state=DYBetaStatus();BOOL enabled=DYBetaEnabled();self.diagnosticToggle.state=enabled?NSControlStateValueOn:NSControlStateValueOff;
self.sendSummaryButton.enabled=enabled; [self refreshBackgroundState];
self.reportID.stringValue=[NSString stringWithFormat:@"报告标识:%@",state[@"installation_id"]?:@"准备中…"];
NSNumber *uploaded=state[@"last_upload"];
if(!enabled)self.diagnosticDetail.stringValue=@"诊断已关闭。不会继续上传,待发送摘要已清除。";
else if(uploaded){NSDateFormatter *format=[[[NSDateFormatter alloc]init]autorelease];format.dateFormat=@"HH:mm:ss";
self.diagnosticDetail.stringValue=[NSString stringWithFormat:@"最近送达 %@ · 待发送 %@ 条",[format stringFromDate:[NSDate dateWithTimeIntervalSince1970:uploaded.doubleValue]],state[@"pending"]?:@0];}
else self.diagnosticDetail.stringValue=@"诊断将在后台发送,离线时暂存并稍后重试。";
}
- (void)toggleDiagnostics:(id)sender { [self keepIntroduction:nil];DYBetaSetEnabled(self.diagnosticToggle.state==NSControlStateValueOn);[self refreshDiagnostics:nil]; }
- (void)sendSummary:(id)sender { [self keepIntroduction:nil];DYBetaSendSummary();self.diagnosticDetail.stringValue=@"已加入后台发送队列,送达后会显示时间。"; }
- (void)keepIntroduction:(id)sender {
[self showMainWindow:sender]; [self refreshBackgroundState];
}
- (void)confirmHost:(id)sender {
if (self.registrationState != DYReady) return;
DYBetaEvent(@"host_confirmed",@{@"status":@"user_confirmed"});
self.diagnostics[@"hostVerification"] = @"user-confirmed";
[self writeDiagnostics]; [self.window orderOut:nil];
}
- (void)writeDiagnostics {
NSURL *base = [NSFileManager.defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask].firstObject;
NSURL *folder = [base URLByAppendingPathComponent:@"com.dayu.color" isDirectory:YES];
[NSFileManager.defaultManager createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:self.diagnostics options:NSJSONWritingPrettyPrinted error:nil];
[data writeToURL:[folder URLByAppendingPathComponent:@"Registration.json"] options:NSDataWritingAtomic error:nil];
}
- (void)openHostWithIdentifiers:(NSArray *)identifiers name:(NSString *)name {
[self keepIntroduction:nil]; NSURL *url = nil;
for (NSString *identifier in identifiers) { url = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:identifier]; if (url) break; }
if (!url) { [self showMessage:[@"未找到 " stringByAppendingString:name] detail:@"请先安装宿主应用,再从效果或滤镜中使用大鱼调色。"]; return; }
[NSWorkspace.sharedWorkspace openApplicationAtURL:url configuration:NSWorkspaceOpenConfiguration.configuration completionHandler:^(NSRunningApplication *app,NSError *error) {
if (error) dispatch_async(dispatch_get_main_queue(), ^{ [self showMessage:@"无法打开宿主" detail:error.localizedDescription]; });
}];
}
- (void)openFinalCut:(id)sender { [self openHostWithIdentifiers:@[@"com.apple.FinalCut",@"com.apple.FinalCutApp"] name:@"Final Cut Pro"]; }
- (void)openMotion:(id)sender { [self openHostWithIdentifiers:@[@"com.apple.motionapp",@"com.apple.motionappApp"] name:@"Motion"]; }
- (void)openWebsite:(id)sender { [self keepIntroduction:nil]; if (![NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:DYReleaseAddress]]) [self showMessage:@"无法打开发布地址" detail:DYReleaseAddress]; }
- (void)showMessage:(NSString *)title detail:(NSString *)detail {
NSAlert *alert = [[[NSAlert alloc] init] autorelease]; alert.messageText = title; alert.informativeText = detail;
[alert addButtonWithTitle:@"好"]; [alert beginSheetModalForWindow:self.window completionHandler:nil];
}
- (void)closeWindow:(id)sender { [self.window performClose:sender]; }
- (void)accessibilityChanged:(NSNotification *)note { [self.window.contentView setNeedsDisplay:YES]; }
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app { return NO; }
- (void)applicationWillTerminate:(NSNotification *)note {
self.terminating = YES;
[NSStatusBar.systemStatusBar removeStatusItem:self.statusItem];
self.updater.changed=nil; [self.updater cancel];DYBetaStop();
[self.updateProgressTimer invalidate];self.updateProgressTimer=nil;
[NSNotificationCenter.defaultCenter removeObserver:self];
[NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self];
}
- (void)dealloc { [_statusItem release]; [_diagnostics release]; [_updater release]; [_updateProgressTimer invalidate]; [_updateProgressTimer release]; [super dealloc]; }
@end