// 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; // Call before the owning plug-in releases this object during teardown. - (void)invalidate; - (void)requestWorkspace; @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; CMTime _snapshotTime; BOOL _invalidated,_validationScheduled; uint64_t _requestSequence,_requestedGesture; // 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; } - (instancetype)initWithAPIManager:(id)manager { if((self=[super init])){_apiManager=manager;_snapshotTime=kCMTimeInvalid;_writerTime=kCMTimeInvalid;}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"); [_snapshot release];[_sourceDocument release];[_writerHost release];[_writerTarget release]; [_writerDescriptors release];[_writerLastValues release];[_writerCompanions release];[_writerNode release];[_writerType release];[super dealloc]; } - (void)requestWorkspace{ dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!_invalidated)manager=_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYColorWorkspaceRequested" object:manager];}); } - (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; 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;_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; 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(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(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];} 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)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(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)[self closeWriter]; if(changed)[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)endGesture { uint64_t gesture;@synchronized(self){gesture=_requestedGesture;_requestedGesture=0;} if(gesture)dispatch_async(dispatch_get_main_queue(),^{if(self->_writerGesture==gesture)[self closeWriter];}); } - (void)invalidate { @synchronized(self){if(_invalidated)return;_invalidated=YES;_requestedGesture=0;_apiManager=nil;} dispatch_async(dispatch_get_main_queue(),^{[self closeWriter];}); } @end