#include "DYScopeDisplayTime.h" #include "DYSpiderState.h" #import "DYHistogram.h" // The OSC side publishes values and enqueues intent. Only the main queue enters // host actions; no OSC/render callback waits for AppKit or a host model write. @interface DYViewerParameterBridge : NSObject - (instancetype)initWithAPIManager:(id)manager; - (void)publishUniforms:(const DYUniforms*)uniforms document:(NSDictionary*)document atTime:(CMTime)time; - (NSDictionary*)snapshotAtTime:(CMTime)time; - (void)beginParameter:(NSDictionary*)descriptor node:(NSString*)nodeID value:(double)value atTime:(CMTime)time; - (void)changeValue:(double)value; - (void)beginParameters:(NSArray*)descriptors node:(NSString*)nodeID values:(NSDictionary*)values atTime:(CMTime)time; // Every sample supplies every key selected by beginParameters. Invalid or // incomplete samples are rejected as a unit, before the first host write. - (void)changeValues:(NSDictionary*)values; - (void)endGesture; - (uint64_t)endCurveGesture; - (BOOL)gesturePending:(uint64_t)gesture; // Call before the owning plug-in releases this object during teardown. - (void)invalidate; - (void)requestWorkspace; - (void)requestMosaicMenu; - (void)requestMosaicMenuFromView:(NSView*)anchor; - (void)requestWorkspacePage:(NSString *)page; - (void)requestMask:(NSInteger)kind; - (void)requestTool:(NSString*)type; - (void)requestWhiteBalanceAtTime:(CMTime)time; @property(nonatomic,retain) DYRenderer *renderer; - (NSData*)canvasHistogramAtTime:(CMTime)time; - (void)publishAssets:(DYAssetState*)assets atTime:(CMTime)time; - (void)beginSpider:(NSData*)mesh node:(NSString*)node enabled:(double)enabled atTime:(CMTime)time; - (void)changeSpider:(NSData*)mesh; @end static BOOL DYViewerSameValue(double a,double b) { return std::isfinite(a)&&std::isfinite(b)&&fabs(a-b)<=1e-6*MAX(1.,MAX(fabs(a),fabs(b))); } static NSDictionary *DYViewerCanonicalDescriptor(NSDictionary *candidate) { if(![candidate isKindOfClass:NSDictionary.class])return nil; for(NSDictionary *d in DYDescriptors())if([d[@"pid"]isEqual:candidate[@"pid"]]&&[d[@"key"]isEqual:candidate[@"key"]])return d; return nil; } static BOOL DYViewerDescriptorBelongsToType(NSDictionary *d,NSString *type) { if(!type.length)return NO; for(NSDictionary *owned in DYBaseToolDescriptors(type))if([owned[@"pid"]isEqual:d[@"pid"]])return YES; return NO; } static BOOL DYViewerSanitizeValue(NSDictionary *d,double input,double *output) { if(!d||!std::isfinite(input))return NO; double lo=[d[@"min"]doubleValue],hi=[d[@"max"]doubleValue],v=MAX(lo,MIN(hi,input)); if(!std::isfinite(lo)||!std::isfinite(hi)||hi=.5?1:0; else if([d[@"kind"]isEqual:@"popup"]){ // A popup is an enum, not a continuous range. Unknown choices must not // silently turn into the first/last item when a stale event is received. v=round(input);NSArray *values=d[@"values"]; if(values){BOOL found=NO;for(NSNumber *number in values)if(DYViewerSameValue(v,number.doubleValue)){v=number.doubleValue;found=YES;break;}if(!found)return NO;} else if(v<0||v>=(double)[d[@"options"]count])return NO; if(vhi)return NO; } if(output)*output=v;return YES; } @implementation DYViewerParameterBridge { id _apiManager; NSDictionary *_snapshot,*_sourceDocument;NSString *_selectedNode; CMTime _snapshotTime; BOOL _invalidated,_validationScheduled; uint64_t _requestSequence,_requestedGesture,_completedGesture; // The fields below are confined to the main queue. id _writerHost,_writerTarget; NSArray *_writerDescriptors; NSDictionary *_writerLastValues,*_writerCompanions; NSString *_writerNode,*_writerType; CMTime _writerTime; uint64_t _writerGesture; BOOL _writerUndoOpen,_writerSpider; NSData *_writerLastMesh; } @synthesize renderer=_renderer; - (instancetype)initWithAPIManager:(id)manager { if((self=[super init])){_apiManager=manager;_snapshotTime=kCMTimeInvalid;_writerTime=kCMTimeInvalid;[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(workspaceSelected:) name:@"DYWorkspaceToolSelection" object:manager];[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(mosaicMenuRequested:) name:@"DYMosaicMenuRequested" object:manager];}return self; } - (void)dealloc { // invalidate enqueues closure before the owner releases its final reference; // the queued block keeps the bridge alive until its host group is closed. NSCAssert(!_writerUndoOpen,@"Viewer parameter group must be closed before teardown"); [NSNotificationCenter.defaultCenter removeObserver:self];[_renderer release];[_selectedNode release];[_snapshot release];[_sourceDocument release];[_writerHost release];[_writerTarget release]; [_writerDescriptors release];[_writerLastValues release];[_writerCompanions release];[_writerNode release];[_writerType release];[super dealloc]; } - (void)publishAssets:(DYAssetState*)assets atTime:(CMTime)time { @synchronized(self){if(_invalidated||!_snapshot||CMTimeCompare(time,_snapshotTime)!=0)return;NSMutableDictionary *next=[[_snapshot mutableCopy]autorelease];next[@"spider"]=assets.spiderMesh?:[NSData data];[_snapshot release];_snapshot=[next copy];} } - (NSData*)canvasHistogramAtTime:(CMTime)time { return [_renderer canvasHistogramAtTime:time]; } - (void)requestWhiteBalanceAtTime:(CMTime)time { if(!CMTIME_IS_NUMERIC(time))return; dispatch_async(dispatch_get_main_queue(),^{ id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;} if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYViewerWhiteBalanceRequested" object:manager userInfo:@{@"time":[(NSDictionary*)CMTimeCopyAsDictionary(time,kCFAllocatorDefault) autorelease]}]; }); } - (void)requestTool:(NSString*)type { if(![DYToolTypes()containsObject:type])return; dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYViewerToolRequested" object:manager userInfo:@{@"type":type}];}); } - (void)applyMosaicMenu:(NSMenuItem*)item { id manager=nil;@synchronized(self){if(!_invalidated)manager=_apiManager;}if(!manager)return; ida=[manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self]; @try{ NSMutableDictionary *doc=DYMutablePlist(DYReadTools(manager,a.currentTime).document); NSMutableDictionary *settings=[NSMutableDictionary dictionaryWithDictionary:doc[@"mosaic"]?:@{@"enabled":@NO,@"source":@"face",@"size":@32}]; [settings addEntriesFromDictionary:item.representedObject]; if([settings[@"source"]isEqual:@"mask"]&&!DYSharedMaskWithID(doc,settings[@"maskID"]))return; doc[@"mosaic"]=settings;idundo=[manager apiForProtocol:@protocol(FxUndoAPI)]; if([undo startUndoGroup:@"局部马赛克"]){DYWriteTools(manager,doc,a.currentTime);[undo endUndoGroup];} }@finally{[a endAction:self];} [_renderer invalidatePreview];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:manager]; } - (void)mosaicMenuRequested:(NSNotification*)note {[self requestMosaicMenuFromView:note.userInfo[@"anchor"]];} - (void)requestMosaicMenu {[self requestMosaicMenuFromView:nil];} - (void)requestMosaicMenuFromView:(NSView*)anchor { dispatch_async(dispatch_get_main_queue(),^{ id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(!manager)return; ida=[manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];NSDictionary *doc=nil; @try{doc=[DYReadTools(manager,a.currentTime).document retain];}@finally{[a endAction:self];} NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"局部马赛克"]autorelease];NSDictionary *settings=doc[@"mosaic"]; auto add=[&](NSString *title,NSDictionary *value,BOOL checked){NSMenuItem *item=[menu addItemWithTitle:title action:@selector(applyMosaicMenu:) keyEquivalent:@""];item.target=self;item.representedObject=value;item.state=checked?NSControlStateValueOn:NSControlStateValueOff;}; add(@"应用到人脸(逐帧识别)",@{@"source":@"face",@"enabled":@YES},[settings[@"enabled"]boolValue]&&[settings[@"source"]isEqual:@"face"]); NSInteger count=0; for(NSDictionary *mask in DYSharedMasks(doc)){if(mask[@"stampSource"])continue;count++;DYMaskParameters p=DYMaskAtTime(mask,kCMTimeInvalid);NSString *shape=@[@"椭圆",@"矩形",@"钢笔",@"渐变",@"HSL",@"亮度"][p.kind]; add([NSString stringWithFormat:@"应用到蒙版 %ld · %@%@",(long)count,shape,[mask[@"keys"]count]?@" · 已跟踪":@""],@{@"source":@"mask",@"maskID":mask[@"id"],@"enabled":@YES},[settings[@"enabled"]boolValue]&&[settings[@"source"]isEqual:@"mask"]&&[settings[@"maskID"]isEqual:mask[@"id"]]); } if(!count){NSMenuItem *hint=[menu addItemWithTitle:@"先用矩形、椭圆或钢笔绘制蒙版" action:nil keyEquivalent:@""];hint.enabled=NO;} [menu addItem:NSMenuItem.separatorItem]; for(NSNumber *size in @[@8,@16,@32,@64,@96,@128])add([NSString stringWithFormat:@"方块大小:%@",size],@{@"size":size},[settings[@"size"]isEqual:size]); [menu addItem:NSMenuItem.separatorItem];add(@"关闭局部马赛克",@{@"enabled":@NO},![settings[@"enabled"]boolValue]); [doc release];[menu popUpMenuPositioningItem:nil atLocation:anchor?NSMakePoint(0,NSMaxY(anchor.bounds)):NSEvent.mouseLocation inView:anchor]; }); } - (void)requestWorkspace{ [self requestWorkspacePage:@"tools"]; } - (void)requestWorkspacePage:(NSString *)page { if(![@[@"tools",@"lut",@"scopes",@"masks"]containsObject:page])return; dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYColorWorkspaceRequested" object:manager userInfo:@{@"page":page}];}); } - (void)requestMask:(NSInteger)kind { if(kind<0||kind>2)return; dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYColorWorkspaceRequested" object:manager userInfo:@{@"page":@"masks",@"maskKind":@(kind)}];}); } - (void)workspaceSelected:(NSNotification *)note { NSString *node=note.userInfo[@"node"];if(![node isKindOfClass:NSString.class])return; @synchronized(self){[_selectedNode release];_selectedNode=[node copy];} } - (void)publishUniforms:(const DYUniforms*)uniforms document:(NSDictionary*)document atTime:(CMTime)time { if(!uniforms||!document||!CMTIME_IS_NUMERIC(time))return; NSDictionary *frozen=nil; @synchronized(self){ if(_invalidated)return; if(document==_sourceDocument&&![document isKindOfClass:NSMutableDictionary.class])frozen=[_snapshot[@"document"]retain]; } if(!frozen){ DYToolDocument *copy=[[[DYToolDocument alloc]init]autorelease]; if(!DYValidToolDocument(document))return;copy.document=document;frozen=[copy.document retain]; } NSData *bytes=[NSData dataWithBytes:uniforms length:sizeof(*uniforms)];BOOL validate=NO; @synchronized(self){ if(!_invalidated){ [_snapshot release];_snapshot=[@{@"uniforms":bytes,@"document":frozen,@"timeValue":@(time.value),@"timeScale":@(time.timescale),@"timeEpoch":@(time.epoch)}copy]; [_sourceDocument release];_sourceDocument=[document retain];_snapshotTime=time; if(_requestedGesture&&!_validationScheduled){_validationScheduled=YES;validate=YES;} } } [frozen release]; if(validate)dispatch_async(dispatch_get_main_queue(),^{ @synchronized(self){self->_validationScheduled=NO;} if(self->_writerGesture&&![self writerStillValid])[self closeWriter]; }); } - (NSDictionary*)snapshotAtTime:(CMTime)time { @synchronized(self){ if(_invalidated||!CMTIME_IS_NUMERIC(time)||!CMTIME_IS_NUMERIC(_snapshotTime)||CMTimeCompare(time,_snapshotTime)!=0)return nil; if(_selectedNode.length){NSMutableDictionary *snapshot=[[_snapshot mutableCopy]autorelease];snapshot[@"selectedNode"]=_selectedNode;return snapshot;} return [[_snapshot retain]autorelease]; } } - (void)closeWriter { NSCAssert(NSThread.isMainThread,@"Host writes require the main queue"); if(_writerUndoOpen){ idaction=[_writerHost apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]; [action startAction:self];@try{[[_writerHost apiForProtocol:@protocol(FxUndoAPI)]endUndoGroup];}@finally{[action endAction:self];} } _writerUndoOpen=NO;_writerSpider=NO;[_writerLastMesh release];_writerLastMesh=nil;_writerGesture=0;_writerTime=kCMTimeInvalid; [_writerHost release];_writerHost=nil;[_writerTarget release];_writerTarget=nil; [_writerDescriptors release];_writerDescriptors=nil;[_writerLastValues release];_writerLastValues=nil; [_writerCompanions release];_writerCompanions=nil; [_writerNode release];_writerNode=nil;[_writerType release];_writerType=nil; } - (BOOL)writerNodeExists { NSDictionary *doc=DYReadTools(_writerHost,_writerTime).document; if([_writerNode hasPrefix:@"base:"])return !DYBaseToolRemoved(doc,_writerType); NSDictionary *node=DYToolWithID(doc,_writerNode);return node&&[node[@"type"]isEqual:_writerType]; } - (BOOL)writerValueMatches { if(![self writerNodeExists])return NO; if(_writerSpider){NSData *current=DYReadAssets(_writerTarget,_writerTime).spiderMesh?:[NSData data];if(![current isEqual:_writerLastMesh])return NO;} idget=[_writerTarget apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]; for(NSDictionary *d in _writerDescriptors){double value=NAN; if(![get getFloatValue:&value fromParameter:[d[@"pid"]unsignedIntValue] atTime:_writerTime]||!DYViewerSameValue(value,[_writerLastValues[d[@"key"]]doubleValue]))return NO; } // Primary scalar edits also touch configuration/bypass switches. A later // external change to any of those switches must win over this live drag. for(NSNumber *pid in _writerCompanions){double companion=NAN;if(![get getFloatValue:&companion fromParameter:pid.unsignedIntValue atTime:_writerTime]||!DYViewerSameValue(companion,[_writerCompanions[pid]doubleValue]))return NO;} return YES; } - (BOOL)writerStillValid { if(!_writerGesture)return NO;BOOL active; @synchronized(self){active=!_invalidated;} if(!active)return NO; idaction=[_writerTarget apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!action)return NO; BOOL valid=NO;[action startAction:self];@try{ valid=CMTIME_IS_NUMERIC(action.currentTime)&&CMTimeCompare(DYHostDisplayedFrameTime(_writerHost,action.currentTime),_writerTime)==0&&[self writerValueMatches]; }@finally{[action endAction:self];}return valid; } - (void)beginParameter:(NSDictionary*)descriptor node:(NSString*)nodeID value:(double)value atTime:(CMTime)time { NSDictionary *d=DYViewerCanonicalDescriptor(descriptor);if(!d)return; [self beginParameters:@[d] node:nodeID values:@{d[@"key"]:@(value)} atTime:time]; } - (void)beginParameters:(NSArray*)descriptors node:(NSString*)nodeID values:(NSDictionary*)values atTime:(CMTime)time { if(![descriptors isKindOfClass:NSArray.class]||!descriptors.count||descriptors.count>DYDescriptors().count||![values isKindOfClass:NSDictionary.class]||values.count!=descriptors.count||![nodeID isKindOfClass:NSString.class]||!CMTIME_IS_NUMERIC(time))return; NSMutableArray *canonical=[NSMutableArray array];NSMutableDictionary *original=[NSMutableDictionary dictionary];NSMutableSet *pids=[NSMutableSet set]; for(NSDictionary *candidate in descriptors){ NSDictionary *d=DYViewerCanonicalDescriptor(candidate);NSNumber *number=d?values[d[@"key"]]:nil;double sanitized=0; if(!d||original[d[@"key"]]||[pids containsObject:d[@"pid"]]||![number isKindOfClass:NSNumber.class]||!DYViewerSanitizeValue(d,number.doubleValue,&sanitized))return; [canonical addObject:d];[pids addObject:d[@"pid"]];original[d[@"key"]]=@(sanitized); } NSString *node=[nodeID copy];NSArray *selected=[canonical copy];NSDictionary *initial=[original copy];uint64_t gesture; @synchronized(self){if(_invalidated){[node release];[selected release];[initial release];return;}_requestedGesture=gesture=++_requestSequence;} dispatch_async(dispatch_get_main_queue(),^{ [self closeWriter];idhost=nil; @synchronized(self){if(!self->_invalidated)host=[self->_apiManager retain];} if(!host)return; idaction=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]; if(!action){[host release];return;} idtarget=nil;NSString *type=nil; [action startAction:self];@try{ if(CMTIME_IS_NUMERIC(action.currentTime)&&CMTimeCompare(DYHostDisplayedFrameTime(host,action.currentTime),time)==0){ NSDictionary *doc=DYReadTools(host,time).document; if([node hasPrefix:@"base:"]){type=[node substringFromIndex:5];if([DYToolTypes()containsObject:type]&&!DYBaseToolRemoved(doc,type))target=[host retain];} else{NSDictionary *layer=DYToolWithID(doc,node);if(layer){type=layer[@"type"];target=[[DYToolManager alloc]initWithHost:host node:layer];}} for(NSDictionary *d in selected)if(!DYViewerDescriptorBelongsToType(d,type)){[target release];target=nil;break;} type=[type copy]; } }@finally{[action endAction:self];} os_log(OS_LOG_DEFAULT,"dayu_viewer_begin accepted=%{public}d event=%{public}.9f action=%{public}.9f count=%{public}lu",target!=nil,CMTimeGetSeconds(time),CMTimeGetSeconds(action.currentTime),(unsigned long)selected.count); if(target){ self->_writerHost=host;self->_writerTarget=target;self->_writerDescriptors=[selected retain];self->_writerLastValues=[initial retain];self->_writerNode=[node copy];self->_writerType=type; self->_writerTime=time;self->_writerGesture=gesture; if(![self writerStillValid])[self closeWriter]; }else{[type release];[host release];} }); [node release];[selected release];[initial release]; } - (void)beginSpider:(NSData*)mesh node:(NSString*)node enabled:(double)enabled atTime:(CMTime)time { if(mesh.length&&!DYSpiderMeshIsValid(mesh))return;NSDictionary *descriptor=nil;for(NSDictionary*d in DYDescriptors())if([d[@"key"]isEqual:@"spiderEnabled"])descriptor=d; if(!descriptor)return;[self beginParameter:descriptor node:node value:enabled atTime:time];uint64_t gesture;@synchronized(self){gesture=_requestedGesture;}NSData *original=[mesh copy]?:[NSData new]; dispatch_async(dispatch_get_main_queue(),^{if(self->_writerGesture==gesture&&[self->_writerType isEqual:@"spider"]){self->_writerSpider=YES;self->_writerLastMesh=[original copy];if(![self writerStillValid])[self closeWriter];}});[original release]; } - (void)changeSpider:(NSData*)mesh { if(!DYSpiderMeshIsValid(mesh))return;NSData *frozen=[mesh copy];uint64_t gesture;@synchronized(self){gesture=_invalidated?0:_requestedGesture;} if(gesture)dispatch_async(dispatch_get_main_queue(),^{ if(self->_writerGesture!=gesture||!self->_writerSpider)return; if(![self writerStillValid]){[self closeWriter];return;} if([frozen isEqual:self->_writerLastMesh])return; ida=[self->_writerTarget apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];BOOL changed=NO,failed=NO; [a startAction:self];@try{ if(!CMTIME_IS_NUMERIC(a.currentTime)||CMTimeCompare(DYHostDisplayedFrameTime(self->_writerHost,a.currentTime),self->_writerTime)!=0||![self writerValueMatches]){failed=YES;} else{ if(!self->_writerUndoOpen)self->_writerUndoOpen=[[self->_writerHost apiForProtocol:@protocol(FxUndoAPI)]startUndoGroup:@"画面调整 · 蜘蛛盘"]; if(self->_writerUndoOpen){DYAssetState *old=DYReadAssets(self->_writerTarget,self->_writerTime);DYAssetState *next=[[old copy]autorelease];next.spiderMesh=frozen; failed=!DYWriteAssets(self->_writerTarget,next,self->_writerTime); if(failed)DYWriteAssets(self->_writerTarget,old,self->_writerTime);else changed=YES; } } }@finally{[a endAction:self];} // Re-read after DYToolManager commits its document at the outer boundary. if(changed){[a startAction:self];NSData *actual=nil;@try{actual=[DYReadAssets(self->_writerTarget,self->_writerTime).spiderMesh retain];}@finally{[a endAction:self];}BOOL saved=[actual isEqual:frozen];[actual release];if(!saved)failed=YES;else{[self->_writerLastMesh release];self->_writerLastMesh=[frozen copy];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self->_apiManager];}} if(failed)[self closeWriter]; });[frozen release]; } - (void)writeValues:(NSDictionary*)values gesture:(uint64_t)gesture { NSCAssert(NSThread.isMainThread,@"Host writes require the main queue"); if(!_writerGesture||gesture!=_writerGesture||values.count!=_writerDescriptors.count)return; NSMutableDictionary *desired=[NSMutableDictionary dictionary];BOOL anyChanged=NO,primaryValue=NO,blackWhite=NO;NSString *workingKey=nil; NSMutableSet *explicitPids=[NSMutableSet set]; for(NSDictionary *d in _writerDescriptors){ NSString *key=d[@"key"];NSNumber *number=values[key];double v=0; if(![number isKindOfClass:NSNumber.class]||!DYViewerSanitizeValue(d,number.doubleValue,&v))return; desired[key]=@(v);[explicitPids addObject:d[@"pid"]]; if(!DYViewerSameValue(v,[_writerLastValues[key]doubleValue])){ anyChanged=YES; primaryValue|=[key hasPrefix:@"cm"]&&![key hasPrefix:@"cmbypass"]&&![key isEqual:@"cmConfigured"]&&![key hasSuffix:@"Enabled"]; blackWhite|=[key isEqual:@"blackWhiteMix"]; if([@[@"cmworkingTransfer",@"cmworkingGamut"]containsObject:key])workingKey=key; } } BOOL active;@synchronized(self){active=!_invalidated;}if(!active){[self closeWriter];return;} idaction=[_writerTarget apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]; if(!action){[self closeWriter];return;}BOOL conflict=NO,changed=NO,failed=NO; [action startAction:self];@try{ conflict=!CMTIME_IS_NUMERIC(action.currentTime)||CMTimeCompare(DYHostDisplayedFrameTime(_writerHost,action.currentTime),_writerTime)!=0||![self writerValueMatches]; if(!conflict&&anyChanged){ idundo=[_writerHost apiForProtocol:@protocol(FxUndoAPI)]; NSString *title=_writerDescriptors.count==1?_writerDescriptors[0][@"title"]:@"图形控件"; if(!_writerUndoOpen)_writerUndoOpen=[undo startUndoGroup:[@"画面调整 · " stringByAppendingString:title?:@"调色"]]; if(_writerUndoOpen){ idset=[_writerTarget apiForProtocol:@protocol(FxParameterSettingAPI_v6)]; idget=[_writerTarget apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]; NSMutableDictionary *before=[NSMutableDictionary dictionary]; for(NSDictionary *d in _writerDescriptors)before[d[@"pid"]]=_writerLastValues[d[@"key"]]; DYInspectorToken *old=nil; if(primaryValue||blackWhite){ [get getCustomParameterValue:&old fromParameter:DYInspectorParameterID atTime:_writerTime]; for(NSDictionary *r in DYDescriptors())if([r[@"key"]isEqual:@"cmConfigured"]||(primaryValue&&[r[@"key"]hasPrefix:@"cmbypass"])){double previous=NAN;if([get getFloatValue:&previous fromParameter:[r[@"pid"]unsignedIntValue] atTime:_writerTime]&&std::isfinite(previous))before[r[@"pid"]]=@(previous);} } // Prevalidation and conflict checks cover the entire batch. Both axes are // set inside this one action; an independent layer commits one document. for(NSDictionary *d in _writerDescriptors)if(![set setFloatValue:[desired[d[@"key"]]doubleValue] toParameter:[d[@"pid"]unsignedIntValue] atTime:_writerTime]){failed=YES;break;} if(!failed&&(primaryValue||blackWhite)){ // Explicit switches in the batch remain literal switches. Automatic CST // companions never overwrite a requested eye/configuration/bypass value. if(primaryValue){ if(![explicitPids containsObject:@2236])failed|=![set setFloatValue:1 toParameter:2236 atTime:_writerTime]; for(NSDictionary *r in DYDescriptors())if([r[@"key"]hasPrefix:@"cmbypass"]&&![explicitPids containsObject:r[@"pid"]])failed|=![set setFloatValue:0 toParameter:[r[@"pid"]unsignedIntValue] atTime:_writerTime]; }else if(old.schema<2&&![explicitPids containsObject:@2236]){double configured=0;[get getFloatValue:&configured fromParameter:2236 atTime:_writerTime];if(configured<.5)failed|=![set setFloatValue:-1 toParameter:2236 atTime:_writerTime];} if(!failed&&old&&old.schema<2){DYInspectorToken *token=[[old copy]autorelease];token.schema=2;failed|=![set setCustomParameterValue:token toParameter:DYInspectorParameterID atTime:_writerTime];} } if(failed){ // The host API has no abortAction. Restore all affected fields before // ending the action rather than leaving half a graphic update behind. for(NSNumber *pid in before)[set setFloatValue:[before[pid]doubleValue] toParameter:pid.unsignedIntValue atTime:_writerTime]; if(old)[set setCustomParameterValue:old toParameter:DYInspectorParameterID atTime:_writerTime]; }else{ if(workingKey)DYPrimaryControlChanged(_writerTarget,_writerTime,workingKey); NSMutableDictionary *actual=[NSMutableDictionary dictionary]; for(NSDictionary *d in _writerDescriptors){double v=[desired[d[@"key"]]doubleValue];[get getFloatValue:&v fromParameter:[d[@"pid"]unsignedIntValue] atTime:_writerTime];actual[d[@"key"]]=@(v);} [_writerLastValues release];_writerLastValues=[actual copy];changed=YES; if(primaryValue||blackWhite){ NSMutableDictionary *companions=[NSMutableDictionary dictionary]; for(NSDictionary *r in DYDescriptors())if([r[@"key"]isEqual:@"cmConfigured"]||(primaryValue&&[r[@"key"]hasPrefix:@"cmbypass"])){double related=NAN;if([get getFloatValue:&related fromParameter:[r[@"pid"]unsignedIntValue] atTime:_writerTime]&&std::isfinite(related))companions[r[@"pid"]]=@(related);} [_writerCompanions release];_writerCompanions=[companions copy]; } } } } }@finally{[action endAction:self];} if(conflict||failed){os_log(OS_LOG_DEFAULT,"dayu_viewer_write rejected conflict=%{public}d failed=%{public}d event=%{public}.9f action=%{public}.9f",conflict,failed,CMTimeGetSeconds(_writerTime),CMTimeGetSeconds(action.currentTime));[self closeWriter];} if(changed){os_log(OS_LOG_DEFAULT,"dayu_viewer_write saved count=%{public}lu time=%{public}.9f",(unsigned long)desired.count,CMTimeGetSeconds(_writerTime));[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_apiManager];} } - (void)changeValue:(double)value { if(!std::isfinite(value))return;uint64_t gesture; @synchronized(self){if(_invalidated)return;gesture=_requestedGesture;} if(gesture)dispatch_async(dispatch_get_main_queue(),^{if(self->_writerGesture==gesture&&self->_writerDescriptors.count==1)[self writeValues:@{self->_writerDescriptors[0][@"key"]:@(value)} gesture:gesture];}); } - (void)changeValues:(NSDictionary*)values { if(![values isKindOfClass:NSDictionary.class]||!values.count)return; // Copy only validated primitive input, so callers may reuse mutable samples. NSMutableDictionary *sample=[NSMutableDictionary dictionary]; for(id key in values){id value=values[key];if(![key isKindOfClass:NSString.class]||![value isKindOfClass:NSNumber.class]||!std::isfinite([value doubleValue]))return;sample[[[key copy]autorelease]]=@([value doubleValue]);} NSDictionary *frozen=[sample copy];uint64_t gesture; @synchronized(self){if(_invalidated){[frozen release];return;}gesture=_requestedGesture;} if(gesture)dispatch_async(dispatch_get_main_queue(),^{[self writeValues:frozen gesture:gesture];}); [frozen release]; } - (void)refreshSavedCurve { if(![_writerType isEqual:@"curve"])return; id action=[_writerHost apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]; id get=[_writerHost apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]; BOOL base=[_writerNode hasPrefix:@"base:"]; NSMutableDictionary *values=[NSMutableDictionary dictionary]; NSDictionary *document=nil; [action startAction:self];@try{ if(CMTimeCompare(DYHostDisplayedFrameTime(_writerHost,action.currentTime),_writerTime)!=0)return; if(base)for(NSDictionary *d in _writerDescriptors){ double value=NAN; if(![get getFloatValue:&value fromParameter:[d[@"pid"]unsignedIntValue] atTime:_writerTime]||!std::isfinite(value))return; values[d[@"offset"]]=@(value); }else document=DYReadTools(_writerHost,_writerTime).document; }@finally{[action endAction:self];} @synchronized(self){ if(_invalidated||!_snapshot||CMTimeCompare(_snapshotTime,_writerTime)!=0)return; NSMutableDictionary *next=[[_snapshot mutableCopy]autorelease]; if(base){ DYUniforms uniforms; [next[@"uniforms"] getBytes:&uniforms length:sizeof(uniforms)]; for(NSNumber *offset in values)*(float*)((uint8_t*)&uniforms+offset.unsignedIntegerValue)=[values[offset]floatValue]; next[@"uniforms"]=[NSData dataWithBytes:&uniforms length:sizeof(uniforms)]; }else if(document){ next[@"document"]=document; [_sourceDocument release];_sourceDocument=nil; } [_snapshot release];_snapshot=[next copy]; } } - (uint64_t)finishGestureRefreshingCurve:(BOOL)refresh { uint64_t gesture;@synchronized(self){gesture=_requestedGesture;_requestedGesture=0;} if(gesture)dispatch_async(dispatch_get_main_queue(),^{ if(self->_writerGesture==gesture){ if(refresh)[self refreshSavedCurve]; [self closeWriter]; } @synchronized(self){self->_completedGesture=MAX(self->_completedGesture,gesture);} }); return gesture; } - (void)endGesture { [self finishGestureRefreshingCurve:NO]; } - (uint64_t)endCurveGesture { return [self finishGestureRefreshingCurve:YES]; } - (BOOL)gesturePending:(uint64_t)gesture { @synchronized(self){return !_invalidated&&gesture>_completedGesture;} } - (void)invalidate { @synchronized(self){if(_invalidated)return;_invalidated=YES;_requestedGesture=0;_apiManager=nil;} dispatch_async(dispatch_get_main_queue(),^{[self closeWriter];}); } @end