文件
dayu-color/大鱼调色/Plugin/DYViewerParameterBridge.inc.h
T

220 行
13 KiB
Objective-C

// 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<PROAPIAccessing>)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)endGesture;
// Call before the owning plug-in releases this object during teardown.
- (void)invalidate;
@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<lo)return NO;
if([d[@"kind"]isEqual:@"bool"])v=v>=.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(v<lo||v>hi)return NO;
}
if(output)*output=v;return YES;
}
@implementation DYViewerParameterBridge {
id<PROAPIAccessing> _apiManager;
NSDictionary *_snapshot,*_sourceDocument;
CMTime _snapshotTime;
BOOL _invalidated,_validationScheduled;
uint64_t _requestSequence,_requestedGesture;
// The fields below are confined to the main queue.
id<PROAPIAccessing> _writerHost,_writerTarget;
NSDictionary *_writerDescriptor,*_writerCompanions;
NSString *_writerNode,*_writerType;
CMTime _writerTime;
double _writerLastValue;
uint64_t _writerGesture;
BOOL _writerUndoOpen;
}
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)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];
[_writerDescriptor release];[_writerCompanions release];[_writerNode release];[_writerType release];[super dealloc];
}
- (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){
id<FxCustomParameterActionAPI_v4>action=[_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;
[_writerDescriptor release];_writerDescriptor=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;
double value=NAN;
BOOL read=[[_writerTarget apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:&value fromParameter:[_writerDescriptor[@"pid"]unsignedIntValue] atTime:_writerTime];
if(!read||!DYViewerSameValue(value,_writerLastValue))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.
id<FxParameterRetrievalAPI_v6>get=[_writerTarget apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];
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;
id<FxCustomParameterActionAPI_v4>action=[_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 *canonical=DYViewerCanonicalDescriptor(descriptor);double sanitized=0;
if(!canonical||![nodeID isKindOfClass:NSString.class]||!CMTIME_IS_NUMERIC(time)||!DYViewerSanitizeValue(canonical,value,&sanitized))return;
NSString *node=[nodeID copy];NSDictionary *d=[canonical retain];uint64_t gesture;
@synchronized(self){if(_invalidated){[node release];[d release];return;}_requestedGesture=gesture=++_requestSequence;}
dispatch_async(dispatch_get_main_queue(),^{
[self closeWriter];id<PROAPIAccessing>host=nil;
@synchronized(self){if(!self->_invalidated)host=[self->_apiManager retain];}
if(!host)return;
id<FxCustomParameterActionAPI_v4>action=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];
if(!action){[host release];return;}
id<PROAPIAccessing>target=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];}}
if(!DYViewerDescriptorBelongsToType(d,type)){[target release];target=nil;}
type=[type copy];
}
}@finally{[action endAction:self];}
if(target){
self->_writerHost=host;self->_writerTarget=target;self->_writerDescriptor=[d retain];self->_writerNode=[node copy];self->_writerType=type;
self->_writerTime=time;self->_writerGesture=gesture;self->_writerLastValue=sanitized;
if(![self writerStillValid])[self closeWriter];
}else{[type release];[host release];}
});
[node release];[d release];
}
- (void)writeValue:(double)value gesture:(uint64_t)gesture {
NSCAssert(NSThread.isMainThread,@"Host writes require the main queue");
if(!_writerGesture||gesture!=_writerGesture)return;double v=0;
if(!DYViewerSanitizeValue(_writerDescriptor,value,&v))return;
BOOL active;@synchronized(self){active=!_invalidated;}if(!active){[self closeWriter];return;}
id<FxCustomParameterActionAPI_v4>action=[_writerTarget apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];
if(!action){[self closeWriter];return;}BOOL conflict=NO,changed=NO;
[action startAction:self];@try{
conflict=!CMTIME_IS_NUMERIC(action.currentTime)||CMTimeCompare(action.currentTime,_writerTime)!=0||![self writerValueMatches];
if(!conflict&&!DYViewerSameValue(v,_writerLastValue)){
id<FxUndoAPI>undo=[_writerHost apiForProtocol:@protocol(FxUndoAPI)];
if(!_writerUndoOpen)_writerUndoOpen=[undo startUndoGroup:[@"画面调整 · " stringByAppendingString:_writerDescriptor[@"title"]?:@"调色"]];
if(_writerUndoOpen){
id<FxParameterSettingAPI_v6>set=[_writerTarget apiForProtocol:@protocol(FxParameterSettingAPI_v6)];
NSString *key=_writerDescriptor[@"key"];
changed=[set setFloatValue:v toParameter:[_writerDescriptor[@"pid"]unsignedIntValue] atTime:_writerTime];
if(changed){
// Mirror scalarChanged in the inspector. Eye/bypass switches remain
// literal switches and are never cleared by their own click.
BOOL primaryValue=[key hasPrefix:@"cm"]&&![key hasPrefix:@"cmbypass"]&&![key isEqual:@"cmConfigured"]&&![key hasSuffix:@"Enabled"];
if(primaryValue||[key isEqual:@"blackWhiteMix"]){
id<FxParameterRetrievalAPI_v6>get=[_writerTarget apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];DYInspectorToken *old=nil;
[get getCustomParameterValue:&old fromParameter:DYInspectorParameterID atTime:_writerTime];
if(primaryValue){[set setFloatValue:1 toParameter:2236 atTime:_writerTime];for(NSDictionary *r in DYDescriptors())if([r[@"key"]hasPrefix:@"cmbypass"])[set setFloatValue:0 toParameter:[r[@"pid"]unsignedIntValue] atTime:_writerTime];}
else if(old.schema<2){double configured=0;[get getFloatValue:&configured fromParameter:2236 atTime:_writerTime];if(configured<.5)[set setFloatValue:-1 toParameter:2236 atTime:_writerTime];}
if(old&&old.schema<2){DYInspectorToken *token=[[old copy]autorelease];token.schema=2;[set setCustomParameterValue:token toParameter:DYInspectorParameterID atTime:_writerTime];}
}
DYPrimaryControlChanged(_writerTarget,_writerTime,key);
double actual=v;[[_writerTarget apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:&actual fromParameter:[_writerDescriptor[@"pid"]unsignedIntValue] atTime:_writerTime];_writerLastValue=actual;
if(primaryValue||[key isEqual:@"blackWhiteMix"]){
NSMutableDictionary *companions=[NSMutableDictionary dictionary];id<FxParameterRetrievalAPI_v6>get=[_writerTarget apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];
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)[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(),^{[self writeValue:value gesture:gesture];});
}
- (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