From 87baa785fd46489ba8772acd60b1459182820aa6 Mon Sep 17 00:00:00 2001 From: mac Date: Sun, 1 Nov 2026 11:08:10 +0800 Subject: [PATCH] feat: load LUT libraries and selections in background with cancellation and visible-only thumbnails --- tools/verify_lut_responsiveness.mm | 97 ++++++ verification/LUTResponsiveness.json | 376 ++++++++++++++++++++++++ 大鱼调色/Plugin/DYInspector.mm | 36 ++- 大鱼调色/Plugin/DYLUTBrowser.mm | 116 +++++--- 大鱼调色/Plugin/DYLUTLibrary.h | 11 + 大鱼调色/Plugin/DYLUTLibrary.mm | 149 +++++++--- 大鱼调色/Plugin/DYRenderer.mm | 17 +- 大鱼调色/Plugin/Info.plist | 4 +- 大鱼调色/Wrapper Application/Info.plist | 4 +- 9 files changed, 710 insertions(+), 100 deletions(-) create mode 100644 tools/verify_lut_responsiveness.mm create mode 100644 verification/LUTResponsiveness.json diff --git a/tools/verify_lut_responsiveness.mm b/tools/verify_lut_responsiveness.mm new file mode 100644 index 0000000..8dcb1bf --- /dev/null +++ b/tools/verify_lut_responsiveness.mm @@ -0,0 +1,97 @@ +#import +#import "../大鱼调色/Plugin/DYLUTLibrary.h" +#ifndef DY_LUT_BASELINE +#import "../大鱼调色/Plugin/DYLUTBrowser.h" +@interface DYLUTBrowser (Acceptance) +- (void)layoutBrowser; +- (void)rebuildGrid; +- (void)thumbnailClicked:(id)sender; +- (void)clearSelection:(id)sender; +- (void)importSelectedURLs:(NSArray *)urls; +@end +#endif +#include +#include + +static NSMutableArray *checks; +static void require(BOOL pass,NSString *name) { + [checks addObject:@{@"name":name,@"pass":@(pass)}]; + if(!pass){fprintf(stderr,"FAIL: %s\n",name.UTF8String);exit(1);} +} +static void pump(BOOL (^done)(void)) { + NSTimeInterval until=NSProcessInfo.processInfo.systemUptime+60; + while(!done()&&NSProcessInfo.processInfo.systemUptime0&&library.folders.count>0;}]; + NSTimeInterval start=NSProcessInfo.processInfo.systemUptime;__block BOOL done=NO;__block NSUInteger importedCount=0; +#ifdef DY_LUT_BASELINE + NSArray *imported=[library importURLs:@[source] error:&error];importedCount=imported.count;done=YES; +#else + [library importURLsAsync:@[source] completion:^(NSArray *imported,NSError *failure){require(NSThread.isMainThread,@"import completion is on main queue");require(failure==nil,@"bulk import succeeds");importedCount=imported.count;done=YES;}]; +#endif + pump(^{return done;});NSTimeInterval duration=NSProcessInfo.processInfo.systemUptime-start; + NSDate *settle=[NSDate dateWithTimeIntervalSinceNow:.03];while(settle.timeIntervalSinceNow>0)[[NSRunLoop mainRunLoop]runMode:NSDefaultRunLoopMode beforeDate:settle];[timer invalidate]; + require(importedCount==count&&library.entries.count==count+1,@"all files and previous entry preserved"); + NSMutableDictionary *report=[NSMutableDictionary dictionaryWithDictionary:@{@"bulkFiles":@(count),@"cubeDimension":@65,@"sourceBytes":@(large.length*count),@"importSeconds":@(duration),@"mainHeartbeatMaxGapMS":@(maxGap*1000),@"mainHeartbeatTicks":@(ticks),@"snapshotsReadDuringImport":@(snapshots)}]; +#ifndef DY_LUT_BASELINE + require(ticks>10&&maxGap<.15,@"main run loop stays responsive while importing"); + done=NO;__block BOOL cancelledDuringCopy=NO; + NSProgress *cancelled=[library importURLsAsync:@[source] completion:^(NSArray *items,NSError *failure){require(!items&&failure.code==NSUserCancelledError,@"cancelled import returns cancellation");done=YES;}]; + NSTimer *canceller=[NSTimer scheduledTimerWithTimeInterval:.001 repeats:YES block:^(NSTimer *t){if(cancelled.completedUnitCount>count){cancelledDuringCopy=YES;[cancelled cancel];[t invalidate];}}]; + pump(^{return done;});[canceller invalidate];require(cancelledDuringCopy,@"cancel exercised after copy had begun"); + require([library reload:&error]&&library.entries.count==count+1,@"cancel rolls back newly copied files only"); + done=NO;NSProgress *scan=[library reloadAsync:^(NSError *failure){require(failure.code==NSUserCancelledError,@"cancelled scan reports cancellation");done=YES;}];[scan cancel];pump(^{return done;}); + require(library.entries.count==count+1,@"cancelled scan preserves previous snapshot"); + done=NO;DYLUTPrepareAsync([source URLByAppendingPathComponent:@"Large-00.cube"].path,^(NSError *failure){require(!failure&&NSThread.isMainThread,@"cold selection prepares off thread and completes on main");done=YES;});pump(^{return done;}); + NSURL *bad=[root URLByAppendingPathComponent:@"Invalid.cube"];[@"invalid LUT" writeToURL:bad atomically:NO encoding:NSUTF8StringEncoding error:&error]; + done=NO;DYLUTPrepareAsync(bad.path,^(NSError *failure){require(failure!=nil,@"invalid selection reports failure asynchronously");done=YES;});pump(^{return done;}); + // Real browser objects, never shown; its grid should represent thousands of + // files with only visible/overscan buttons, including after a distant scroll. + NSURL *catalog=[destination URLByAppendingPathComponent:@"Catalog" isDirectory:YES];[fm createDirectoryAtURL:catalog withIntermediateDirectories:NO attributes:nil error:&error]; + BOOL catalogOK=YES;for(NSUInteger i=0;i<3000;i++){NSString *path=[catalog.path stringByAppendingPathComponent:[NSString stringWithFormat:@"Catalog-%04lu.cube",(unsigned long)i]];if(link(anchor.path.fileSystemRepresentation,path.fileSystemRepresentation)!=0){catalogOK=NO;break;}}require(catalogOK,@"3000 catalog fixtures created"); + [NSApplication sharedApplication];[NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited]; + NSMutableArray *selected=[NSMutableArray array]; + DYLUTBrowser *browser=[[DYLUTBrowser alloc]initWithLibrary:library preview:nil selectedPath:nil palette:@{} selection:^(NSString *path){[selected addObject:path?:@""];}]; + pump(^{return [browser valueForKey:@"libraryTask"]==nil;}); + NSUInteger visible=[[browser valueForKey:@"visibleEntries"]count],tileCount=[[browser valueForKey:@"tiles"]count]; + require(visible==3025&&tileCount>0&&tileCount<200,@"large catalog creates only visible thumbnail controls"); + NSScrollView *scroll=[browser valueForKey:@"gridScroll"];[scroll.contentView scrollToPoint:NSMakePoint(0,scroll.documentView.frame.size.height-scroll.contentSize.height)];[browser layoutBrowser]; + require([[browser valueForKey:@"tiles"]count]<200,@"scrolling keeps thumbnail view count bounded"); + NSSearchField *search=[browser valueForKey:@"search"];search.stringValue=@"Catalog-000";[browser rebuildGrid]; + require([[browser valueForKey:@"visibleEntries"]count]==10,@"search remains usable after catalog loading"); + NSDictionary *tiles=[browser valueForKey:@"tiles"];NSArray *keys=[tiles.allKeys sortedArrayUsingSelector:@selector(compare:)]; + [browser thumbnailClicked:tiles[keys[0]]];[browser thumbnailClicked:tiles[keys[1]]];pump(^{return [browser valueForKey:@"selectionTask"]==nil;}); + require(selected.count==1&&[selected.lastObject isEqual:keys[1]],@"rapid selection applies only the latest LUT"); + [browser thumbnailClicked:tiles[keys[0]]];[browser clearSelection:nil];pump(^{return [browser valueForKey:@"selectionTask"]==nil;}); + require([selected.lastObject isEqual:@""],@"clear selection supersedes pending LUT application"); + [browser importSelectedURLs:@[source]];[browser close];done=NO;[library reloadAsync:^(NSError *failure){require(!failure,@"scan after browser close completes");done=YES;}];pump(^{return done;}); + require(library.entries.count==3025,@"closing during import cancels without changing existing library"); + [browser release];report[@"largeCatalogEntries"]=@(visible);report[@"initialLiveThumbnailViews"]=@(tileCount);report[@"pass"]=@YES; +#else + report[@"mode"]=@"baseline synchronous import"; +#endif + report[@"checks"]=checks;report[@"scope"]=@"Synthetic 24 x 65-cube import with real main-run-loop heartbeat and snapshot reads; headless browser cancellation, latest selection and 3,025-entry virtualization. No user library or visible test app."; + NSData *json=[NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingPrettyPrinted error:&error];require([json writeToFile:[NSString stringWithUTF8String:argv[1]] atomically:YES],@"report written"); + require([fm removeItemAtURL:root error:&error],@"isolated fixtures removed");printf("PASS: import %.3fs, main gap %.1fms, %lu ticks\n",duration,maxGap*1000,(unsigned long)ticks);[checks release];return 0; +}} diff --git a/verification/LUTResponsiveness.json b/verification/LUTResponsiveness.json new file mode 100644 index 0000000..a390c2e --- /dev/null +++ b/verification/LUTResponsiveness.json @@ -0,0 +1,376 @@ +{ + "date": "2026-11-01", + "gpu": "Apple M4", + "osVersion": "27.0.1", + "baselineCommit": "57830ca74458a45cff207b76b5293e9dd17e273f", + "baseline": { + "mainHeartbeatMaxGapMS": 10018.783083301969, + "checks": [ + { + "name": "isolated source folder created", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "anchor fixture written", + "pass": true + }, + { + "name": "preexisting library item imported", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "all files and previous entry preserved", + "pass": true + } + ], + "bulkFiles": 24, + "mode": "baseline synchronous import", + "scope": "Synthetic 24 x 65-cube import with real main-run-loop heartbeat and snapshot reads; headless browser cancellation, latest selection and 3,025-entry virtualization. No user library or visible test app.", + "snapshotsReadDuringImport": 8, + "importSeconds": 10.018748541595414, + "cubeDimension": 65, + "sourceBytes": 197731344, + "mainHeartbeatTicks": 8 + }, + "background": { + "sourceBytes": 197731344, + "mainHeartbeatMaxGapMS": 6.287041702307761, + "bulkFiles": 24, + "checks": [ + { + "name": "isolated source folder created", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "synthetic 65-cube file written", + "pass": true + }, + { + "name": "anchor fixture written", + "pass": true + }, + { + "name": "preexisting library item imported", + "pass": true + }, + { + "name": "import completion is on main queue", + "pass": true + }, + { + "name": "bulk import succeeds", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "all files and previous entry preserved", + "pass": true + }, + { + "name": "main run loop stays responsive while importing", + "pass": true + }, + { + "name": "cancelled import returns cancellation", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "cancel exercised after copy had begun", + "pass": true + }, + { + "name": "cancel rolls back newly copied files only", + "pass": true + }, + { + "name": "cancelled scan reports cancellation", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "cancelled scan preserves previous snapshot", + "pass": true + }, + { + "name": "cold selection prepares off thread and completes on main", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "invalid selection reports failure asynchronously", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "3000 catalog fixtures created", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "large catalog creates only visible thumbnail controls", + "pass": true + }, + { + "name": "scrolling keeps thumbnail view count bounded", + "pass": true + }, + { + "name": "search remains usable after catalog loading", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "rapid selection applies only the latest LUT", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "clear selection supersedes pending LUT application", + "pass": true + }, + { + "name": "scan after browser close completes", + "pass": true + }, + { + "name": "background operation completes within timeout", + "pass": true + }, + { + "name": "closing during import cancels without changing existing library", + "pass": true + } + ], + "initialLiveThumbnailViews": 45, + "snapshotsReadDuringImport": 1493, + "scope": "Synthetic 24 x 65-cube import with real main-run-loop heartbeat and snapshot reads; headless browser cancellation, latest selection and 3,025-entry virtualization. No user library or visible test app.", + "mainHeartbeatTicks": 1493, + "pass": true, + "largeCatalogEntries": 3025, + "cubeDimension": 65, + "importSeconds": 7.432438375079073 + }, + "coreLibraryChecks": 92, + "coreLibraryPassed": true, + "limitations": [ + "Headless run-loop and AppKit objects with synthetic files; formal FCP interaction is a separate gate.", + "Measured on this Apple M4 with local APFS temporary files; network volumes, older Macs and other host versions were not benchmarked." + ] +} diff --git a/大鱼调色/Plugin/DYInspector.mm b/大鱼调色/Plugin/DYInspector.mm index 754eb30..1272344 100644 --- a/大鱼调色/Plugin/DYInspector.mm +++ b/大鱼调色/Plugin/DYInspector.mm @@ -387,6 +387,8 @@ static NSImage *DYWheelImage(void) { NSMutableDictionary *_tabs; NSInteger _visibleLooks; BOOL _refreshing; + NSMutableDictionary *_assetLoads; + NSProgress *_menuScan; } @end @@ -396,7 +398,7 @@ static NSImage *DYWheelImage(void) { } - (instancetype)initWithAPIManager:(id)manager renderer:(DYRenderer *)renderer { if((self=[super initWithFrame:NSMakeRect(0,0,360,780)])) { - _manager=manager; _renderer=[renderer retain];_library=[DYLUTLibrary new];_tabs=[NSMutableDictionary new];_visibleLooks=1; + _assetLoads=[NSMutableDictionary new];_manager=manager; _renderer=[renderer retain];_library=[DYLUTLibrary new];_tabs=[NSMutableDictionary new];_visibleLooks=1; _sections=[DYPresentationSections() copy]; _cards=[[NSMutableArray alloc] init]; _controls=[[NSMutableDictionary alloc] init]; _assetButtons=[[NSMutableDictionary alloc] init]; _graphics=[[NSMutableArray alloc] init]; @@ -406,7 +408,7 @@ static NSImage *DYWheelImage(void) { self.layer.backgroundColor=[DYThemePalette()[@"background"] CGColor]; self.appearance=[NSAppearance appearanceNamed:NSAppearanceNameDarkAqua]; _brand=[DYLabel(@"◒ 大鱼调色",16) retain]; _brand.font=[NSFont boldSystemFontOfSize:16];_brand.textColor=DYInk(); - _subtitle=[DYLabel(@"1.1",9) retain]; _subtitle.textColor=DYThemeColor(@"secondary"); + _subtitle=[DYLabel([[NSBundle bundleForClass:self.class]objectForInfoDictionaryKey:@"CFBundleShortVersionString"]?:@"1.1.3",9) retain]; _subtitle.textColor=DYThemeColor(@"secondary"); _resetAll=[DYButton(@"↺",self,@selector(resetAll:)) retain];_resetAll.bordered=NO; _resetAll.toolTip=@"恢复全部调色参数与 LUT";_resetAll.accessibilityLabel=@"全部还原"; _save=[DYButton(@"保存预设",self,@selector(savePreset:)) retain]; _load=[DYButton(@"载入预设",self,@selector(loadPreset:)) retain]; @@ -437,6 +439,7 @@ static NSImage *DYWheelImage(void) { return self; } - (void)dealloc { + for(NSProgress *p in _assetLoads.allValues)[p cancel];[_assetLoads release];[_menuScan cancel];[_menuScan release]; [[NSNotificationCenter defaultCenter] removeObserver:self]; [_brand release]; [_subtitle release]; [_resetAll release]; [_save release]; [_load release]; [_export release]; [_scroll release]; [_document release]; [_sections release]; [_cards release]; [_controls release]; [_assetButtons release]; [_graphics release]; [_sampler release]; @@ -452,6 +455,7 @@ static NSImage *DYWheelImage(void) { - (NSSize)intrinsicContentSize { return NSMakeSize(360,780); } - (void)viewDidMoveToWindow { [super viewDidMoveToWindow]; + if(!self.window){for(NSProgress *p in _assetLoads.allValues)[p cancel];[_assetLoads removeAllObjects];} if(self.window) { [self refresh]; NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification); @@ -707,7 +711,7 @@ static NSImage *DYWheelImage(void) { NSString *path=assets.paths[key]; NSButton *button=_assetButtons[key][@"choose"]; NSString *name=path.length?path.lastPathComponent.stringByDeletingPathExtension:@"无"; if([key isEqual:@"input"]&&!path.length){double profile=0;[get getFloatValue:&profile fromParameter:2013 atTime:t];for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"inputProfile"]){NSArray *options=d[@"options"];NSInteger index=MAX(0,MIN((NSInteger)llround(profile),(NSInteger)options.count-1));name=options[index];break;}} - button.title=name; button.toolTip=path.length?path:@"选择输入转换或 LUT;点击网格图标浏览缩略图"; + button.title=_assetLoads[key]?@"正在载入…":name; button.toolTip=path.length?path:@"选择输入转换或 LUT;点击网格图标浏览缩略图"; [_assetButtons[key][@"remove"] setEnabled:path.length>0]; NSButton *eye=_assetButtons[key][@"eye"];if(eye){NSInteger slot=[[key substringFromIndex:4]integerValue];double enabled=1;[get getFloatValue:&enabled fromParameter:2040+(UInt32)slot-1 atTime:t];eye.state=enabled>=.5?NSControlStateValueOn:NSControlStateValueOff;eye.image=[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"];} } @@ -787,6 +791,7 @@ static NSImage *DYWheelImage(void) { [self setSectionEnabled:[_cards[sender.tag][@"collapsed"]boolValue] atIndex:sender.tag]; } - (void)resetSection:(NSButton *)sender { + [self cancelAssetLoads]; if(sender.tag>=_cards.count)return; NSDictionary *section=_cards[sender.tag][@"section"]; id action=[self actionAPI];if(!action)return; @@ -811,6 +816,7 @@ static NSImage *DYWheelImage(void) { [self postChanged]; } - (void)resetAll:(id)sender { + [self cancelAssetLoads]; id action=[self actionAPI];if(!action)return; [action startAction:self]; @try { @@ -821,16 +827,18 @@ static NSImage *DYWheelImage(void) { [self postChanged]; } - (void)chooseAsset:(NSButton *)sender { - [_library reload:NULL];NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"LUT"]autorelease]; + if(!_menuScan)_menuScan=[[_library reloadAsync:^(NSError *error){[_menuScan release];_menuScan=nil;}]retain]; + NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"LUT"]autorelease]; NSMenuItem *none=[menu addItemWithTitle:@"无" action:@selector(assetMenuItem:) keyEquivalent:@""];none.target=self;none.representedObject=@{@"key":sender.identifier,@"path":@"",@"profile":@0}; if([sender.identifier isEqual:@"input"]){for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"inputProfile"]){NSInteger i=0;for(NSString *title in d[@"options"]){if(i){NSMenuItem *item=[menu addItemWithTitle:title action:@selector(assetMenuItem:) keyEquivalent:@""];item.target=self;item.representedObject=@{@"key":@"input",@"profile":@(i),@"path":@""};}i++;}break;}} [menu addItem:NSMenuItem.separatorItem];NSMenuItem *browser=[menu addItemWithTitle:@"缩略图浏览库…" action:@selector(assetMenuBrowse:) keyEquivalent:@""];browser.target=self;browser.representedObject=sender.identifier; NSMenuItem *file=[menu addItemWithTitle:@"载入 LUT 文件…" action:@selector(assetMenuFile:) keyEquivalent:@""];file.target=self;file.representedObject=sender.identifier; NSMutableDictionary *folders=[NSMutableDictionary dictionary];NSUInteger count=0; - for(NSDictionary *entry in _library.entries){if(count++>=1000)break;NSString *folder=entry[@"relativeFolder"];NSMenu *parent=menu; + for(NSDictionary *entry in _library.entries){if(count++>=100)break;NSString *folder=entry[@"relativeFolder"];NSMenu *parent=menu; if(folder.length){parent=folders[folder];if(!parent){NSMenuItem *group=[menu addItemWithTitle:folder action:nil keyEquivalent:@""];parent=[[[NSMenu alloc]initWithTitle:folder]autorelease];group.submenu=parent;folders[folder]=parent;}} NSMenuItem *item=[parent addItemWithTitle:entry[@"name"] action:@selector(assetMenuItem:) keyEquivalent:@""];item.target=self;item.representedObject=@{@"key":sender.identifier,@"path":entry[@"path"]}; } + if(_library.entries.count>100){NSMenuItem *more=[menu addItemWithTitle:@"更多 LUT,请打开缩略图浏览库…" action:@selector(assetMenuBrowse:) keyEquivalent:@""];more.target=self;more.representedObject=sender.identifier;} [menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(0,sender.bounds.size.height) inView:sender]; } - (void)assetMenuBrowse:(NSMenuItem *)item {NSButton *button=_assetButtons[item.representedObject][@"browse"];[self browseAsset:button];} @@ -843,8 +851,7 @@ static NSImage *DYWheelImage(void) { - (void)chooseFileForKey:(NSString *)key { NSOpenPanel *panel=[NSOpenPanel openPanel];panel.allowedFileTypes=@[@"cube"];panel.allowsMultipleSelection=NO; panel.canChooseDirectories=NO;panel.message=@"选择 .cube 立体 LUT"; - if([panel runModal]!=NSModalResponseOK)return; - [self setAssetPath:panel.URL.path forKey:key]; + [panel beginWithCompletionHandler:^(NSModalResponse response){if(response==NSModalResponseOK&&self.window)[self setAssetPath:panel.URL.path forKey:key];}]; } - (void)browseAsset:(NSButton *)sender { [_browser close];[_browser release];_browser=nil; @@ -866,7 +873,19 @@ static NSImage *DYWheelImage(void) { } - (void)removeAsset:(NSButton *)sender { [self setAssetPath:nil forKey:sender.identifier]; } - (void)setAssetPath:(NSString *)path forKey:(NSString *)key { - if(path.length){std::vector values;NSUInteger size=0;NSError *error=nil;if(!DYLUTReadCube(path,values,size,&error)){[self showError:error.localizedDescription];return;}} + [_assetLoads[key]cancel];[_assetLoads removeObjectForKey:key]; + if(!path.length){[self commitAssetPath:nil forKey:key];return;} + __block NSProgress *task=nil; + task=DYLUTPrepareAsync(path,^(NSError *error){ + if(_assetLoads[key]!=task||!self.window)return;[_assetLoads removeObjectForKey:key]; + if(error){[self refresh];[_assetButtons[key][@"choose"]setToolTip:error.localizedDescription];return;} + [self commitAssetPath:path forKey:key]; + });_assetLoads[key]=task;[_assetButtons[key][@"choose"]setTitle:@"正在载入…"]; +} +- (void)cancelAssetLoads { + for(NSProgress *p in _assetLoads.allValues)[p cancel];[_assetLoads removeAllObjects]; +} +- (void)commitAssetPath:(NSString *)path forKey:(NSString *)key { id action=[self actionAPI];if(!action)return; [action startAction:self]; @try { @@ -917,6 +936,7 @@ static NSImage *DYWheelImage(void) { if(![path isKindOfClass:NSString.class]||![path isAbsolutePath]||![[path pathExtension].lowercaseString isEqual:@"cube"]){[self showError:@"预设包含无效 LUT 路径,尚未修改当前调色。"];return;} if([[NSFileManager defaultManager] isReadableFileAtPath:path])validPaths[key]=path;else [missing addObject:[path lastPathComponent]]; } + [self cancelAssetLoads]; id action=[self actionAPI];if(!action)return; [action startAction:self]; @try { diff --git a/大鱼调色/Plugin/DYLUTBrowser.mm b/大鱼调色/Plugin/DYLUTBrowser.mm index e5b2a2a..c778a66 100644 --- a/大鱼调色/Plugin/DYLUTBrowser.mm +++ b/大鱼调色/Plugin/DYLUTBrowser.mm @@ -121,7 +121,12 @@ static NSString *const DYBrowserFolderPreference=@"com.dayu.color.lookLUTPreview NSCache *_thumbnailCache; dispatch_queue_t _previewQueue; DYBrowserWork *_work; - BOOL _closed,_sizing,_visible,_remoteMode,_importing; + BOOL _closed,_sizing,_visible,_remoteMode,_importing,_layingOut; + NSProgress *_libraryTask,*_selectionTask; + NSTimer *_progressTimer; + NSUInteger _libraryGeneration,_selectionGeneration; + NSInteger _columns; + CGFloat _tileWidth,_tileHeight; } @end @@ -168,6 +173,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b } - (void)dealloc{ [NSObject cancelPreviousPerformRequestsWithTarget:self];[[NSNotificationCenter defaultCenter]removeObserver:self]; + [_libraryTask cancel];[_libraryTask release];[_selectionTask cancel];[_selectionTask release];[_progressTimer invalidate];[_progressTimer release]; _work.cancelled=YES;_work.owner=nil;[_work release];self.window.delegate=nil; _popover.delegate=nil;[_popover close];[_popover release];[_root removeFromSuperview]; [_library release];[_preview release];[_selectedPath release];[_folder release];[_palette release];[_selection release];[_closeAction release]; @@ -214,7 +220,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b // The API owner's completion may release this controller synchronously. [self retain]; [NSObject cancelPreviousPerformRequestsWithTarget:self]; - _closed=YES;_visible=NO;_work.cancelled=YES;_work.owner=nil; + _closed=YES;_visible=NO;_work.cancelled=YES;_work.owner=nil;[_libraryTask cancel];[_selectionTask cancel];[_progressTimer invalidate];[_progressTimer release];_progressTimer=nil; _popover.delegate=nil;if(_popover.shown)[_popover close]; [_root removeFromSuperview];[_queuedPaths removeAllObjects];[_thumbnailCache removeAllObjects]; [_selection release];_selection=nil; @@ -223,6 +229,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b [self release]; } - (void)layoutBrowser{ + if(_layingOut)return;_layingOut=YES; CGFloat w=_root.bounds.size.width,h=_root.bounds.size.height,left=162; _titleLabel.frame=NSMakeRect(12,15,145,20);_countLabel.frame=NSMakeRect(12,39,145,18); _search.frame=NSMakeRect(left+14,14,MAX(125,w-left-351),24); @@ -237,12 +244,30 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b _folderDocument.frame=NSMakeRect(0,0,fw,MAX(fy,_folderScroll.contentSize.height)); CGFloat available=MAX(80,_gridScroll.contentSize.width),tileWidth=_sizeSlider.doubleValue,gap=10; NSInteger columns=MAX(1,(NSInteger)floor((available+gap)/(tileWidth+gap)));tileWidth=MIN(tileWidth,(available-gap*(columns-1)-14)/columns);tileWidth=MAX(70,tileWidth); - CGFloat tileHeight=ceil(tileWidth*9/16)+24,x=7,y=8;NSInteger index=0; - for(NSDictionary *entry in _visibleEntries){DYBrowserTile *tile=_tiles[entry[@"path"]];NSInteger col=index%columns,row=index/columns;tile.frame=NSMakeRect(x+col*(tileWidth+gap),y+row*(tileHeight+gap),tileWidth,tileHeight);index++;} - NSInteger rows=(_visibleEntries.count+columns-1)/columns;CGFloat contentHeight=MAX(_gridScroll.contentSize.height,rows*(tileHeight+gap)+12); + _columns=columns;_tileWidth=tileWidth;_tileHeight=ceil(tileWidth*9/16)+24; + NSInteger rows=(_visibleEntries.count+columns-1)/columns;CGFloat contentHeight=MAX(_gridScroll.contentSize.height,rows*(_tileHeight+gap)+12); _gridDocument.frame=NSMakeRect(0,0,available,contentHeight);_emptyLabel.frame=NSMakeRect(20,MAX(36,_gridScroll.contentSize.height/2-45),MAX(50,available-40),90); + _layingOut=NO;[self updateVisibleTiles]; +} +- (void)resetThumbnailWork { + _work.cancelled=YES;_work.owner=nil;[_work release];_work=[DYBrowserWork new];_work.owner=self;[_queuedPaths removeAllObjects]; +} +- (void)updateVisibleTiles { + if(_closed||_layingOut||_columns<1)return; + NSRect visible=NSInsetRect(_gridScroll.contentView.bounds,-30,-180);CGFloat step=_tileHeight+10; + NSUInteger first=(NSUInteger)MAX(0,floor((NSMinY(visible)-8)/step))*_columns; + NSUInteger end=MIN(_visibleEntries.count,(NSUInteger)MAX(0,ceil((NSMaxY(visible)-8)/step)+1)*_columns); + NSMutableSet *wanted=[NSMutableSet set];BOOL changed=NO; + for(NSUInteger i=first;i0; - for(NSDictionary *entry in entries){ - NSString *path=entry[@"path"];DYBrowserTile *tile=[[[DYBrowserTile alloc]initWithFrame:NSZeroRect]autorelease];tile.identifier=path;tile.displayName=entry[@"name"];tile.toolTip=entry[@"relativePath"]?:path;tile.palette=_palette;tile.chosen=[path isEqualToString:_selectedPath];tile.target=self;tile.action=@selector(thumbnailClicked:);tile.enabled=NO;[_gridDocument addSubview:tile];_tiles[path]=tile; - } - [self layoutBrowser];[_gridScroll.contentView scrollToPoint:NSZeroPoint];[_gridScroll reflectScrolledClipView:_gridScroll.contentView]; + [_gridScroll.contentView scrollToPoint:NSZeroPoint];[self layoutBrowser];[_gridScroll reflectScrolledClipView:_gridScroll.contentView]; NSAccessibilityPostNotification(_gridDocument,NSAccessibilityLayoutChangedNotification); } - (void)thumbnailClicked:(DYBrowserTile *)sender{ - if(!sender.enabled||!sender.thumbnail||sender.failure.length)return; - std::vector values;NSUInteger dimension=0;NSError *error=nil; - if(!DYLUTReadCube(sender.identifier,values,dimension,&error)){ - sender.failure=error.localizedDescription?:@"LUT 文件已失效,请刷新浏览库";sender.enabled=NO;[sender setNeedsDisplay:YES];[self setStatus:sender.failure];return; - } - [_selectedPath release];_selectedPath=[sender.identifier copy]; - for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=[tile.identifier isEqualToString:_selectedPath];[tile setNeedsDisplay:YES];} - [self setStatus:[NSString stringWithFormat:@"已应用 %@",sender.displayName]]; - if(_selection)_selection(_selectedPath); - if(sender.doubleClicked)[self close]; + if(!sender.enabled||sender.failure.length)return; + [_selectionTask cancel];[_selectionTask release];NSUInteger generation=++_selectionGeneration; + NSString *path=sender.identifier,*name=sender.displayName;BOOL closeAfter=sender.doubleClicked;[self setStatus:[@"正在载入 " stringByAppendingString:name]]; + _selectionTask=[DYLUTPrepareAsync(path,^(NSError *error){ + if(_closed||generation!=_selectionGeneration)return;[_selectionTask release];_selectionTask=nil; + if(error){[self setStatus:error.localizedDescription];return;} + [_selectedPath release];_selectedPath=[path copy]; + for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=[tile.identifier isEqualToString:path];[tile setNeedsDisplay:YES];} + if(_selection)_selection(path);[self setStatus:[@"已选择 " stringByAppendingString:name]];if(closeAfter)[self close]; + })retain]; } - (void)clearSelection:(id)sender{ + ++_selectionGeneration;[_selectionTask cancel];[_selectionTask release];_selectionTask=nil; [_selectedPath release];_selectedPath=nil; for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=NO;[tile setNeedsDisplay:YES];} if(_selection)_selection(nil);[self setStatus:@"已移除 LUT"]; } - (void)done:(id)sender{[self close];} -- (void)showImportError:(NSError *)error{ - if(!error||_closed)return;NSAlert *alert=[[[NSAlert alloc]init]autorelease];alert.messageText=@"LUT 导入未完成";alert.informativeText=error.localizedDescription?:@"请选择有效的 .cube LUT 文件。";[alert addButtonWithTitle:@"好"]; - _importing=YES;[alert runModal];_importing=NO; +- (void)showImportError:(NSError *)error{if(error&&!_closed)[self setStatus:error.localizedDescription];} +- (void)importSelectedURLs:(NSArray *)urls { + if(_closed||_libraryTask)return;NSUInteger generation=++_libraryGeneration; + NSProgress *task=[_library importURLsAsync:urls completion:^(NSArray *imported,NSError *error){ + if(_closed||generation!=_libraryGeneration)return;[self endLibraryTask]; + if(!imported){[self showImportError:error];return;} + [_thumbnailCache removeAllObjects];[self rebuildFolders];[self rebuildGrid];[self setStatus:[NSString stringWithFormat:@"已导入 %lu 个 LUT",(unsigned long)imported.count]]; + }];[self beginLibraryTask:task]; } - (void)importPanelForFolders:(BOOL)folders{ + if(_libraryTask||_importing||_closed)return; NSOpenPanel *panel=[NSOpenPanel openPanel];panel.canChooseFiles=!folders;panel.canChooseDirectories=folders;panel.allowsMultipleSelection=YES;panel.title=folders?@"导入 LUT 文件夹":@"导入 LUT 文件";panel.message=folders?@"所选文件夹中的 .cube 文件会按目录复制到大鱼调色 LUT 库。":@"选择要复制到大鱼调色 LUT 库的 .cube 文件。"; if(!folders)panel.allowedFileTypes=@[@"cube"]; - _importing=YES;NSModalResponse response=[panel runModal];_importing=NO; - if(response!=NSModalResponseOK||_closed)return;NSError *error=nil;NSArray *imported=[_library importURLs:panel.URLs error:&error]; - if(!imported){[self showImportError:error];return;} - [self rebuildFolders];[self rebuildGrid];[self setStatus:[NSString stringWithFormat:@"已导入 %lu 个 LUT",(unsigned long)imported.count]]; + _importing=YES;[panel beginWithCompletionHandler:^(NSModalResponse response){_importing=NO;if(response==NSModalResponseOK&&!_closed)[self importSelectedURLs:panel.URLs];}]; } - (void)importFiles:(id)sender{[self importPanelForFolders:NO];} - (void)importFolder:(id)sender{[self importPanelForFolders:YES];} diff --git a/大鱼调色/Plugin/DYLUTLibrary.h b/大鱼调色/Plugin/DYLUTLibrary.h index f57ae12..5e51c96 100644 --- a/大鱼调色/Plugin/DYLUTLibrary.h +++ b/大鱼调色/Plugin/DYLUTLibrary.h @@ -13,6 +13,11 @@ FOUNDATION_EXPORT BOOL DYLUTReadCube(NSString *path, std::vector& values, NSUInteger& dimension, NSError * _Nullable * _Nullable error); #endif +/// Parse/warm the shared table cache off the UI thread. Completion is always on +/// the main queue; cancel suppresses application of the result. +FOUNDATION_EXPORT NSProgress *DYLUTPrepareAsync(NSString *path, + void (^completion)(NSError * _Nullable error)); + /// Float RGBA in display-encoded RGB, matching the renderer's 320×180 preview. /// Empty path means identity. Alpha is preserved; invalid samples become clear. FOUNDATION_EXPORT NSData * _Nullable DYLUTTransformRGBA(NSData *sourceRGBA, @@ -35,6 +40,12 @@ FOUNDATION_EXPORT NSImage * _Nullable DYLUTThumbnail(NSString * _Nullable path, - (instancetype)initWithRootURL:(NSURL *)rootURL NS_DESIGNATED_INITIALIZER; /// Does not follow symbolic links or create a missing root directory. - (BOOL)reload:(NSError * _Nullable * _Nullable)error; +/// Background file work is serialized separately from the short snapshot lock. +/// The returned progress supports cancellation and per-file status; callbacks +/// always run on the main queue. Existing snapshots remain readable meanwhile. +- (NSProgress *)reloadAsync:(void (^)(NSError * _Nullable error))completion; +- (NSProgress *)importURLsAsync:(NSArray *)urls + completion:(void (^)(NSArray * _Nullable imported, NSError * _Nullable error))completion; /// Copies Cube files (recursing into folders) into the library. No existing file /// is replaced. Names receive numeric suffixes on collision. Source data stays put. /// Returns imported entry dictionaries, or nil on preflight/copy failure. diff --git a/大鱼调色/Plugin/DYLUTLibrary.mm b/大鱼调色/Plugin/DYLUTLibrary.mm index adb7942..c986b8d 100644 --- a/大鱼调色/Plugin/DYLUTLibrary.mm +++ b/大鱼调色/Plugin/DYLUTLibrary.mm @@ -1,5 +1,9 @@ #import "DYLUTLibrary.h" #include +#include +#include +#include +#include #include #include #include @@ -58,7 +62,12 @@ static void DYLUTSample(const std::vector& table,NSUInteger n,const float } } -static BOOL DYLUTParse(NSString *path,std::vector& data,NSUInteger& size,NSError **error) { +static BOOL DYLUTCancelled(NSProgress *progress,NSError **error) { + if(!progress.cancelled)return NO; + if(error)*error=[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:@{NSLocalizedDescriptionKey:@"已取消 LUT 加载"}]; + return YES; +} +static BOOL DYLUTParse(NSString *path,std::vector& data,NSUInteger& size,NSProgress *progress,NSError **error) { data.clear();size=0; NSDictionary *attributes=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:error]; if(!attributes)return NO; @@ -76,28 +85,37 @@ static BOOL DYLUTParse(NSString *path,std::vector& data,NSUInteger& size, for(float v:data)if(!std::isfinite(v))return DYLUTFail(error,@"输入 LUT 含无效数字"); size=n;return YES; } - NSString *text=[[[NSString alloc]initWithData:bytes encoding:NSUTF8StringEncoding]autorelease]; - if(!text)return DYLUTFail(error,@"LUT 必须是 UTF-8 文本"); - float domainMin[3]={0,0,0},domainMax[3]={1,1,1}; - BOOL foundSize=NO; - for(NSString *line in [text componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { - NSString *clean=[[[line componentsSeparatedByString:@"#"]firstObject]stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; - if(!clean.length)continue; - const char *c=clean.UTF8String;int n=0;float r,g,b; - if(sscanf(c,"LUT_3D_SIZE %d",&n)==1) { - if(foundSize||n<2||n>128)return DYLUTFail(error,@"LUT 尺寸应为 2–128,且只能声明一次"); + // Validate encoding once, then parse byte spans without allocating an + // NSString, NSArray and temporary strings for every numeric row. + NSString *text=[[NSString alloc]initWithData:bytes encoding:NSUTF8StringEncoding]; + if(!text)return DYLUTFail(error,@"LUT 必须是 UTF-8 文本");[text release]; + std::string storage((const char *)bytes.bytes,bytes.length); + static locale_t numericLocale;static dispatch_once_t localeOnce;dispatch_once(&localeOnce,^{numericLocale=newlocale(LC_NUMERIC_MASK,"C",NULL);}); + float domainMin[3]={0,0,0},domainMax[3]={1,1,1};BOOL foundSize=NO; + std::string_view remaining(storage);NSUInteger rows=0; + if(remaining.size()>=3&&remaining.substr(0,3)=="\xef\xbb\xbf")remaining.remove_prefix(3); + auto trim=[](std::string_view v){while(!v.empty()&&(v.front()==' '||v.front()=='\t'||v.front()=='\r'))v.remove_prefix(1);return v;}; + auto number=[&](std::string_view& v,float& value){v=trim(v);if(v.empty())return false;char *end=nullptr;value=strtof_l(v.data(),&end,numericLocale);if(end==v.data()||end>v.data()+v.size())return false;v.remove_prefix(end-v.data());return true;}; + while(!remaining.empty()) { + if((rows++&1023)==0&&DYLUTCancelled(progress,error))return NO; + size_t end=remaining.find_first_of("\r\n");std::string_view line=remaining.substr(0,end); + if(end==std::string_view::npos)remaining={};else remaining.remove_prefix(end+1); + line=line.substr(0,line.find('#'));line=trim(line);if(line.empty())continue; + float r=0,g=0,b=0; + auto starts=[&](std::string_view prefix){return line.substr(0,prefix.size())==prefix;}; + if(starts("LUT_3D_SIZE")) { + auto v=trim(line.substr(11));int n=0;auto result=std::from_chars(v.data(),v.data()+v.size(),n); + if(result.ec!=std::errc{}||foundSize||n<2||n>128)return DYLUTFail(error,@"LUT 尺寸应为 2–128,且只能声明一次"); size=n;foundSize=YES;data.reserve(size*size*size*4); - } else if(sscanf(c,"DOMAIN_MIN %f %f %f",&r,&g,&b)==3) { - domainMin[0]=r;domainMin[1]=g;domainMin[2]=b; - } else if(sscanf(c,"DOMAIN_MAX %f %f %f",&r,&g,&b)==3) { - domainMax[0]=r;domainMax[1]=g;domainMax[2]=b; - } else if(sscanf(c,"%f %f %f",&r,&g,&b)==3) { - if(!std::isfinite(r)||!std::isfinite(g)||!std::isfinite(b))return DYLUTFail(error,@"LUT 含无效数字"); - data.insert(data.end(),{r,g,b,1}); - if(data.size()>128*128*128*4)return DYLUTFail(error,@"LUT 数据过多"); - } else if([clean hasPrefix:@"LUT_1D_SIZE"])return DYLUTFail(error,@"请选择三维 .cube LUT"); - else if(![clean hasPrefix:@"TITLE"]&&![clean hasPrefix:@"LUT_3D_INPUT_RANGE"]) - return DYLUTFail(error,[NSString stringWithFormat:@"无法解析 LUT 行:%@",[clean substringToIndex:MIN(clean.length,(NSUInteger)80)]]); + } else if(starts("DOMAIN_MIN")||starts("DOMAIN_MAX")) { + auto v=line.substr(10);if(!number(v,r)||!number(v,g)||!number(v,b))return DYLUTFail(error,@"LUT DOMAIN 范围无效"); + float *domain=starts("DOMAIN_MIN")?domainMin:domainMax;domain[0]=r;domain[1]=g;domain[2]=b; + } else if(starts("TITLE")||starts("LUT_3D_INPUT_RANGE"))continue; + else if(starts("LUT_1D_SIZE"))return DYLUTFail(error,@"请选择三维 .cube LUT"); + else { + auto v=line;if(!number(v,r)||!number(v,g)||!number(v,b)||!std::isfinite(r)||!std::isfinite(g)||!std::isfinite(b))return DYLUTFail(error,@"LUT 含无效数据行"); + data.insert(data.end(),{r,g,b,1});if(data.size()>128*128*128*4)return DYLUTFail(error,@"LUT 数据过多"); + } } if(size<2||data.size()!=size*size*size*4)return DYLUTFail(error,@"LUT 数据数量与尺寸不符"); bool resample=false; @@ -108,6 +126,7 @@ static BOOL DYLUTParse(NSString *path,std::vector& data,NSUInteger& size, if(resample) { std::vector original=data; for(NSUInteger z=0;z& data,NSUInteger& size, return YES; } -BOOL DYLUTReadCube(NSString *path,std::vector& data,NSUInteger& size,NSError **error) { +static BOOL DYLUTReadCancellable(NSString *path,std::vector& data,NSUInteger& size,NSProgress *progress,NSError **error) { data.clear();size=0; if(!path.length)return DYLUTFail(error,@"未选择 LUT 文件"); NSDictionary *a=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:error]; @@ -127,12 +146,26 @@ BOOL DYLUTReadCube(NSString *path,std::vector& data,NSUInteger& size,NSEr DYLUTTable *cached=[DYLUTTableCache()objectForKey:key]; if(cached){data=cached->values;size=cached->dimension;return YES;} std::vector parsed;NSUInteger n=0; - if(!DYLUTParse(path,parsed,n,error))return NO; + if(DYLUTCancelled(progress,error)||!DYLUTParse(path,parsed,n,progress,error))return NO; DYLUTTable *table=[[[DYLUTTable alloc]init]autorelease];table->values=std::move(parsed);table->dimension=n; [DYLUTTableCache()setObject:table forKey:key cost:table->values.size()*sizeof(float)]; data=table->values;size=n;return YES; } +BOOL DYLUTReadCube(NSString *path,std::vector& data,NSUInteger& size,NSError **error) { + return DYLUTReadCancellable(path,data,size,nil,error); +} +NSProgress *DYLUTPrepareAsync(NSString *path,void (^completion)(NSError *)) { + static dispatch_queue_t queue;static dispatch_once_t once; + dispatch_once(&once,^{queue=dispatch_queue_create("com.dayu.color.lut-selection",DISPATCH_QUEUE_SERIAL);dispatch_set_target_queue(queue,dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0));}); + NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:1];progress.localizedDescription=@"正在载入 LUT…"; + dispatch_async(queue,^{@autoreleasepool{ + NSError *error=nil;std::vector values;NSUInteger n=0; + DYLUTReadCancellable(path,values,n,progress,&error);DYLUTCancelled(progress,&error);progress.completedUnitCount=1; + dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(error);}); + }});return progress; +} + NSData *DYLUTTransformRGBA(NSData *source,NSUInteger width,NSUInteger height,NSString *path,NSError **error) { if(!width||!height||width>8192||height>8192||width*height>8192*8192||source.length!=width*height*16) { DYLUTFail(error,@"缩略图源必须是有效的 float RGBA 图像");return nil; @@ -238,6 +271,8 @@ static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) { NSURL *_rootURL; NSArray *_entries,*_folders; NSMutableSet *_favoritePaths; + NSObject *_fileLock; + dispatch_queue_t _fileQueue; } @end @implementation DYLUTLibrary @@ -246,25 +281,30 @@ static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) { - (instancetype)initWithRootURL:(NSURL *)rootURL { if(!rootURL.isFileURL||!rootURL.path.length){[self release];return nil;} if((self=[super init])) { + _fileLock=[NSObject new];_fileQueue=dispatch_queue_create("com.dayu.color.lut-files",DISPATCH_QUEUE_SERIAL);dispatch_set_target_queue(_fileQueue,dispatch_get_global_queue(QOS_CLASS_UTILITY,0)); _rootURL=[DYLUTCanonicalURL(rootURL)copy];_entries=[@[]copy];_folders=[@[@""]copy];_favoritePaths=[NSMutableSet new]; NSDictionary *saved=[NSDictionary dictionaryWithContentsOfURL:[_rootURL URLByAppendingPathComponent:@".favorites.plist"]]; NSArray *relativePaths=[saved[@"relativePaths"]isKindOfClass:NSArray.class]?saved[@"relativePaths"]:@[]; for(NSString *path in relativePaths)if([path isKindOfClass:NSString.class]&&![path isAbsolutePath]&&![path.pathComponents containsObject:@".."]) [_favoritePaths addObject:[_rootURL.path stringByAppendingPathComponent:path]]; }return self; } -- (void)dealloc {[_rootURL release];[_entries release];[_folders release];[_favoritePaths release];[super dealloc];} +- (void)dealloc {[_rootURL release];[_entries release];[_folders release];[_favoritePaths release];[_fileLock release];dispatch_release(_fileQueue);[super dealloc];} - (NSURL *)rootURL {return [[_rootURL copy]autorelease];} - (NSArray *)entries {@synchronized(self){return [[_entries copy]autorelease];}} - (NSArray *)folders {@synchronized(self){return [[_folders copy]autorelease];}} - (NSSet *)favoritePaths {@synchronized(self){return [[_favoritePaths copy]autorelease];}} -- (BOOL)reload:(NSError **)error {@synchronized(self){ +- (BOOL)reload:(NSError **)error {return [self reloadProgress:nil error:error];} +- (BOOL)reloadProgress:(NSProgress *)progress error:(NSError **)error {@synchronized(_fileLock){ BOOL isDirectory=NO;NSFileManager *fm=NSFileManager.defaultManager; - if(![fm fileExistsAtPath:_rootURL.path isDirectory:&isDirectory]){[_entries release];_entries=[@[]copy];[_folders release];_folders=[@[@""]copy];return YES;} + if(DYLUTCancelled(progress,error))return NO; + if(![fm fileExistsAtPath:_rootURL.path isDirectory:&isDirectory]){@synchronized(self){[_entries release];_entries=[@[]copy];[_folders release];_folders=[@[@""]copy];}return YES;} if(!isDirectory||!DYLUTOrdinaryURL(_rootURL,NULL,error))return DYLUTFail(error,@"LUT 库目录无效"); NSMutableArray *entries=[NSMutableArray array];NSMutableSet *folders=[NSMutableSet setWithObject:@""]; __block NSError *scanError=nil; NSDirectoryEnumerator *enumerator=[fm enumeratorAtURL:_rootURL includingPropertiesForKeys:@[NSURLIsDirectoryKey,NSURLIsRegularFileKey,NSURLIsSymbolicLinkKey] options:NSDirectoryEnumerationSkipsHiddenFiles|NSDirectoryEnumerationSkipsPackageDescendants errorHandler:^BOOL(NSURL *url,NSError *e){(void)url;scanError=e;return NO;}]; for(NSURL *url in enumerator) { + if(DYLUTCancelled(progress,error))return NO; + progress.completedUnitCount++; NSNumber *link=nil;[url getResourceValue:&link forKey:NSURLIsSymbolicLinkKey error:NULL]; if(link.boolValue){[enumerator skipDescendants];continue;} BOOL directory=NO;if(!DYLUTOrdinaryURL(url,&directory,NULL))continue; @@ -275,12 +315,15 @@ static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) { } if(scanError){if(error)*error=scanError;return NO;} [entries sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){return [a[@"relativePath"]localizedStandardCompare:b[@"relativePath"]];}]; - [_entries release];_entries=[entries copy];[_folders release];_folders=[[folders.allObjects sortedArrayUsingSelector:@selector(localizedStandardCompare:)]copy];return YES; + if(DYLUTCancelled(progress,error))return NO; + @synchronized(self){[_entries release];_entries=[entries copy];[_folders release];_folders=[[folders.allObjects sortedArrayUsingSelector:@selector(localizedStandardCompare:)]copy];}return YES; }} -- (NSArray *)importURLs:(NSArray *)urls error:(NSError **)error {@synchronized(self){ +- (NSArray *)importURLs:(NSArray *)urls error:(NSError **)error {return [self importURLs:urls progress:nil error:error];} +- (NSArray *)importURLs:(NSArray *)urls progress:(NSProgress *)progress error:(NSError **)error {@synchronized(_fileLock){ NSFileManager *fm=NSFileManager.defaultManager;NSMutableArray *plans=[NSMutableArray array]; NSString *root=_rootURL.path; for(NSURL *sourceURL in urls) { + if(DYLUTCancelled(progress,error))return nil; if(!sourceURL.isFileURL){DYLUTFail(error,@"只能导入本机 LUT 文件");return nil;} NSURL *source=[sourceURL URLByStandardizingPath];BOOL directory=NO; if(!DYLUTOrdinaryURL(source,&directory,error))return nil; @@ -295,6 +338,7 @@ static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) { __block NSError *scanError=nil; NSDirectoryEnumerator *enumerator=[fm enumeratorAtURL:source includingPropertiesForKeys:@[NSURLIsSymbolicLinkKey,NSURLIsDirectoryKey,NSURLIsRegularFileKey] options:NSDirectoryEnumerationSkipsHiddenFiles|NSDirectoryEnumerationSkipsPackageDescendants errorHandler:^BOOL(NSURL *url,NSError *e){(void)url;scanError=e;return NO;}]; for(NSURL *file in enumerator) { + if(DYLUTCancelled(progress,error))return nil; NSNumber *link=nil;[file getResourceValue:&link forKey:NSURLIsSymbolicLinkKey error:NULL]; if(link.boolValue){[enumerator skipDescendants];continue;} BOOL subdirectory=NO;if(!DYLUTOrdinaryURL(file,&subdirectory,NULL)||subdirectory||![file.pathExtension.lowercaseString isEqual:@"cube"])continue; @@ -308,23 +352,46 @@ static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) { } if(!plans.count){DYLUTFail(error,@"没有找到可导入的 .cube 文件");return nil;} // Validate every source before writing the library, preserving existing files. - for(NSDictionary *plan in plans){std::vector values;NSUInteger n=0;if(!DYLUTReadCube([plan[@"source"]path],values,n,error))return nil;} + progress.totalUnitCount=plans.count*2;progress.completedUnitCount=0; + for(NSDictionary *plan in plans){ + NSError *itemError=nil;BOOL valid=NO; + @autoreleasepool{ + progress.localizedDescription=[NSString stringWithFormat:@"正在校验 %lld/%lu",progress.completedUnitCount+1,(unsigned long)plans.count];progress.localizedAdditionalDescription=[plan[@"source"]lastPathComponent]; + std::vector values;NSUInteger n=0;valid=!DYLUTCancelled(progress,&itemError)&&DYLUTReadCancellable([plan[@"source"]path],values,n,progress,&itemError);[itemError retain]; + } + if(!valid){if(error)*error=[itemError autorelease];else[itemError release];return nil;}[itemError release];progress.completedUnitCount++; + } if(!DYLUTEnsureDirectory(_rootURL,_rootURL,error))return nil; NSMutableArray *created=[NSMutableArray array],*imported=[NSMutableArray array];BOOL success=YES; - for(NSDictionary *plan in plans) { - NSURL *destination=[_rootURL URLByAppendingPathComponent:plan[@"relative"]]; - if(!DYLUTEnsureDirectory(destination.URLByDeletingLastPathComponent,_rootURL,error)){success=NO;break;} - NSString *stem=destination.path.stringByDeletingPathExtension,*extension=destination.pathExtension; - NSUInteger suffix=1; - while([fm fileExistsAtPath:destination.path])destination=[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@ %lu.%@",stem,(unsigned long)++suffix,extension]]; - if(![fm copyItemAtURL:plan[@"source"] toURL:destination error:error]){success=NO;break;} - [created addObject:destination]; - std::vector values;NSUInteger n=0;if(!DYLUTReadCube(destination.path,values,n,error)){success=NO;break;} - [imported addObject:DYLUTEntry(destination,_rootURL)]; + for(NSDictionary *plan in plans){ + NSError *itemError=nil;BOOL copied=NO; + @autoreleasepool{ + copied=[&]()->BOOL{ + if(DYLUTCancelled(progress,&itemError))return NO; + progress.localizedDescription=[NSString stringWithFormat:@"正在导入 %lu/%lu",(unsigned long)imported.count+1,(unsigned long)plans.count];progress.localizedAdditionalDescription=[plan[@"source"]lastPathComponent]; + NSURL *destination=[_rootURL URLByAppendingPathComponent:plan[@"relative"]]; + if(!DYLUTEnsureDirectory(destination.URLByDeletingLastPathComponent,_rootURL,&itemError))return NO; + NSString *stem=destination.path.stringByDeletingPathExtension,*extension=destination.pathExtension;NSUInteger suffix=1; + while([fm fileExistsAtPath:destination.path])destination=[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@ %lu.%@",stem,(unsigned long)++suffix,extension]]; + if(![fm copyItemAtURL:plan[@"source"] toURL:destination error:&itemError])return NO;[created addObject:destination]; + std::vector values;NSUInteger n=0;if(!DYLUTReadCancellable(destination.path,values,n,progress,&itemError))return NO; + [imported addObject:DYLUTEntry(destination,_rootURL)];return YES; + }();[itemError retain]; + } + if(!copied){if(error)*error=[itemError autorelease];else[itemError release];success=NO;break;}[itemError release];progress.completedUnitCount++; } + if(success)success=!DYLUTCancelled(progress,error)&&[self reload:error]; if(!success){for(NSURL *url in created)[fm removeItemAtURL:url error:NULL];return nil;} - if(![self reload:error])return nil;return imported; + return imported; }} +- (NSProgress *)reloadAsync:(void (^)(NSError *))completion { + NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:-1];progress.localizedDescription=@"正在扫描 LUT 文件夹…"; + dispatch_async(_fileQueue,^{@autoreleasepool{NSError *error=nil;[self reloadProgress:progress error:&error];progress.totalUnitCount=MAX(1,progress.completedUnitCount);progress.completedUnitCount=progress.totalUnitCount;dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(error);});}});return progress; +} +- (NSProgress *)importURLsAsync:(NSArray *)urls completion:(void (^)(NSArray *,NSError *))completion { + NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:-1];progress.localizedDescription=@"正在查找 LUT 文件…";NSArray *sources=[[urls copy]autorelease]; + dispatch_async(_fileQueue,^{@autoreleasepool{NSError *error=nil;NSArray *imported=[self importURLs:sources progress:progress error:&error];dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(imported,error);});}});return progress; +} - (BOOL)isFavoritePath:(NSString *)path {@synchronized(self){return [_favoritePaths containsObject:path];}} - (BOOL)setFavorite:(BOOL)favorite forPath:(NSString *)path error:(NSError **)error {@synchronized(self){ NSString *prefix=[_rootURL.path stringByAppendingString:@"/"]; diff --git a/大鱼调色/Plugin/DYRenderer.mm b/大鱼调色/Plugin/DYRenderer.mm index b9e235a..293990f 100644 --- a/大鱼调色/Plugin/DYRenderer.mm +++ b/大鱼调色/Plugin/DYRenderer.mm @@ -11,16 +11,17 @@ static id texture3D(idd,const float*values,NSUInteger n){ @interface DYRenderer(){ NSMutableDictionary *_devices,*_luts; DYColorTables *_tables; + NSObject *_previewLock; NSData *_preview,*_lookLUTPreview; CFTimeInterval _lastPreview; } @end @implementation DYRenderer -- (instancetype)init{if((self=[super init])){_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_tables=[DYColorTables new];}return self;} -- (void)dealloc{[_devices release];[_luts release];[_tables release];[_preview release];[_lookLUTPreview release];[super dealloc];} -- (void)invalidatePreview{@synchronized(self){[_preview release];_preview=nil;[_lookLUTPreview release];_lookLUTPreview=nil;_lastPreview=0;}} -- (NSData*)preview{@synchronized(self){return [[_preview retain]autorelease];}} -- (NSData*)lookLUTPreview{@synchronized(self){return [[_lookLUTPreview retain]autorelease];}} +- (instancetype)init{if((self=[super init])){_previewLock=[NSObject new];_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_tables=[DYColorTables new];}return self;} +- (void)dealloc{[_devices release];[_luts release];[_tables release];[_preview release];[_lookLUTPreview release];[_previewLock release];[super dealloc];} +- (void)invalidatePreview{@synchronized(_previewLock){[_preview release];_preview=nil;[_lookLUTPreview release];_lookLUTPreview=nil;_lastPreview=0;}} +- (NSData*)preview{@synchronized(_previewLock){return [[_preview retain]autorelease];}} +- (NSData*)lookLUTPreview{@synchronized(_previewLock){return [[_lookLUTPreview retain]autorelease];}} - (NSMutableDictionary*)device:(uint64_t)registry error:(NSError**)err{ NSNumber*k=@(registry);NSMutableDictionary*entry=_devices[k];if(entry)return entry; idd=nil;NSArray*all=MTLCopyAllDevices();for(idcandidate in all)if(candidate.registryID==registry||!registry){d=[candidate retain];break;}[all release];if(!d){fail(err,@"宿主的 Metal 设备不可用");return nil;} @@ -60,14 +61,14 @@ static id texture3D(idd,const float*values,NSUInteger n){ idcb=[e[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyUnpremultiply"]];[ce setTexture:input atIndex:0];[ce setTexture:straight atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding]; float level=.5;idscene=[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared]; if(u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyWhitesSceneStatistics"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:1];[ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding];} - BOOL preview=CACurrentMediaTime()-_lastPreview>.5;idpb=nil;if(preview){pb=[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyInputAnalysis"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[0] atIndex:1];float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0;[ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];} + BOOL preview=NO;@synchronized(_previewLock){preview=CACurrentMediaTime()-_lastPreview>.5;}idpb=nil;if(preview){pb=[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyInputAnalysis"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[0] atIndex:1];float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0;[ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];} MTLRenderPassDescriptor*rp=[MTLRenderPassDescriptor renderPassDescriptor];rp.colorAttachments[0].texture=output;rp.colorAttachments[0].loadAction=MTLLoadActionDontCare;rp.colorAttachments[0].storeAction=MTLStoreActionStore;idre=[cb renderCommandEncoderWithDescriptor:rp];[re setRenderPipelineState:pipeline]; float w=output.width,h=output.height;FxRect s=src.tilePixelBounds,t=dst.tilePixelBounds;float sw=s.right-s.left,sh=s.top-s.bottom;float l=(t.left-s.left)/sw,r=(t.right-s.left)/sw,top=(s.top-t.top)/sh,bottom=(s.top-t.bottom)/sh; if(src.imageOrigin==kFxImageOrigin_BOTTOM_LEFT){top=1-top;bottom=1-bottom;} DYVertex2D vs[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}}; if(dst.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(int i=0;i<4;i++)vs[i].position.y=-vs[i].position.y; vector_uint2 vp={(unsigned)output.width,(unsigned)output.height};[re setVertexBytes:vs length:sizeof(vs) atIndex:0];[re setVertexBytes:&vp length:sizeof(vp) atIndex:1];[re setViewport:(MTLViewport){0,0,w,h,0,1}];[re setFragmentTexture:straight atIndex:0];for(NSUInteger i=0;i texture3D(idd,const float*values,NSUInteger n){ _lookLUTPreview=[topFirst copy]; }else _lookLUTPreview=[_preview retain]; _lastPreview=CACurrentMediaTime();dispatch_async(dispatch_get_main_queue(),^{[[NSNotificationCenter defaultCenter]postNotificationName:@"DYPreviewDidChange" object:self];}); - } + }} if(!ok)fail(err,cb.error.localizedDescription);[pb release];[straight release];[scene release];return ok; }}} - (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{@synchronized(self){ diff --git a/大鱼调色/Plugin/Info.plist b/大鱼调色/Plugin/Info.plist index 3e56633..a335b7b 100644 --- a/大鱼调色/Plugin/Info.plist +++ b/大鱼调色/Plugin/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 1.1.2 + 1.1.3 CFBundleVersion - 11 + 12 NSHumanReadableCopyright PlugInKit diff --git a/大鱼调色/Wrapper Application/Info.plist b/大鱼调色/Wrapper Application/Info.plist index cbc6eee..8e6be3c 100644 --- a/大鱼调色/Wrapper Application/Info.plist +++ b/大鱼调色/Wrapper Application/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.1.2 + 1.1.3 CFBundleVersion - 11 + 12 LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright