文件
dayu-color/大鱼调色/Plugin/DYLUTLibrary.mm
T

341 行
22 KiB
Plaintext

#import "DYLUTLibrary.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <limits>
#include <limits.h>
#include <stdlib.h>
#include <zlib.h>
static NSString *const DYLUTLibraryErrorDomain=@"com.dayu.color.LUTLibrary";
static NSURL *DYLUTCanonicalURL(NSURL *url) {
// Foundation deliberately abbreviates /private/var back to /var in some
// URL normalization APIs; its enumerator returns the POSIX canonical path.
NSString *path=url.path.stringByStandardizingPath;
NSMutableArray *missing=[NSMutableArray array];char resolved[PATH_MAX];
while(path.length&&!realpath(path.fileSystemRepresentation,resolved)) {
NSString *parent=path.stringByDeletingLastPathComponent;
if([parent isEqual:path])return [NSURL fileURLWithPath:url.path.stringByStandardizingPath];
[missing insertObject:path.lastPathComponent atIndex:0];path=parent;
}
NSString *canonical=[[NSFileManager defaultManager]stringWithFileSystemRepresentation:resolved length:strlen(resolved)];
for(NSString *component in missing)canonical=[canonical stringByAppendingPathComponent:component];
return [NSURL fileURLWithPath:canonical];
}
static BOOL DYLUTFail(NSError **error,NSString *message) {
if(error)*error=[NSError errorWithDomain:DYLUTLibraryErrorDomain code:1
userInfo:@{NSLocalizedDescriptionKey:message?:@"LUT 操作未完成"}];
return NO;
}
@interface DYLUTTable : NSObject {
@public std::vector<float> values;
@public NSUInteger dimension;
}
@end
@implementation DYLUTTable @end
static NSCache *DYLUTTableCache(void) {
static NSCache *cache;static dispatch_once_t once;
dispatch_once(&once,^{cache=[NSCache new];cache.countLimit=12;cache.totalCostLimit=96*1024*1024;});
return cache;
}
static void DYLUTSample(const std::vector<float>& table,NSUInteger n,const float rgb[3],float out[3]) {
float fraction[3];NSUInteger index[3];
for(int c=0;c<3;c++) {
float scaled=std::min(1.f,std::max(0.f,rgb[c]))*float(n-1);
index[c]=std::min(n-2,(NSUInteger)scaled);fraction[c]=scaled-float(index[c]);
}
for(int c=0;c<3;c++) {
float sum=0;
for(int k=0;k<8;k++) {
int x=k&1,y=(k>>1)&1,z=(k>>2)&1;
sum+=table[(((index[2]+z)*n+index[1]+y)*n+index[0]+x)*4+c]
*(x?fraction[0]:1-fraction[0])*(y?fraction[1]:1-fraction[1])*(z?fraction[2]:1-fraction[2]);
}
out[c]=sum;
}
}
static BOOL DYLUTParse(NSString *path,std::vector<float>& data,NSUInteger& size,NSError **error) {
data.clear();size=0;
NSDictionary *attributes=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:error];
if(!attributes)return NO;
if(![attributes[NSFileType]isEqual:NSFileTypeRegular])return DYLUTFail(error,@"LUT 必须是普通文件");
if([attributes[NSFileSize]unsignedLongLongValue]>256ULL*1024*1024)return DYLUTFail(error,@"LUT 文件超过 256 MB 限制");
NSData *bytes=[NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:error];
if(!bytes)return NO;
if([path.pathExtension.lowercaseString isEqual:@"dylut"]) {
if(bytes.length<36||memcmp(bytes.bytes,"DYLT",4))return DYLUTFail(error,@"输入 LUT 格式损坏");
uint32_t n=0,count=0;memcpy(&n,(const uint8_t *)bytes.bytes+4,4);memcpy(&count,(const uint8_t *)bytes.bytes+8,4);
if(n<2||n>128||count!=n*n*n*16)return DYLUTFail(error,@"输入 LUT 尺寸无效");
data.resize(count/4);uLongf length=count;
if(uncompress((Bytef *)data.data(),&length,(const Bytef *)bytes.bytes+36,bytes.length-36)!=Z_OK||length!=count)
return DYLUTFail(error,@"输入 LUT 解压失败");
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,且只能声明一次");
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)]]);
}
if(size<2||data.size()!=size*size*size*4)return DYLUTFail(error,@"LUT 数据数量与尺寸不符");
bool resample=false;
for(int c=0;c<3;c++) {
if(!std::isfinite(domainMin[c])||!std::isfinite(domainMax[c])||domainMax[c]<=domainMin[c])return DYLUTFail(error,@"LUT DOMAIN 范围无效");
resample|=domainMin[c]!=0||domainMax[c]!=1;
}
if(resample) {
std::vector<float> original=data;
for(NSUInteger z=0;z<size;z++)for(NSUInteger y=0;y<size;y++)for(NSUInteger x=0;x<size;x++) {
float rgb[3]={(float(x)/(size-1)-domainMin[0])/(domainMax[0]-domainMin[0]),
(float(y)/(size-1)-domainMin[1])/(domainMax[1]-domainMin[1]),
(float(z)/(size-1)-domainMin[2])/(domainMax[2]-domainMin[2])};
float sample[3];DYLUTSample(original,size,rgb,sample);
size_t dest=((z*size+y)*size+x)*4;for(int c=0;c<3;c++)data[dest+c]=sample[c];
}
}
return YES;
}
BOOL DYLUTReadCube(NSString *path,std::vector<float>& data,NSUInteger& size,NSError **error) {
data.clear();size=0;
if(!path.length)return DYLUTFail(error,@"未选择 LUT 文件");
NSDictionary *a=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:error];
if(!a)return NO;
NSString *key=[NSString stringWithFormat:@"%@|%.9f|%@|%@",path.stringByStandardizingPath,[a[NSFileModificationDate]timeIntervalSinceReferenceDate],a[NSFileSize],a[NSFileSystemFileNumber]];
DYLUTTable *cached=[DYLUTTableCache()objectForKey:key];
if(cached){data=cached->values;size=cached->dimension;return YES;}
std::vector<float> parsed;NSUInteger n=0;
if(!DYLUTParse(path,parsed,n,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;
}
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;
}
std::vector<float> table;NSUInteger n=0;
if(path.length&&!DYLUTReadCube(path,table,n,error))return nil;
NSMutableData *result=[NSMutableData dataWithLength:source.length];
const float *input=(const float *)source.bytes;float *output=(float *)result.mutableBytes;
for(NSUInteger i=0;i<width*height;i++) {
const float *p=input+i*4;float *q=output+i*4;
if(!std::isfinite(p[0])||!std::isfinite(p[1])||!std::isfinite(p[2])||!std::isfinite(p[3])||p[3]<=0)continue;
if(n)DYLUTSample(table,n,p,q);else for(int c=0;c<3;c++)q[c]=p[c];
q[3]=std::min(1.f,std::max(0.f,p[3]));
}
return result;
}
static NSData *DYLUTFallback(void) {
static NSData *chart;static dispatch_once_t once;
dispatch_once(&once,^{
NSMutableData *data=[NSMutableData dataWithLength:320*180*16];float *p=(float *)data.mutableBytes;
const float swatches[][3]={{.74,.43,.33},{.49,.31,.25},{.95,.80,.67},{.82,.71,.51},{.16,.51,.75},{.24,.67,.35},{.94,.22,.18},{.14,.18,.33}};
for(NSUInteger y=0;y<180;y++)for(NSUInteger x=0;x<320;x++) {
float t=float(x)/319;float *q=p+(y*320+x)*4;
if(y<45)q[0]=q[1]=q[2]=t;
else if(y<90){q[0]=t;q[1]=1-t;q[2]=.31;}
else if(y<135){for(int c=0;c<3;c++)q[c]=swatches[std::min((NSUInteger)7,x*8/320)][c];}
else{q[0]=t;q[1]=t*t;q[2]=sqrtf(t);}
q[3]=1;
}
chart=[data copy];
});return chart;
}
NSImage *DYLUTThumbnail(NSString *path,NSData *source,NSUInteger sourceWidth,NSUInteger sourceHeight,NSSize outputSize,NSError **error) {
if(!std::isfinite(outputSize.width)||!std::isfinite(outputSize.height)||outputSize.width<1||outputSize.height<1||outputSize.width>2048||outputSize.height>2048) {
DYLUTFail(error,@"缩略图尺寸无效");return nil;
}
if(!source){source=DYLUTFallback();sourceWidth=320;sourceHeight=180;}
NSData *transformed=DYLUTTransformRGBA(source,sourceWidth,sourceHeight,path,error);if(!transformed)return nil;
NSUInteger width=(NSUInteger)llround(outputSize.width),height=(NSUInteger)llround(outputSize.height);
NSBitmapImageRep *bitmap=[[[NSBitmapImageRep alloc]initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height
bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:NSBitmapFormatAlphaNonpremultiplied bytesPerRow:width*4 bitsPerPixel:32]autorelease];
if(!bitmap){DYLUTFail(error,@"无法分配缩略图位图");return nil;}
const float *p=(const float *)transformed.bytes;uint8_t *q=bitmap.bitmapData;
for(NSUInteger y=0;y<height;y++)for(NSUInteger x=0;x<width;x++) {
// Center-aligned bilinear scaling, independent of NSGraphicsContext.
float fx=(float(x)+.5f)*sourceWidth/width-.5f,fy=(float(y)+.5f)*sourceHeight/height-.5f;
fx=std::max(0.f,std::min(float(sourceWidth-1),fx));fy=std::max(0.f,std::min(float(sourceHeight-1),fy));
NSUInteger x0=(NSUInteger)fx,y0=(NSUInteger)fy,x1=std::min(sourceWidth-1,x0+1),y1=std::min(sourceHeight-1,y0+1);
float tx=fx-x0,ty=fy-y0;
for(int c=0;c<4;c++) {
float v=(p[(y0*sourceWidth+x0)*4+c]*(1-tx)+p[(y0*sourceWidth+x1)*4+c]*tx)*(1-ty)
+(p[(y1*sourceWidth+x0)*4+c]*(1-tx)+p[(y1*sourceWidth+x1)*4+c]*tx)*ty;
q[(y*width+x)*4+c]=(uint8_t)lroundf(std::max(0.f,std::min(1.f,v))*255);
}
}
NSImage *image=[[[NSImage alloc]initWithSize:NSMakeSize(width,height)]autorelease];[image addRepresentation:bitmap];return image;
}
static NSString *DYLUTRelativeFolder(NSString *path,NSString *root) {
NSString *parent=path.stringByDeletingLastPathComponent;
if([parent isEqual:root])return @"";
NSString *prefix=[root stringByAppendingString:@"/"];
return [parent hasPrefix:prefix]?[parent substringFromIndex:prefix.length]:@"";
}
static NSDictionary *DYLUTEntry(NSURL *url,NSURL *root) {
NSString *path=url.path,*base=root.path;
NSString *relative=[path hasPrefix:[base stringByAppendingString:@"/"]]?[path substringFromIndex:base.length+1]:path.lastPathComponent;
return @{@"name":path.lastPathComponent.stringByDeletingPathExtension,@"path":path,
@"relativeFolder":DYLUTRelativeFolder(path,base),@"relativePath":relative};
}
static BOOL DYLUTOrdinaryURL(NSURL *url,BOOL *directory,NSError **error) {
NSNumber *isDirectory=nil,*isRegular=nil,*isLink=nil;
if(![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:error]||
![url getResourceValue:&isRegular forKey:NSURLIsRegularFileKey error:error]||
![url getResourceValue:&isLink forKey:NSURLIsSymbolicLinkKey error:error])return NO;
if(isLink.boolValue||(!isDirectory.boolValue&&!isRegular.boolValue))return DYLUTFail(error,@"不导入符号链接或特殊文件");
if(directory)*directory=isDirectory.boolValue;return YES;
}
static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) {
NSString *prefix=[root.path stringByAppendingString:@"/"];
if(![directory.path isEqual:root.path]&&![directory.path hasPrefix:prefix])return DYLUTFail(error,@"LUT 目标路径超出目录边界");
NSFileManager *fm=NSFileManager.defaultManager;
if(![fm fileExistsAtPath:root.path]&&![fm createDirectoryAtURL:root withIntermediateDirectories:YES attributes:nil error:error])return NO;
NSDictionary *attributes=[fm attributesOfItemAtPath:root.path error:error];
if(![attributes[NSFileType]isEqual:NSFileTypeDirectory])return DYLUTFail(error,@"LUT 库根目录不是普通文件夹");
NSString *relative=[directory.path isEqual:root.path]?@"":[directory.path substringFromIndex:prefix.length];
NSURL *current=root;
for(NSString *component in relative.pathComponents) {
if(!component.length)continue;
current=[current URLByAppendingPathComponent:component isDirectory:YES];
NSDictionary *existing=[fm attributesOfItemAtPath:current.path error:NULL];
if(existing) {
if(![existing[NSFileType]isEqual:NSFileTypeDirectory])return DYLUTFail(error,@"LUT 目标文件夹含符号链接或非目录项");
} else if(![fm createDirectoryAtURL:current withIntermediateDirectories:NO attributes:nil error:error])return NO;
}
return YES;
}
@interface DYLUTLibrary () {
NSURL *_rootURL;
NSArray *_entries,*_folders;
NSMutableSet *_favoritePaths;
}
@end
@implementation DYLUTLibrary
+ (NSURL *)defaultRootURL {return [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Movies/大鱼调色LUT/look LUTs"] isDirectory:YES];}
- (instancetype)init {return [self initWithRootURL:self.class.defaultRootURL];}
- (instancetype)initWithRootURL:(NSURL *)rootURL {
if(!rootURL.isFileURL||!rootURL.path.length){[self release];return nil;}
if((self=[super init])) {
_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];}
- (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 isDirectory=NO;NSFileManager *fm=NSFileManager.defaultManager;
if(![fm fileExistsAtPath:_rootURL.path isDirectory:&isDirectory]){[_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) {
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;
if(![url.path hasPrefix:[_rootURL.path stringByAppendingString:@"/"]])return DYLUTFail(error,@"LUT 库文件路径超出目录边界");
if(directory){NSString *relative=[url.path substringFromIndex:_rootURL.path.length+1];[folders addObject:relative];continue;}
if([url.pathExtension.lowercaseString isEqual:@"cube"])[entries addObject:DYLUTEntry(url,_rootURL)];
if(entries.count>10000)return DYLUTFail(error,@"LUT 库超过 10,000 个文件限制");
}
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;
}}
- (NSArray *)importURLs:(NSArray<NSURL *> *)urls error:(NSError **)error {@synchronized(self){
NSFileManager *fm=NSFileManager.defaultManager;NSMutableArray *plans=[NSMutableArray array];
NSString *root=_rootURL.path;
for(NSURL *sourceURL in urls) {
if(!sourceURL.isFileURL){DYLUTFail(error,@"只能导入本机 LUT 文件");return nil;}
NSURL *source=[sourceURL URLByStandardizingPath];BOOL directory=NO;
if(!DYLUTOrdinaryURL(source,&directory,error))return nil;
// NSDirectoryEnumerator canonicalizes /var to /private/var on macOS.
// Canonicalize both sides before calculating a relative path.
source=DYLUTCanonicalURL(source);
if([source.path isEqual:root]||[source.path hasPrefix:[root stringByAppendingString:@"/"]]){DYLUTFail(error,@"此 LUT 已位于浏览库中");return nil;}
if(!directory) {
if(![source.pathExtension.lowercaseString isEqual:@"cube"]){DYLUTFail(error,@"请选择 .cube 文件或包含它们的文件夹");return nil;}
[plans addObject:@{@"source":source,@"relative":source.lastPathComponent}];
} else {
__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) {
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;
if(![file.path hasPrefix:[source.path stringByAppendingString:@"/"]]){DYLUTFail(error,@"导入文件路径超出目录边界");return nil;}
NSString *relative=[source.lastPathComponent stringByAppendingPathComponent:[file.path substringFromIndex:source.path.length+1]];
[plans addObject:@{@"source":file,@"relative":relative}];
if(plans.count>10000){DYLUTFail(error,@"单次导入超过 10,000 个 LUT 限制");return nil;}
}
if(scanError){if(error)*error=scanError;return nil;}
}
}
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<float> values;NSUInteger n=0;if(!DYLUTReadCube([plan[@"source"]path],values,n,error))return nil;}
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<float> values;NSUInteger n=0;if(!DYLUTReadCube(destination.path,values,n,error)){success=NO;break;}
[imported addObject:DYLUTEntry(destination,_rootURL)];
}
if(!success){for(NSURL *url in created)[fm removeItemAtURL:url error:NULL];return nil;}
if(![self reload:error])return nil;return imported;
}}
- (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:@"/"];
if(![path hasPrefix:prefix]||[path.pathComponents containsObject:@".."])return DYLUTFail(error,@"只能收藏浏览库中的 LUT");
NSMutableSet *next=[[_favoritePaths mutableCopy]autorelease];if(favorite)[next addObject:path];else[next removeObject:path];
NSMutableArray *relative=[NSMutableArray array];for(NSString *p in next)[relative addObject:[p substringFromIndex:prefix.length]];
[relative sortUsingSelector:@selector(localizedStandardCompare:)];
if(!DYLUTEnsureDirectory(_rootURL,_rootURL,error))return NO;
NSData *data=[NSPropertyListSerialization dataWithPropertyList:@{@"relativePaths":relative} format:NSPropertyListXMLFormat_v1_0 options:0 error:error];
if(!data||![data writeToURL:[_rootURL URLByAppendingPathComponent:@".favorites.plist"] options:NSDataWritingAtomic error:error])return NO;
[_favoritePaths release];_favoritePaths=[next mutableCopy];return YES;
}}
@end