#import "DYLUTBrowser.h" #import "DYLUTLibrary.h" #import #include static NSColor *DYBrowserColor(NSDictionary *palette, NSString *key) { NSColor *color=palette[key]; if([color isKindOfClass:NSColor.class])return color; if([key isEqualToString:@"text"])return [NSColor colorWithWhite:.92 alpha:1]; if([key isEqualToString:@"secondary"])return [NSColor colorWithWhite:.65 alpha:1]; if([key isEqualToString:@"accent"])return [NSColor colorWithSRGBRed:.32 green:.75 blue:.97 alpha:1]; if([key isEqualToString:@"border"])return [NSColor colorWithWhite:.30 alpha:1]; return [NSColor colorWithWhite:.12 alpha:1]; } static NSString *const DYBrowserSizePreference=@"com.dayu.color.lookLUTPreview.thumbnailSize"; static NSString *const DYBrowserFolderPreference=@"com.dayu.color.lookLUTPreview.selectedFolder"; static NSString *const DYBrowserFramePreference=@"com.dayu.color.lookLUTPreview.windowFrame"; static NSString *const DYBrowserLayoutPreference=@"com.dayu.color.lookLUTPreview.layout"; static NSString *const DYBrowserSidebarPreference=@"com.dayu.color.lookLUTPreview.sidebarWidth"; static NSString *const DYBrowserRecentFolder=@"@recent"; static NSString *DYBrowserPreference(NSString *key,DYLUTLibrary *library){return [NSString stringWithFormat:@"%@|%@",key,library.rootURL.path];} // Opt-in, local-only geometry samples. No LUT names, paths or image data. static void DYBrowserGeometrySample(NSView *root,NSString *phase){ if(![NSUserDefaults.standardUserDefaults boolForKey:@"DYBrowserGeometryDiagnostics"]||!root)return; NSMutableArray *views=[NSMutableArray array]; for(NSView *view=root;view&&views.count<8;view=view.superview){ NSMutableDictionary *sample=[NSMutableDictionary dictionaryWithDictionary:@{ @"class":NSStringFromClass(view.class),@"frame":NSStringFromRect(view.frame),@"bounds":NSStringFromRect(view.bounds), @"visibleRect":NSStringFromRect(view.visibleRect),@"windowRect":NSStringFromRect([view convertRect:view.bounds toView:nil]), @"flipped":@(view.flipped),@"autoresizesSubviews":@(view.autoresizesSubviews),@"autoresizingMask":@(view.autoresizingMask), @"frameRotation":@(view.frameRotation),@"boundsRotation":@(view.boundsRotation),@"wantsLayer":@(view.wantsLayer)}]; if(view.layer){CALayer *layer=view.layer;CATransform3D t=layer.transform;sample[@"layer"]=@{ @"frame":NSStringFromRect(NSRectFromCGRect(layer.frame)),@"bounds":NSStringFromRect(NSRectFromCGRect(layer.bounds)), @"position":NSStringFromPoint(NSPointFromCGPoint(layer.position)),@"anchorPoint":NSStringFromPoint(NSPointFromCGPoint(layer.anchorPoint)), @"contentsScale":@(layer.contentsScale),@"geometryFlipped":@(layer.geometryFlipped), @"transform":@[@(t.m11),@(t.m12),@(t.m21),@(t.m22),@(t.m41),@(t.m42)]};} [views addObject:sample]; } NSMutableDictionary *record=[NSMutableDictionary dictionaryWithDictionary:@{@"phase":phase,@"time":@(NSDate.timeIntervalSinceReferenceDate),@"views":views}]; NSWindow *window=root.window; if(window){record[@"window"]=@{@"class":NSStringFromClass(window.class),@"frame":NSStringFromRect(window.frame), @"contentFrame":NSStringFromRect(window.contentView.frame),@"contentBounds":NSStringFromRect(window.contentView.bounds), @"contentLayoutRect":NSStringFromRect(window.contentLayoutRect),@"backingScaleFactor":@(window.backingScaleFactor), @"screenRect":NSStringFromRect([window convertRectToScreen:[root convertRect:root.bounds toView:nil]])};} NSMutableArray *screens=[NSMutableArray array]; for(NSScreen *screen in NSScreen.screens)[screens addObject:@{@"frame":NSStringFromRect(screen.frame),@"visibleFrame":NSStringFromRect(screen.visibleFrame),@"backingScaleFactor":@(screen.backingScaleFactor)}]; record[@"screens"]=screens; NSString *logs=[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES).firstObject stringByAppendingPathComponent:@"Logs/大鱼调色"]; [NSFileManager.defaultManager createDirectoryAtPath:logs withIntermediateDirectories:YES attributes:nil error:nil]; NSString *path=[logs stringByAppendingPathComponent:[NSString stringWithFormat:@"BrowserGeometry-%d.jsonl",NSProcessInfo.processInfo.processIdentifier]]; NSData *json=[NSJSONSerialization dataWithJSONObject:record options:0 error:nil];if(!json)return; if(![NSFileManager.defaultManager fileExistsAtPath:path])[NSFileManager.defaultManager createFileAtPath:path contents:nil attributes:nil]; NSFileHandle *file=[NSFileHandle fileHandleForWritingAtPath:path]; @try{if([file seekToEndOfFile]<1024*1024){[file writeData:json];[file writeData:[@"\n" dataUsingEncoding:NSUTF8StringEncoding]];}}@finally{[file closeFile];} } @interface DYBrowserCanvas : NSView @property(copy) NSDictionary *palette; @property(copy) NSString *fillKey; @end @implementation DYBrowserCanvas - (BOOL)isFlipped{return YES;} - (BOOL)isAccessibilityElement{return YES;} - (NSAccessibilityRole)accessibilityRole{return NSAccessibilityGroupRole;} - (NSArray *)accessibilityChildren{return NSAccessibilityUnignoredChildren(self.subviews);} - (NSArray *)accessibilityVisibleChildren{ NSMutableArray *result=[NSMutableArray array]; for(NSView *child in self.subviews)if(!child.hidden&&NSIntersectsRect(child.frame,self.visibleRect))[result addObject:child]; return NSAccessibilityUnignoredChildren(result); } - (void)drawRect:(NSRect)dirty{[DYBrowserColor(_palette,_fillKey?:@"background") setFill];NSRectFill(self.bounds);} - (void)dealloc{[_palette release];[_fillKey release];[super dealloc];} @end @interface DYBrowserTile : NSButton @property(retain) NSImage *thumbnail; @property(copy) NSString *displayName; @property(copy) NSString *failure; @property(copy) NSDictionary *palette; @property BOOL chosen; @property BOOL doubleClicked; @property BOOL listLayout; @end @implementation DYBrowserTile - (BOOL)isFlipped{return YES;} - (instancetype)initWithFrame:(NSRect)frame{ if((self=[super initWithFrame:frame])){self.bordered=NO;self.title=@"";self.imagePosition=NSNoImage;self.focusRingType=NSFocusRingTypeExterior;} return self; } - (void)dealloc{[_thumbnail release];[_displayName release];[_failure release];[_palette release];[super dealloc];} - (NSString *)accessibilityLabel{return _displayName?:@"LUT";} - (id)accessibilityValue{return _chosen?@"已选择":_failure.length?@"LUT 无效":_thumbnail?@"可应用":@"正在生成缩略图";} - (NSString *)accessibilityHelp{return _failure?:@"单击应用此 LUT,双击应用并关闭浏览器";} - (void)drawRect:(NSRect)dirty{ NSRect bounds=NSInsetRect(self.bounds,1,1); NSBezierPath *outline=[NSBezierPath bezierPathWithRoundedRect:bounds xRadius:7 yRadius:7]; [DYBrowserColor(_palette,_chosen?@"field":@"card") setFill];[outline fill]; NSRect imageRect=_listLayout?NSMakeRect(3,3,104,bounds.size.height-4):NSMakeRect(2,2,MAX(1,bounds.size.width-2),MAX(1,bounds.size.height-25)); if(_thumbnail){ [NSGraphicsContext saveGraphicsState]; [[NSBezierPath bezierPathWithRoundedRect:imageRect xRadius:4 yRadius:4]addClip]; NSSize size=_thumbnail.size;CGFloat scale=MAX(imageRect.size.width/MAX(1,size.width),imageRect.size.height/MAX(1,size.height)); NSRect dest=NSMakeRect(NSMidX(imageRect)-size.width*scale/2,NSMidY(imageRect)-size.height*scale/2,size.width*scale,size.height*scale); [_thumbnail drawInRect:dest fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1 respectFlipped:YES hints:nil]; [NSGraphicsContext restoreGraphicsState]; }else{ [DYBrowserColor(_palette,@"background")setFill];NSRectFill(imageRect); NSString *message=_failure.length?@"无法预览":@"生成预览…"; NSDictionary *attributes=@{NSFontAttributeName:[NSFont systemFontOfSize:11],NSForegroundColorAttributeName:DYBrowserColor(_palette,@"secondary")}; NSSize size=[message sizeWithAttributes:attributes]; [message drawAtPoint:NSMakePoint(NSMidX(imageRect)-size.width/2,NSMidY(imageRect)-size.height/2) withAttributes:attributes]; } NSMutableParagraphStyle *paragraph=[[[NSMutableParagraphStyle alloc]init]autorelease];paragraph.alignment=_listLayout?NSTextAlignmentLeft:NSTextAlignmentCenter;paragraph.lineBreakMode=NSLineBreakByTruncatingMiddle; [_displayName drawInRect:(_listLayout?NSMakeRect(120,NSMidY(bounds)-9,MAX(1,bounds.size.width-136),20):NSMakeRect(7,NSMaxY(bounds)-24,bounds.size.width-14,18)) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:11 weight:_chosen?NSFontWeightSemibold:NSFontWeightRegular],NSForegroundColorAttributeName:DYBrowserColor(_palette,@"text"),NSParagraphStyleAttributeName:paragraph}]; [DYBrowserColor(_palette,_chosen?@"accent":@"border")setStroke];outline.lineWidth=_chosen?2:1;[outline stroke]; } - (void)mouseDown:(NSEvent *)event{self.doubleClicked=event.clickCount>1;[super mouseDown:event];} @end @interface DYBrowserFolderButton : NSButton @property(copy) NSDictionary *palette; @property BOOL chosen; @end @implementation DYBrowserFolderButton - (BOOL)isFlipped{return YES;} - (void)dealloc{[_palette release];[super dealloc];} - (void)drawRect:(NSRect)dirty{ if(_chosen){[DYBrowserColor(_palette,@"field")setFill];[[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds,1,1) xRadius:5 yRadius:5]fill];} NSMutableParagraphStyle *paragraph=[[[NSMutableParagraphStyle alloc]init]autorelease];paragraph.lineBreakMode=NSLineBreakByTruncatingMiddle; [self.title drawInRect:NSInsetRect(self.bounds,9,8) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:11 weight:_chosen?NSFontWeightSemibold:NSFontWeightRegular],NSForegroundColorAttributeName:DYBrowserColor(_palette,_chosen?@"accent":@"text"),NSParagraphStyleAttributeName:paragraph}]; } @end @class DYLUTBrowser; /// The jobs own this token, never the browser or its host selection block. @interface DYBrowserWork : NSObject @property(assign) DYLUTBrowser *owner; @property BOOL cancelled; @end @implementation DYBrowserWork @end @interface DYLUTBrowser () { DYLUTLibrary *_library; NSData *_preview; NSString *_selectedPath,*_folder; NSDictionary *_palette; DYLUTSelectionHandler _selection; void (^_closeAction)(void); NSPopover *_popover; NSWindow *_presentationWindow;NSSplitView *_splitView;NSPopUpButton *_layoutMenu; DYBrowserCanvas *_root,*_folderDocument,*_gridDocument; NSScrollView *_folderScroll,*_gridScroll; NSTextField *_titleLabel,*_countLabel,*_statusLabel,*_sizeLabel,*_emptyLabel; NSSearchField *_search; NSButton *_importFiles,*_importFolder,*_reveal,*_refresh,*_none,*_done; NSSlider *_sizeSlider; NSMutableArray *_folderButtons; NSMutableDictionary *_tiles; NSArray *_visibleEntries,*_folderPaths; NSMutableSet *_queuedPaths; NSCache *_thumbnailCache; dispatch_queue_t _previewQueue; DYBrowserWork *_work; BOOL _closed,_sizing,_visible,_remoteMode,_importing,_layingOut,_detached; NSProgress *_libraryTask,*_selectionTask; NSTimer *_progressTimer; NSUInteger _libraryGeneration,_selectionGeneration; NSInteger _columns; CGFloat _tileWidth,_tileHeight,_sidebarWidth; } @end @implementation DYLUTBrowser + (NSSize)minimumContentSize{return NSMakeSize(720,420);} + (NSSize)maximumContentSize{return NSMakeSize(1800,1200);} + (NSSize)preferredContentSize{ NSString *key=[NSString stringWithFormat:@"%@|%@",DYBrowserFramePreference,DYLUTLibrary.defaultRootURL.path]; NSString *saved=[[NSUserDefaults standardUserDefaults]stringForKey:key];NSRect frame=saved?NSRectFromString(saved):NSZeroRect; if(!std::isfinite(frame.size.width)||!std::isfinite(frame.size.height)||frame.size.width<720||frame.size.height<420)return NSMakeSize(900,620); NSSize content=[NSWindow contentRectForFrameRect:frame styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable].size; return NSMakeSize(MIN(1800,MAX(720,content.width)),MIN(1200,MAX(420,content.height))); } static NSTextField *BrowserLabel(NSString *title,CGFloat size){NSTextField *label=[NSTextField labelWithString:title];label.font=[NSFont systemFontOfSize:size];label.lineBreakMode=NSLineBreakByTruncatingTail;return label;} static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *button=[NSButton buttonWithTitle:title target:target action:action];button.font=[NSFont systemFontOfSize:11];button.bezelStyle=NSBezelStyleRounded;return button;} - (instancetype)initWithLibrary:(DYLUTLibrary *)library preview:(NSData *)rgba selectedPath:(NSString *)path palette:(NSDictionary *)palette selection:(DYLUTSelectionHandler)selection{ NSPanel *panel=[[[NSPanel alloc]initWithContentRect:NSMakeRect(0,0,760,560) styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]autorelease]; if((self=[super initWithWindow:panel])){ NSString *savedFolder=[[NSUserDefaults standardUserDefaults]stringForKey:DYBrowserPreference(DYBrowserFolderPreference,library)]?:[[NSUserDefaults standardUserDefaults]stringForKey:DYBrowserFolderPreference]; if(!library.recentPaths.count&&path.length)[library recordUsedPath:path]; if(!savedFolder)savedFolder=library.recentPaths.count?DYBrowserRecentFolder:@"*"; _library=[library retain];_preview=[rgba copy];_selectedPath=[path copy];_folder=[(savedFolder?:@"*") copy];_selection=[selection copy]; _folderButtons=[NSMutableArray new];_tiles=[NSMutableDictionary new];_queuedPaths=[NSMutableSet new];_thumbnailCache=[NSCache new];_thumbnailCache.countLimit=600;_thumbnailCache.totalCostLimit=64*1024*1024;_previewQueue=dispatch_queue_create("com.dayu.color.lut-thumbnails",DISPATCH_QUEUE_SERIAL);dispatch_set_target_queue(_previewQueue,dispatch_get_global_queue(QOS_CLASS_UTILITY,0)); panel.title=@"风格 LUT";panel.contentMinSize=self.class.minimumContentSize;panel.contentMaxSize=self.class.maximumContentSize;panel.releasedWhenClosed=NO;panel.hidesOnDeactivate=NO;panel.delegate=self; _root=[[DYBrowserCanvas alloc]initWithFrame:NSMakeRect(0,0,760,560)];_root.accessibilityLabel=@"LUT 缩略图浏览库";panel.contentView=_root; _titleLabel=[BrowserLabel(@"LUT 文件夹",14)retain];_titleLabel.font=[NSFont systemFontOfSize:14 weight:NSFontWeightSemibold]; _countLabel=[BrowserLabel(@"0 个 LUT",11)retain]; _statusLabel=[BrowserLabel(@"单击缩略图应用 LUT",11)retain]; _sizeLabel=[BrowserLabel(@"缩略图大小",11)retain]; _emptyLabel=[BrowserLabel(@"此文件夹还没有 LUT。\n点“导入文件”或“导入文件夹”添加 .cube 文件。",13)retain];_emptyLabel.maximumNumberOfLines=3;_emptyLabel.alignment=NSTextAlignmentCenter; _search=[[NSSearchField alloc]initWithFrame:NSZeroRect];_search.placeholderString=@"搜索 LUT";_search.accessibilityLabel=@"搜索 LUT";_search.delegate=self;_search.target=self;_search.action=@selector(searchChanged:); _importFiles=[BrowserButton(@"导入文件…",self,@selector(importFiles:))retain];_importFiles.accessibilityLabel=@"导入 LUT 文件"; _importFolder=[BrowserButton(@"导入文件夹…",self,@selector(importFolder:))retain];_importFolder.accessibilityLabel=@"导入 LUT 文件夹"; _reveal=[BrowserButton(@"打开文件夹",self,@selector(revealLibrary:))retain]; _refresh=[BrowserButton(@"刷新",self,@selector(reloadLibrary:))retain]; _none=[BrowserButton(@"无 LUT",self,@selector(clearSelection:))retain]; _done=[BrowserButton(@"完成",self,@selector(done:))retain];_done.keyEquivalent=@"\r"; NSUserDefaults *preferences=NSUserDefaults.standardUserDefaults; NSNumber *storedSize=[preferences objectForKey:DYBrowserPreference(DYBrowserSizePreference,library)]?:[preferences objectForKey:DYBrowserSizePreference];double size=storedSize?storedSize.doubleValue:120; _layoutMenu=[[NSPopUpButton alloc]initWithFrame:NSZeroRect pullsDown:NO];[_layoutMenu addItemsWithTitles:@[@"网格",@"列表"]];_layoutMenu.font=[NSFont systemFontOfSize:11];_layoutMenu.target=self;_layoutMenu.action=@selector(layoutChanged:);_layoutMenu.accessibilityLabel=@"LUT 浏览布局"; [_layoutMenu selectItemAtIndex:[preferences integerForKey:DYBrowserPreference(DYBrowserLayoutPreference,library)]==1?1:0]; double sidebar=[preferences doubleForKey:DYBrowserPreference(DYBrowserSidebarPreference,library)];_sidebarWidth=std::isfinite(sidebar)&&sidebar>=128?MIN(360,sidebar):162; if(!std::isfinite(size))size=96; _sizeSlider=[[NSSlider alloc]initWithFrame:NSZeroRect];_sizeSlider.minValue=70;_sizeSlider.maxValue=255;_sizeSlider.doubleValue=fmax(70,fmin(255,size));_sizeSlider.continuous=YES;_sizeSlider.target=self;_sizeSlider.action=@selector(sizeChanged:);_sizeSlider.accessibilityLabel=@"LUT 缩略图大小"; _folderScroll=[[NSScrollView alloc]initWithFrame:NSZeroRect];_folderScroll.hasVerticalScroller=YES;_folderScroll.autohidesScrollers=YES;_folderScroll.borderType=NSNoBorder;_folderScroll.drawsBackground=NO;_folderScroll.accessibilityLabel=@"LUT 文件夹列表"; _gridScroll=[[NSScrollView alloc]initWithFrame:NSZeroRect];_gridScroll.hasVerticalScroller=YES;_gridScroll.autohidesScrollers=YES;_gridScroll.borderType=NSNoBorder;_gridScroll.drawsBackground=NO;_gridScroll.accessibilityLabel=@"LUT 缩略图网格"; _folderDocument=[[DYBrowserCanvas alloc]initWithFrame:NSZeroRect];_folderDocument.fillKey=@"card";_folderDocument.palette=_palette;_folderDocument.accessibilityLabel=@"LUT 文件夹";_folderScroll.documentView=_folderDocument; _gridDocument=[[DYBrowserCanvas alloc]initWithFrame:NSZeroRect];_gridDocument.palette=_palette;_gridDocument.accessibilityLabel=@"LUT 缩略图";_gridScroll.documentView=_gridDocument; _folderScroll.contentView.postsBoundsChangedNotifications=YES; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(folderScrolled:) name:NSViewBoundsDidChangeNotification object:_folderScroll.contentView]; _gridScroll.contentView.postsBoundsChangedNotifications=YES; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gridScrolled:) name:NSViewBoundsDidChangeNotification object:_gridScroll.contentView]; _splitView=[[NSSplitView alloc]initWithFrame:NSMakeRect(12,80,736,425)];_splitView.vertical=YES;_splitView.dividerStyle=NSSplitViewDividerStyleThin;_splitView.accessibilityLabel=@"调整 LUT 文件夹与预览宽度"; _folderScroll.frame=NSMakeRect(0,0,162,425);_gridScroll.frame=NSMakeRect(163,0,573,425);[_splitView addSubview:_folderScroll];[_splitView addSubview:_gridScroll]; for(NSView *view in @[_titleLabel,_countLabel,_statusLabel,_sizeLabel,_search,_importFiles,_importFolder,_reveal,_refresh,_none,_done,_sizeSlider,_layoutMenu,_splitView])[_root addSubview:view]; [_gridDocument addSubview:_emptyLabel]; _root.postsFrameChangedNotifications=YES;_root.postsBoundsChangedNotifications=YES; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(browserRootResized:) name:NSViewFrameDidChangeNotification object:_root]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(browserRootResized:) name:NSViewBoundsDidChangeNotification object:_root]; _splitView.delegate=self;[self reloadLibrary:nil];[self updatePalette:palette];[self layoutBrowser]; } return self; } - (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]; [_root release];[_folderDocument release];[_gridDocument release];[_folderScroll release];[_gridScroll release]; [_titleLabel release];[_countLabel release];[_statusLabel release];[_sizeLabel release];[_emptyLabel release];[_search release]; [_importFiles release];[_importFolder release];[_reveal release];[_refresh release];[_none release];[_done release];[_sizeSlider release];[_layoutMenu release];_splitView.delegate=nil;[_splitView release];[_presentationWindow release]; [_folderButtons release];[_folderPaths release];[_tiles release];[_visibleEntries release];[_queuedPaths release];[_thumbnailCache release]; dispatch_release(_previewQueue);[super dealloc]; } - (void)showRelativeToView:(NSView *)view{ if(_closed||_remoteMode||!view.window||_popover.shown)return; self.window.contentView=[[[NSView alloc]initWithFrame:NSMakeRect(0,0,1,1)]autorelease]; NSSize size=self.class.preferredContentSize;[_root removeFromSuperview];_root.frame=(NSRect){NSZeroPoint,size};_root.autoresizingMask=NSViewWidthSizable|NSViewHeightSizable; _popover=[[NSPopover alloc]init];_popover.behavior=NSPopoverBehaviorSemitransient;_popover.animates=YES;_popover.delegate=self;_popover.contentSize=size; NSViewController *controller=[[[NSViewController alloc]init]autorelease];controller.title=@"风格 LUT";controller.view=_root;_popover.contentViewController=controller; [self layoutBrowser]; @try {[_popover showRelativeToRect:view.bounds ofView:view preferredEdge:NSRectEdgeMaxX];_visible=_popover.shown;} @catch(NSException *exception){[self finishClosing];} } - (BOOL)visible{return !_closed&&((_remoteMode||_detached)?_visible:_popover.shown);} - (void)showInRemoteParent:(NSView *)parent close:(void (^)(void))closeAction{ if(_closed||!parent||self.visible)return; _remoteMode=YES;_visible=YES;[_closeAction release];_closeAction=[closeAction copy]; self.window.contentView=[[[NSView alloc]initWithFrame:NSMakeRect(0,0,1,1)]autorelease]; [_root removeFromSuperview];_root.frame=parent.bounds;_root.autoresizingMask=NSViewWidthSizable|NSViewHeightSizable;_root.hidden=NO; // FxRemoteWindow owns the window and may publish view geometry separately. // Follow the supplied parent without changing the bridge's resize policy. parent.postsFrameChangedNotifications=YES;parent.postsBoundsChangedNotifications=YES; for(NSNotificationName name in @[NSViewFrameDidChangeNotification,NSViewBoundsDidChangeNotification])[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(remoteParentGeometryChanged:) name:name object:parent]; [parent addSubview:_root];DYBrowserGeometrySample(_root,@"before-content-origin-alignment");[self fitRemoteParent]; DYBrowserGeometrySample(_root,@"attached-before-sdk-reply"); // Attach synchronously: the SDK reads the first child before reply returns. dispatch_async(dispatch_get_main_queue(),^{if(!_closed){[self configurePresentationWindow];DYBrowserGeometrySample(_root,@"after-sdk-reply");}}); if([NSUserDefaults.standardUserDefaults boolForKey:@"DYBrowserGeometryDiagnostics"])dispatch_after(dispatch_time(DISPATCH_TIME_NOW,NSEC_PER_SEC),dispatch_get_main_queue(),^{if(!_closed)DYBrowserGeometrySample(_root,@"settled");}); NSAccessibilityPostNotification(parent,NSAccessibilityLayoutChangedNotification); } - (void)fitRemoteParent{ NSView *parent=_root.superview;if(_closed||!_remoteMode||!parent)return; // A scaled-display ViewBridge service can hand us its top-level content // view with a stale frame origin (observed: 789,521 in an 1800x1200 window). // Matching only its bounds keeps our child correct inside a displaced // container. Align that content origin using AppKit's coordinate APIs; // leave the host's window, content size and bridge resize policy intact. NSWindow *window=parent.window; if(window&&parent==window.contentView&&parent.superview){ NSRect screenContent=[window contentRectForFrameRect:window.frame]; NSRect windowContent=[window convertRectFromScreen:screenContent]; NSPoint origin=[parent.superview convertPoint:windowContent.origin fromView:nil]; if(std::isfinite(origin.x)&&std::isfinite(origin.y)&&!NSEqualPoints(parent.frame.origin,origin))[parent setFrameOrigin:origin]; } if(!NSEqualRects(_root.frame,parent.bounds))_root.frame=parent.bounds; [self layoutBrowser];[_root setNeedsDisplay:YES]; } - (void)remoteParentGeometryChanged:(NSNotification *)notification{ if(notification.object==_root.superview)[self fitRemoteParent]; DYBrowserGeometrySample(_root,notification.name); } - (void)configurePresentationWindow{ NSWindow *window=_root.window;if(!window||window==self.window)return; if(_presentationWindow!=window){[_presentationWindow release];_presentationWindow=[window retain]; for(NSNotificationName name in @[NSWindowDidMoveNotification,NSWindowDidResizeNotification])[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(presentationGeometryChanged:) name:name object:window]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(presentationWindowClosed:) name:NSWindowWillCloseNotification object:window]; } // The v2 API caps the size to 80% of the host window. A service-side NSWindow // is not authority to override that geometry, metadata or saved position. if(_remoteMode){[self fitRemoteParent];return;} window.title=@"风格 LUT";window.contentMinSize=self.class.minimumContentSize;window.contentMaxSize=self.class.maximumContentSize; if(_detached)window.styleMask|=NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable; NSString *saved=[NSUserDefaults.standardUserDefaults stringForKey:DYBrowserPreference(DYBrowserFramePreference,_library)]; NSRect frame=saved?NSRectFromString(saved):[window frameRectForContentRect:(NSRect){window.frame.origin,self.class.preferredContentSize}]; if(std::isfinite(frame.origin.x)&&std::isfinite(frame.origin.y)&&std::isfinite(frame.size.width)&&std::isfinite(frame.size.height)&&frame.size.width>=720&&frame.size.height>=420){ NSScreen *target=window.screen?:NSScreen.mainScreen;CGFloat largest=0; for(NSScreen *candidate in NSScreen.screens){NSRect overlap=NSIntersectionRect(frame,candidate.visibleFrame);CGFloat area=overlap.size.width*overlap.size.height;if(area>largest){largest=area;target=candidate;}} if(target){ NSRect screen=target.visibleFrame;NSSize available=[window contentRectForFrameRect:screen].size,minimum=self.class.minimumContentSize,maximum=self.class.maximumContentSize; minimum=NSMakeSize(MIN(minimum.width,available.width),MIN(minimum.height,available.height));maximum=NSMakeSize(MIN(maximum.width,available.width),MIN(maximum.height,available.height)); window.contentMinSize=minimum;window.contentMaxSize=maximum; NSRect content=[window contentRectForFrameRect:frame];content.size=NSMakeSize(MIN(maximum.width,MAX(minimum.width,content.size.width)),MIN(maximum.height,MAX(minimum.height,content.size.height)));frame=[window frameRectForContentRect:content]; frame.origin.x=MAX(NSMinX(screen),MIN(frame.origin.x,NSMaxX(screen)-frame.size.width));frame.origin.y=MAX(NSMinY(screen),MIN(frame.origin.y,NSMaxY(screen)-frame.size.height));[window setFrame:frame display:YES]; } } [self layoutBrowser]; } - (void)presentationGeometryChanged:(NSNotification *)notification{ if(_closed||!_presentationWindow)return;if(_remoteMode){[self fitRemoteParent];return;}NSRect frame=_presentationWindow.frame; if(std::isfinite(frame.size.width)&&std::isfinite(frame.size.height)&&frame.size.width>=720&&frame.size.height>=420)[NSUserDefaults.standardUserDefaults setObject:NSStringFromRect(frame) forKey:DYBrowserPreference(DYBrowserFramePreference,_library)]; [self layoutBrowser]; } - (void)presentationWindowClosed:(NSNotification *)notification{[self finishClosing];} - (BOOL)popoverShouldDetach:(NSPopover *)popover{return YES;} - (void)popoverDidDetach:(NSPopover *)popover{_detached=YES;_visible=YES;[self configurePresentationWindow];} - (void)browserRootResized:(NSNotification *)notification{if(!_closed)[self layoutBrowser];} - (void)windowDidResize:(NSNotification *)notification{[self layoutBrowser];} - (void)windowWillClose:(NSNotification *)notification{[self finishClosing];} - (BOOL)popoverShouldClose:(NSPopover *)popover{return !_importing;} - (void)popoverDidClose:(NSNotification *)notification{if([notification.userInfo[NSPopoverCloseReasonKey]isEqual:NSPopoverCloseReasonDetachToWindow])return;[self finishClosing];} - (void)close{ if(_closed)return; if(_detached&&_presentationWindow){[_presentationWindow performClose:nil];if(!_closed)[self finishClosing];} else if(_popover.shown){[_popover close];if(!_closed)[self finishClosing];} else [self finishClosing]; } - (void)finishClosing{ if(_closed)return; // 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;[_libraryTask cancel];[_selectionTask cancel];[_progressTimer invalidate];[_progressTimer release];_progressTimer=nil; _popover.delegate=nil;if(_popover.shown)[_popover close]; if(_remoteMode&&_root.superview)for(NSNotificationName name in @[NSViewFrameDidChangeNotification,NSViewBoundsDidChangeNotification])[[NSNotificationCenter defaultCenter]removeObserver:self name:name object:_root.superview]; [_root removeFromSuperview];[_queuedPaths removeAllObjects];[_thumbnailCache removeAllObjects]; [_selection release];_selection=nil; void (^closeAction)(void)=[_closeAction copy];[_closeAction release];_closeAction=nil; if(closeAction)closeAction();[closeAction release]; [self release]; } - (void)layoutBrowser{ if(_layingOut)return;_layingOut=YES; CGFloat w=_root.bounds.size.width,h=_root.bounds.size.height; _titleLabel.frame=NSMakeRect(14,12,160,20);_countLabel.frame=NSMakeRect(180,14,120,18); _search.frame=NSMakeRect(14,46,MAX(125,w-350),24); _importFiles.frame=NSMakeRect(w-322,44,100,28);_importFolder.frame=NSMakeRect(w-218,44,113,28);_refresh.frame=NSMakeRect(w-101,44,82,28); _splitView.frame=NSMakeRect(12,80,MAX(400,w-24),MAX(140,h-135));[_splitView adjustSubviews]; CGFloat sidebar=MAX(128,MIN(_sidebarWidth,MIN(360,_splitView.bounds.size.width*.45)));[_splitView setPosition:sidebar ofDividerAtIndex:0]; _reveal.frame=NSMakeRect(w-153,9,139,27);_none.frame=NSMakeRect(14,h-44,75,27);_layoutMenu.frame=NSMakeRect(100,h-44,97,27); _sizeLabel.frame=NSMakeRect(211,h-39,74,18);_sizeSlider.frame=NSMakeRect(288,h-41,MIN(150,MAX(80,w-550)),20); _done.frame=NSMakeRect(w-98,h-44,78,27); CGFloat statusX=NSMaxX(_sizeSlider.frame)+14;_statusLabel.frame=NSMakeRect(statusX,h-39,MAX(0,w-statusX-112),18); CGFloat fw=MAX(100,_folderScroll.contentSize.width); _folderDocument.frame=NSMakeRect(0,0,fw,MAX(_folderPaths.count*35+4,_folderScroll.contentSize.height)); [self updateVisibleFolders]; CGFloat available=MAX(80,_gridScroll.contentSize.width),tileWidth=_sizeSlider.doubleValue,gap=10; BOOL list=_layoutMenu.indexOfSelectedItem==1;NSInteger columns=list?1:MAX(1,(NSInteger)floor((available+gap)/(tileWidth+gap)));tileWidth=list?MAX(110,available-14):MIN(tileWidth,(available-gap*(columns-1)-14)/columns);tileWidth=MAX(70,tileWidth); _columns=columns;_tileWidth=tileWidth;_tileHeight=list?70: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]; } - (CGFloat)splitView:(NSSplitView *)split constrainMinCoordinate:(CGFloat)proposed ofSubviewAt:(NSInteger)index{return 128;} - (CGFloat)splitView:(NSSplitView *)split constrainMaxCoordinate:(CGFloat)proposed ofSubviewAt:(NSInteger)index{return MIN(360,split.bounds.size.width*.45);} - (void)splitViewDidResizeSubviews:(NSNotification *)notification{ if(_closed||_layingOut)return;_sidebarWidth=_folderScroll.frame.size.width;[NSUserDefaults.standardUserDefaults setDouble:_sidebarWidth forKey:DYBrowserPreference(DYBrowserSidebarPreference,_library)];[self layoutBrowser]; } - (void)layoutChanged:(id)sender{[NSUserDefaults.standardUserDefaults setInteger:_layoutMenu.indexOfSelectedItem forKey:DYBrowserPreference(DYBrowserLayoutPreference,_library)];[self layoutBrowser];} - (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;i.7&&background.greenComponent>.7; // Keep the supplied neutral surface in both relief themes. [_palette release];_palette=[browserPalette copy];_root.palette=_palette;_folderDocument.palette=_palette;_gridDocument.palette=_palette; self.window.backgroundColor=DYBrowserColor(_palette,@"background");self.window.appearance=[NSAppearance appearanceNamed:light?NSAppearanceNameAqua:NSAppearanceNameDarkAqua]; _root.appearance=[NSAppearance appearanceNamed:light?NSAppearanceNameAqua:NSAppearanceNameDarkAqua]; for(NSTextField *label in @[_titleLabel,_countLabel,_statusLabel,_sizeLabel,_emptyLabel])label.textColor=DYBrowserColor(_palette,label==_titleLabel?@"text":@"secondary"); for(NSButton *button in @[_importFiles,_importFolder,_reveal,_refresh,_none,_done,_layoutMenu])button.contentTintColor=DYBrowserColor(_palette,@"accent"); _search.textColor=DYBrowserColor(_palette,@"text");_search.backgroundColor=DYBrowserColor(_palette,@"field"); for(DYBrowserFolderButton *button in _folderButtons){button.palette=_palette;[button setNeedsDisplay:YES];} for(DYBrowserTile *tile in _tiles.allValues){tile.palette=_palette;[tile setNeedsDisplay:YES];} [_root setNeedsDisplay:YES];[_folderDocument setNeedsDisplay:YES];[_gridDocument setNeedsDisplay:YES]; } - (void)updatePreview:(NSData *)rgba{ if(_closed||_preview==rgba||[_preview isEqualToData:rgba])return; if(rgba&&rgba.length!=320*180*16)return; [_preview release];_preview=[rgba copy];[_thumbnailCache removeAllObjects]; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshThumbnailSize) object:nil]; [self refreshThumbnailSize]; } - (void)setStatus:(NSString *)status{_statusLabel.stringValue=status?:@"";_statusLabel.toolTip=status;} - (void)rebuildFolders{ NSMutableArray *paths=[NSMutableArray arrayWithObjects:DYBrowserRecentFolder,@"*",nil];NSMutableSet *seen=[NSMutableSet setWithArray:paths]; for(NSString *folder in _library.folders){NSString *top=folder.length?[folder componentsSeparatedByString:@"/"].firstObject:@"";if(![seen containsObject:top]){[paths addObject:top];[seen addObject:top];}} if(![seen containsObject:_folder]){[_folder release];_folder=[@"*" copy];} [_folderPaths release];_folderPaths=[paths copy];[self updateVisibleFolders]; } - (void)folderScrolled:(NSNotification *)notification{if(!_layingOut)[self updateVisibleFolders];} - (void)updateVisibleFolders { if(_closed)return;NSRect visible=NSInsetRect(_folderScroll.contentView.bounds,0,-35); NSUInteger first=(NSUInteger)MAX(0,floor(NSMinY(visible)/35)),end=MIN(_folderPaths.count,(NSUInteger)MAX(0,ceil(NSMaxY(visible)/35)+1)); NSMutableDictionary *existing=[NSMutableDictionary dictionary];for(NSButton *button in _folderButtons)existing[button.identifier]=button; NSMutableArray *buttons=[NSMutableArray array]; for(NSUInteger i=first;i_queuedPaths removeObject:cacheKey]; NSDictionary *result=image?@{@"image":image}:@{@"error":failure?:@"无法预览此 LUT"}; [owner->_thumbnailCache setObject:result forKey:cacheKey cost:image?width*height*4:128]; DYBrowserTile *current=owner->_tiles[path];if(!current||!NSIntersectsRect(current.frame,NSInsetRect(owner->_gridScroll.contentView.bounds,-30,-180)))return; current.thumbnail=image;current.failure=failure;current.enabled=image!=nil;if(failure.length)current.toolTip=failure;[current setNeedsDisplay:YES]; }); }}); } } - (void)rebuildGrid{ [self resetThumbnailWork]; for(NSView *tile in _tiles.allValues)[tile removeFromSuperview];[_tiles removeAllObjects]; NSString *query=[_search.stringValue stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];NSMutableArray *entries=[NSMutableArray array]; BOOL recent=[_folder isEqual:DYBrowserRecentFolder];NSArray *history=_library.recentPaths; for(NSDictionary *entry in (recent?_library.recentEntries:_library.entries)){ NSString *folder=entry[@"relativeFolder"]?:@""; BOOL folderMatch=recent||[_folder isEqualToString:@"*"]||[folder isEqualToString:_folder]||(_folder.length&&[folder hasPrefix:[_folder stringByAppendingString:@"/"]]); if(folderMatch&&(!query.length||[entry[@"name"]localizedCaseInsensitiveContainsString:query]||[entry[@"relativePath"]localizedCaseInsensitiveContainsString:query]))[entries addObject:entry]; } if(!recent)[entries sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){NSUInteger i=[history indexOfObject:a[@"path"]],j=[history indexOfObject:b[@"path"]];if(i==j)return [a[@"relativePath"]localizedStandardCompare:b[@"relativePath"]];return i0; [_gridScroll.contentView scrollToPoint:NSZeroPoint];[self layoutBrowser];[_gridScroll reflectScrolledClipView:_gridScroll.contentView]; NSAccessibilityPostNotification(_gridDocument,NSAccessibilityLayoutChangedNotification); } - (void)thumbnailClicked:(DYBrowserTile *)sender{ 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]]; void (^applied)(NSError *)=^(NSError *error){ if(_closed||generation!=_selectionGeneration)return;[_selectionTask release];_selectionTask=nil; if(error){[self setStatus:error.localizedDescription];return;} [_selectedPath release];_selectedPath=[path copy];[_library recordUsedPath:path];[self rebuildGrid]; for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=[tile.identifier isEqualToString:path];[tile setNeedsDisplay:YES];} [self setStatus:[@"已选择 " stringByAppendingString:name]];if(closeAfter)[self close]; }; _selectionTask=[(_selection?_selection(path,applied):DYLUTPrepareAsync(path,applied))retain]; } - (void)clearSelection:(id)sender{ NSUInteger generation=++_selectionGeneration;[_selectionTask cancel];[_selectionTask release];_selectionTask=nil; [self setStatus:@"正在移除 LUT…"]; void (^cleared)(NSError *)=^(NSError *error){ if(_closed||generation!=_selectionGeneration)return;[_selectionTask release];_selectionTask=nil; if(error){[self setStatus:error.localizedDescription];return;} [_selectedPath release];_selectedPath=nil; for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=NO;[tile setNeedsDisplay:YES];} [self setStatus:@"已移除 LUT"]; }; if(_selection)_selectionTask=[_selection(nil,cleared)retain];else cleared(nil); } - (void)done:(id)sender{[self close];} - (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"]; // FxPlug bridges the modal chooser; the asynchronous AppKit chooser cannot // become key in the service. Only choosing a path is modal; file work is not. _importing=YES;NSModalResponse response=[panel runModal];_importing=NO; if(response==NSModalResponseOK&&!_closed)[self importSelectedURLs:panel.URLs]; } - (void)importFiles:(id)sender{[self importPanelForFolders:NO];} - (void)importFolder:(id)sender{[self importPanelForFolders:YES];} - (void)revealLibrary:(id)sender{ NSError *error=nil; if(![[NSFileManager defaultManager]createDirectoryAtURL:_library.rootURL withIntermediateDirectories:YES attributes:nil error:&error]){[self showImportError:error];return;} if(![[NSWorkspace sharedWorkspace]openURL:_library.rootURL])[self setStatus:@"无法打开 LUT 文件夹"]; } @end