// Host-provided canvas coordinates, normalized to the actual object transform. @interface DYToolOSC : NSObject @property(nonatomic,assign) id apiManager; @end @implementation DYToolOSC { id _device;id _queue;CIContext *_context; DYViewerControls *_viewerControls;CGFloat _height,_canvasWidth,_uiScale;BOOL _maskCapturing;DYPlugIn *_maskCaptureOwner;NSRect _imageRect;NSDictionary *_mask;NSMutableArray *_handles;NSBezierPath *_outline;NSInteger _lastRoute;NSUInteger _drawCount,_hitDiagnostics,_eventDiagnostics; BOOL _hslSampling; BOOL _stampHasSource,_stampDragging,_stampSaving,_stampNeedsRedraw; NSPoint _stampSource,_stampStart,_stampEnd; NSString *_stampFailure,*_levelFailure; DYLevelTransform _level; double _levelAngle; NSInteger _levelMode; CMTime _levelTime; BOOL _levelHasFirst,_levelDown,_levelSecondPress,_levelSaving,_levelPlaced; NSInteger _levelEditingEnd; NSDictionary *_levelState; NSPoint _levelFirst,_levelLast; } - (instancetype)initWithAPIManager:(id)manager{if((self=[super init])){_apiManager=manager;_viewerControls=[DYViewerControls new];_handles=[NSMutableArray new];_lastRoute=-1;_uiScale=1;os_log(OS_LOG_DEFAULT,"dayu_tool_osc_init");}return self;} - (void)dealloc{[_viewerControls release];[_device release];[_queue release];[_context release];[_mask release];[_handles release];[_outline release];[_stampFailure release];[_levelFailure release];[_levelState release];[super dealloc];} - (FxDrawingCoordinates)drawingCoordinates{return kFxDrawingCoordinates_CANVAS;} - (DYPlugIn*)pluginAtTime:(CMTime)time{NSString *value=nil;idget=[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];[get getStringParameterValue:&value fromParameter:DYCanvasSessionParameterID];@synchronized(DYToolCanvasSessions()){return [DYToolCanvasSessions()objectForKey:value];}} - (void)clearLevelLine { _levelHasFirst=_levelDown=_levelSecondPress=_levelPlaced=NO;_levelEditingEnd=0; [_levelFailure release];_levelFailure=nil; } - (void)restoreLevelReference { [self clearLevelLine]; NSArray *points=_levelState[@"levelReference"][@"points"]; if(points.count==4){_levelFirst=NSMakePoint([points[0]doubleValue],[points[1]doubleValue]);_levelLast=NSMakePoint([points[2]doubleValue],[points[3]doubleValue]);_levelPlaced=YES;} } - (void)updateLevelFrom:(DYPlugIn *)plugin { double angle=0; double fallback=NSWidth(_imageRect)>0&&NSHeight(_imageRect)>0?NSWidth(_imageRect)/NSHeight(_imageRect):1; _level=plugin?[plugin toolCanvasLevelForAspect:fallback rotation:&angle]:DYLevelTransform(0,fallback); NSDictionary *state=plugin?[plugin toolCanvasLevelState]:@{}; BOOL changed=![_levelState isEqual:state]; if(changed){[_levelState release];_levelState=[state copy];[self restoreLevelReference];} if(!_levelMode&&_viewerControls.levelMode){[self restoreLevelReference];NSInteger mode=[state[@"levelReference"][@"mode"]integerValue];if(mode)_viewerControls.levelMode=mode;} if(_levelMode&&!_viewerControls.levelMode)[self restoreLevelReference]; _levelMode=_viewerControls.levelMode;_levelAngle=angle; _viewerControls.levelMeasureOnly=[state[@"levelMeasureOnly"]boolValue]; } - (NSPoint)displayUV:(NSPoint)point { return NSMakePoint((point.x-NSMinX(_imageRect))/NSWidth(_imageRect),(point.y-NSMinY(_imageRect))/NSHeight(_imageRect)); } - (NSPoint)clampedDisplayUV:(NSPoint)point { NSPoint uv=[self displayUV:point]; return NSMakePoint(std::clamp(uv.x,0.,1.),std::clamp(uv.y,0.,1.)); } - (NSPoint)canvasDisplayPoint:(NSPoint)uv { return NSMakePoint(NSMinX(_imageRect)+uv.x*NSWidth(_imageRect),NSMinY(_imageRect)+uv.y*NSHeight(_imageRect)); } - (void)commitLevelState:(NSDictionary *)state plugin:(DYPlugIn *)plugin { if(_levelSaving)return;_levelSaving=YES; DYViewerParameterBridge *bridge=_viewerControls.bridge; [plugin saveCanvasLevel:state replacing:_levelState?:@{} completion:^(NSString *failure){ @synchronized(self){ self->_levelSaving=NO; if(self->_viewerControls.bridge!=bridge)return; [self updateLevelFrom:plugin];_hslSampling=[plugin canvasHSLSampling];[self restoreLevelReference]; self->_levelFailure=[failure copy]; } }]; } - (void)commitLevelReference:(DYPlugIn *)plugin { double corrected=DYLevelDelta(_levelFirst,_levelLast,_level.aspect,_levelMode==2); NSMutableDictionary *state=[NSMutableDictionary dictionaryWithDictionary:_levelState?:@{}]; state[@"levelRotation"]=@(fabs(corrected)<1e-7?0:corrected); state[@"levelReference"]=@{@"points":@[@(_levelFirst.x),@(_levelFirst.y),@(_levelLast.x),@(_levelLast.y)],@"aspect":@(_level.aspect),@"mode":@(_levelMode)}; [self commitLevelState:state plugin:plugin]; } - (BOOL)handleLevelEvent:(NSEventType)type point:(NSPoint)point part:(NSInteger)part key:(unichar)key time:(CMTime)time plugin:(DYPlugIn *)plugin { if(!_levelMode||!plugin)return NO; if(type==NSEventTypeKeyDown&&key==27){ [self restoreLevelReference];_viewerControls.levelMode=0;return YES; } if(_levelHasFirst&&(type==NSEventTypeLeftMouseDown||type==NSEventTypeLeftMouseUp)&& (time.epoch!=_levelTime.epoch||fabs(CMTimeGetSeconds(CMTimeSubtract(time,_levelTime)))>.05))[self restoreLevelReference]; if(type==NSEventTypeLeftMouseDown&&(part==10015||part==10016||part==10017)){ if(_levelSaving)return YES; [_levelFailure release];_levelFailure=nil; _levelDown=YES;_levelSecondPress=_levelHasFirst; NSPoint source=_level.toSource([self clampedDisplayUV:point]); _levelEditingEnd=part==10016?1:part==10017?2:0; if(_levelEditingEnd){_levelTime=time;return YES;} _levelPlaced=NO; _levelLast=source; if(!_levelHasFirst){_levelFirst=source;_levelTime=time;_levelHasFirst=YES;} return YES; } if(!_levelDown||(type!=NSEventTypeLeftMouseDragged&&type!=NSEventTypeLeftMouseUp))return NO; NSPoint source=_level.toSource([self clampedDisplayUV:point]); if(_levelEditingEnd==1)_levelFirst=source;else _levelLast=source; if(type==NSEventTypeLeftMouseUp){ _levelDown=NO; NSPoint first=[self canvasDisplayPoint:_level.toOutput(_levelFirst)],last=[self canvasDisplayPoint:_level.toOutput(_levelLast)]; double distance=hypot(last.x-first.x,last.y-first.y); if(distance>=5*_uiScale)[self commitLevelReference:plugin]; else if(_levelSecondPress||_levelEditingEnd){[self restoreLevelReference];_levelFailure=[@"两点太近,请重新选择。" copy];} } return YES; } - (void)drawLevelControls { if(!_levelMode)return; NSRect viewport=NSIntersectionRect(_imageRect,NSMakeRect(0,0,_canvasWidth,_height)); CGFloat scale=MIN(_uiScale,NSWidth(viewport)/420.); NSRect prompt=NSMakeRect(NSMinX(viewport)+8*scale,NSMinY(viewport)+8*scale,400*scale,72*scale); DYDrawSoftControl(prompt,4*scale,NO,NO,NO); NSString *title=_levelFailure?:(_levelSaving?@"正在保存水平校正…":_levelPlaced?@"拖动端点修正 · 空白处重画 · Esc 收起":_levelHasFirst?@"选择参考线终点 · Esc 取消":@"点击两点或拖出参考线 · Esc 收起"); NSDictionary *attrs=@{NSForegroundColorAttributeName:NSColor.whiteColor,NSFontAttributeName:[NSFont systemFontOfSize:12*scale]}; [title drawInRect:NSMakeRect(NSMinX(prompt)+6*scale,NSMinY(prompt)+5*scale,388*scale,18*scale) withAttributes:attrs]; DYLevelTransform result(_levelAngle,_level.aspect); NSString *numbers=[NSString stringWithFormat:@"FCP 旋转 %+.2f° 缩放 %.2f%%(增加 %.2f%%)",-_levelAngle*180/M_PI,result.zoom*100,(result.zoom-1)*100]; [numbers drawInRect:NSMakeRect(NSMinX(prompt)+6*scale,NSMinY(prompt)+27*scale,388*scale,18*scale) withAttributes:attrs]; NSString *hint=_viewerControls.levelMeasureOnly?@"仅测量:数值用于原始变换;已有缩放请乘以上述比例。":@"插件已应用;改用原始变换前,请切换「仅测量」。"; [hint drawInRect:NSMakeRect(NSMinX(prompt)+6*scale,NSMinY(prompt)+49*scale,388*scale,18*scale) withAttributes:@{NSForegroundColorAttributeName:NSColor.whiteColor,NSFontAttributeName:[NSFont systemFontOfSize:10*scale]}]; if(!_levelHasFirst&&!_levelPlaced)return; NSPoint first=[self canvasDisplayPoint:_level.toOutput(_levelFirst)],last=[self canvasDisplayPoint:_level.toOutput(_levelLast)]; [NSGraphicsContext saveGraphicsState];NSRectClip(viewport); NSBezierPath *line=[NSBezierPath bezierPath];[line moveToPoint:first];[line lineToPoint:last]; for(NSValue *value in @[[NSValue valueWithPoint:first],[NSValue valueWithPoint:last]]){ NSPoint point=value.pointValue;CGFloat r=5*_uiScale; [line appendBezierPathWithOvalInRect:NSMakeRect(point.x-r,point.y-r,2*r,2*r)]; } [NSColor.blackColor setStroke];line.lineWidth=3.5*_uiScale;[line stroke]; [NSColor.systemCyanColor setStroke];line.lineWidth=1.5*_uiScale;[line stroke]; [NSGraphicsContext restoreGraphicsState]; } - (NSPoint)canvasPoint:(float)x y:(float)y parameters:(DYMaskParameters)p{ float ca=cos(p.angle),sa=sin(p.angle),aspect=p.imageAspect;float px=x*p.width*aspect,py=y*p.height;float u=p.centerX+(px*ca-py*sa)/aspect,v=p.centerY+px*sa+py*ca;return [self canvasStampSource:NSMakePoint(u,v)]; } - (void)addHandle:(NSPoint)p part:(NSInteger)part{[_handles addObject:@{@"point":[NSValue valueWithPoint:p],@"part":@(part)}];} - (NSRect)toolbarRectForItem:(NSInteger)item{ // Keep the temporary pen actions clear of the permanent tool rail. if(![_mask[@"drawing"]boolValue]||(item!=9&&item!=10))return NSZeroRect; NSRect v=NSIntersectionRect(_imageRect,NSMakeRect(0,0,_canvasWidth,_height));CGFloat scale=MAX(.01,MIN(_uiScale,MIN(v.size.width/300.,v.size.height/100.))); return NSMakeRect(NSMinX(v)+(item==9?8:76)*scale,NSMaxY(v)-61*scale,64*scale,24*scale); } - (void)clearStampCreation{ _stampHasSource=_stampDragging=NO; [_stampFailure release];_stampFailure=nil; } - (NSRect)stampControlRect:(NSInteger)index{ NSRect viewport=NSIntersectionRect(_imageRect,NSMakeRect(0,0,_canvasWidth,_height)); CGFloat scale=MIN(_uiScale,viewport.size.width/360.); return NSMakeRect(NSMinX(viewport)+(8+82*index)*scale,NSMaxY(viewport)-62*scale,78*scale,25*scale); } - (NSRect)stampTarget{ return NSMakeRect(MIN(_stampStart.x,_stampEnd.x),MIN(_stampStart.y,_stampEnd.y),fabs(_stampStart.x-_stampEnd.x),fabs(_stampStart.y-_stampEnd.y)); } - (NSPoint)canvasStampSource:(NSPoint)source{ return [self canvasDisplayPoint:_level.toOutput(source)]; } - (void)drawStampSource:(NSPoint)source{ NSPoint p=[self canvasStampSource:source]; CGFloat r=8*_uiScale; NSBezierPath *mark=[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(p.x-r,p.y-r,2*r,2*r)]; [mark moveToPoint:NSMakePoint(p.x-r,p.y)];[mark lineToPoint:NSMakePoint(p.x+r,p.y)]; [mark moveToPoint:NSMakePoint(p.x,p.y-r)];[mark lineToPoint:NSMakePoint(p.x,p.y+r)]; [NSColor.blackColor setStroke];mark.lineWidth=3.5*_uiScale;[mark stroke]; [NSColor.systemCyanColor setStroke];mark.lineWidth=1.5*_uiScale;[mark stroke]; } - (NSRect)stampActionRect:(NSInteger)index{return NSOffsetRect([self stampControlRect:index],0,-30*_uiScale);} - (void)drawStampReference { NSData *data=_mask[@"referenceShape"];if(data.length!=sizeof(DYMaskParameters))return; DYMaskParameters p;[data getBytes:&p length:sizeof(p)];NSBezierPath *path=[NSBezierPath bezierPath]; const float xy[][2]={{-.5,-.5},{.5,-.5},{.5,.5},{-.5,.5}}; for(int i=0;i<4;i++){NSPoint q=[self canvasStampSource:NSMakePoint(p.centerX+xy[i][0]*p.width,p.centerY+xy[i][1]*p.height)];if(i)[path lineToPoint:q];else[path moveToPoint:q];} [path closePath];path.lineWidth=3*_uiScale;[NSColor.blackColor setStroke];[path stroke];CGFloat dash[]={5*_uiScale,3*_uiScale};[path setLineDash:dash count:2 phase:0];path.lineWidth=1.5*_uiScale;[NSColor.systemGreenColor setStroke];[path stroke]; } - (void)drawStampControls{ NSArray *source=_mask[@"stampSource"]; if(_viewerControls.stampArmed){ NSRect cell=NSUnionRect([self stampControlRect:0],[self stampControlRect:3]); DYDrawSoftControl(cell,4,NO,NO,NO); NSString *prompt=_stampSaving?@"正在保存仿制图章…":_stampFailure?:(_stampHasSource?@"拖出要覆盖的椭圆 · Esc 取消":@"点击画面选择取样中心 · Esc 取消"); [prompt drawInRect:NSInsetRect(cell,6,4) withAttributes:@{NSForegroundColorAttributeName:NSColor.whiteColor,NSFontAttributeName:[NSFont systemFontOfSize:MAX(8.,NSHeight(cell)*.48)]}]; if(_stampHasSource)[self drawStampSource:_stampSource]; if(_stampDragging||_stampSaving||_stampFailure){ NSRect target=[self stampTarget]; NSBezierPath *outline=[NSBezierPath bezierPath]; for(int i=0;i<64;i++){ double angle=i*(2*M_PI/64); NSPoint uv=NSMakePoint(NSMidX(target)+cos(angle)*NSWidth(target)/2,NSMidY(target)+sin(angle)*NSHeight(target)/2); NSPoint p=[self canvasStampSource:uv]; if(i==0)[outline moveToPoint:p];else [outline lineToPoint:p]; } [outline closePath];outline.lineWidth=2*_uiScale;[NSColor.systemCyanColor setStroke];[outline stroke]; } }else if(source.count==4){ [self drawStampReference]; [self drawStampSource:NSMakePoint([source[0]doubleValue],[source[1]doubleValue])]; BOOL tracking=[_mask[@"tracking"]boolValue]; NSString *status=_mask[@"status"]; if(status.length){ NSRect box=NSMakeRect(NSMinX(_imageRect)+8*_uiScale,NSMinY(_imageRect)+10*_uiScale,MAX(1,MIN(NSWidth(_imageRect)-16*_uiScale,680*_uiScale)),64*_uiScale); DYDrawSoftControl(box,4,NO,NO,NO);NSMutableParagraphStyle *style=[[[NSMutableParagraphStyle alloc]init]autorelease];style.lineBreakMode=NSLineBreakByWordWrapping; [status drawInRect:NSInsetRect(box,7*_uiScale,5*_uiScale) withAttributes:@{NSForegroundColorAttributeName:[_mask[@"trackingStopped"]boolValue]?NSColor.systemOrangeColor:NSColor.whiteColor,NSFontAttributeName:[NSFont systemFontOfSize:11*_uiScale],NSParagraphStyleAttributeName:style}]; } if(!tracking){NSArray *actions=@[[_mask[@"referenceDrawing"]boolValue]?@"取消参考选择":@"选择跟踪参考",@"手工关键帧",@"最后可信帧"];for(NSInteger i=0;i<3;i++){NSRect cell=[self stampActionRect:i];DYDrawSoftControl(cell,4,NO,NO,NO);[actions[i]drawInRect:NSInsetRect(cell,4,4) withAttributes:@{NSForegroundColorAttributeName:i==2&&![_mask[@"canReturn"]boolValue]?NSColor.grayColor:NSColor.whiteColor,NSFontAttributeName:[NSFont systemFontOfSize:MAX(8.,NSHeight(cell)*.45)]}];}} NSArray *titles=tracking?@[@"停止跟踪"]:[_mask[@"referenceDrawing"]boolValue]?@[]:@[@"向后跟踪",@"双向跟踪",@"向前跟踪"]; for(NSUInteger i=0;id in devices)if(d.registryID==destination.deviceRegistryID)_device=[d retain];[devices release];[_queue release];_queue=[_device newCommandQueue];[_context release];_context=_device?[[CIContext contextWithMTLDevice:_device options:@{kCIContextWorkingColorSpace:NSNull.null,kCIContextOutputColorSpace:NSNull.null}]retain]:nil;} idtexture=[destination metalTextureForDevice:_device];if(!texture||!_queue)return;idcommands=[_queue commandBuffer];MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=texture;pass.colorAttachments[0].loadAction=MTLLoadActionClear;pass.colorAttachments[0].storeAction=MTLStoreActionStore;pass.colorAttachments[0].clearColor=MTLClearColorMake(0,0,0,0);idencoder=[commands renderCommandEncoderWithDescriptor:pass];[encoder endEncoding]; _height=destination.imagePixelBounds.top-destination.imagePixelBounds.bottom;CGFloat canvasWidth=destination.imagePixelBounds.right-destination.imagePixelBounds.left;_canvasWidth=canvasWidth; idapi=[_apiManager apiForProtocol:@protocol(FxOnScreenControlAPI_v4)];double lx=0,ly=0,ux=0,uy=0;[api convertPointFromSpace:kFxDrawingCoordinates_OBJECT fromX:0 fromY:0 toSpace:kFxDrawingCoordinates_CANVAS toX:&lx toY:&ly];[api convertPointFromSpace:kFxDrawingCoordinates_OBJECT fromX:1 fromY:1 toSpace:kFxDrawingCoordinates_CANVAS toX:&ux toY:&uy];_imageRect=NSMakeRect(lx,_height-uy,ux-lx,uy-ly);_uiScale=[api respondsToSelector:@selector(backingScaleFactor)]?MAX(1.,MIN(3.,[api backingScaleFactor])):1.; DYPlugIn *plugin=[self pluginAtTime:time];NSDictionary *mask=[plugin toolCanvasMaskAtTime:time];NSInteger route=(plugin?1:0)+(mask?2:0);if(route!=_lastRoute||_drawCount++<2){_lastRoute=route;os_log(OS_LOG_DEFAULT,"dayu_tool_osc_route plugin=%{public}d mask=%{public}d width=%{public}.2f height=%{public}.2f",plugin!=nil,mask!=nil,_imageRect.size.width,_imageRect.size.height);}[_mask release];_mask=[mask copy];[_handles removeAllObjects];[_outline release];_outline=nil; [_viewerControls setBridge:[plugin viewerParameterBridge]];[_viewerControls setViewport:_imageRect];[_viewerControls prepareWithSize:NSMakeSize(canvasWidth,_height) scale:_uiScale atTime:time]; [self updateLevelFrom:plugin];_hslSampling=[plugin canvasHSLSampling]; if(_levelMode)mask=nil; if(plugin&&canvasWidth>0&&_height>0&&canvasWidth<16384&&_height<16384&&_imageRect.size.width>0&&_imageRect.size.height>0){ NSRect region=mask||_viewerControls.stampArmed||_levelMode?NSMakeRect(0,0,canvasWidth,_height):NSIntegralRect([_viewerControls drawingBounds]); if(_hslSampling)region=NSIntegralRect(NSUnionRect(region,[self hslPickerRect])); if(NSIsEmptyRect(region)){[commands commit];[commands waitUntilCompleted];return;} NSBitmapImageRep *bitmap=[[[NSBitmapImageRep alloc]initWithBitmapDataPlanes:NULL pixelsWide:(NSInteger)NSWidth(region) pixelsHigh:(NSInteger)NSHeight(region) bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:(NSInteger)NSWidth(region)*4 bitsPerPixel:32]autorelease]; if(!bitmap){[commands commit];[commands waitUntilCompleted];return;} memset(bitmap.bitmapData,0,bitmap.bytesPerRow*bitmap.pixelsHigh); [NSGraphicsContext saveGraphicsState];[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]]; NSAffineTransform *flip=[NSAffineTransform transform];[flip translateXBy:-NSMinX(region) yBy:NSMaxY(region)];[flip scaleXBy:1 yBy:-1];[flip concat]; // Match AppKit text/image drawing to the top-down canvas CTM. [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:NSGraphicsContext.currentContext.CGContext flipped:YES]]; if(mask){BOOL blankShape=[mask[@"drawShape"]boolValue]&&![mask[@"shapeStarted"]boolValue];DYMaskParameters p;[mask[@"parameters"]getBytes:&p length:sizeof(p)];p.imageAspect=_imageRect.size.width/_imageRect.size.height;_outline=[[NSBezierPath bezierPath]retain]; if(p.kind==DYMaskBezier){NSData *data=mask[@"nodes"];auto *nodes=(const DYBezierNode*)data.bytes;NSUInteger count=data.length/sizeof(DYBezierNode);for(NSUInteger i=0;i3){NSBezierPath *line=[NSBezierPath bezierPath];[line moveToPoint:anchor];[line lineToPoint:handle];[[NSColor colorWithWhite:1 alpha:.55]setStroke];[line stroke];[self addHandle:handle part:1000+i*3+j+1];}}} NSArray *hover=mask[@"hover"];if(count&&[mask[@"drawing"]boolValue]&&hover.count==2){NSPoint target=[self canvasStampSource:NSMakePoint([hover[0]doubleValue],[hover[1]doubleValue])];[_outline curveToPoint:target controlPoint1:[self canvasPoint:nodes[count-1].outX y:nodes[count-1].outY parameters:p] controlPoint2:target];} if(count>=3&&![mask[@"drawing"]boolValue]){auto a=nodes[count-1],b=nodes[0];[_outline curveToPoint:[self canvasPoint:b.x y:b.y parameters:p] controlPoint1:[self canvasPoint:a.outX y:a.outY parameters:p] controlPoint2:[self canvasPoint:b.inX y:b.inY parameters:p]];[_outline closePath];} }else if(p.kind<2&&!blankShape){int count=p.kind==DYMaskEllipse?96:4;for(int i=0;i=3*sizeof(DYBezierNode)){const DYBezierNode *nodes=(const DYBezierNode*)data.bytes;NSPoint first=[self canvasPoint:nodes[0].x y:nodes[0].y parameters:p];if(hypot(point.x-first.x,point.y-first.y)<=10*_uiScale)return 1000;}return NSPointInRect(point,_imageRect)?1:0;} for(NSDictionary *h in _handles){NSPoint q=[h[@"point"]pointValue];if(hypot(q.x-point.x,q.y-point.y)<=9*_uiScale)return [h[@"part"]integerValue];} if(p.kind==DYMaskBezier||p.kind==DYMaskLinearGradient||[_outline containsPoint:point])return 1;return 0; } - (void)hitTestOSCAtMousePositionX:(double)x mousePositionY:(double)y activePart:(NSInteger*)part atTime:(CMTime)time{@synchronized(self){DYPlugIn*plugin=[self pluginAtTime:time];[_viewerControls setBridge:[plugin viewerParameterBridge]];[_viewerControls setViewport:_imageRect];[_viewerControls prepareWithSize:NSMakeSize(_canvasWidth,_height) scale:_uiScale atTime:time];NSDictionary *fresh=[plugin toolCanvasMaskAtTime:time];[_mask release];_mask=[fresh copy];[self updateLevelFrom:plugin];_hslSampling=[plugin canvasHSLSampling];NSInteger hit=[self partAtPoint:NSMakePoint(x,_height-y)];if(part)*part=hit;if(_hitDiagnostics++<16)os_log(OS_LOG_DEFAULT,"dayu_tool_osc_hit x=%{public}.2f y=%{public}.2f height=%{public}.2f rect=%{public}.2f,%{public}.2f,%{public}.2f,%{public}.2f mask=%{public}d hit=%{public}ld",x,y,_height,_imageRect.origin.x,_imageRect.origin.y,_imageRect.size.width,_imageRect.size.height,_mask!=nil,(long)hit);}} - (BOOL)event:(NSEventType)type x:(double)x y:(double)y part:(NSInteger)part modifiers:(FxModifierKeys)modifiers key:(unichar)key time:(CMTime)time {@synchronized(self){ DYPlugIn *plugin=[self pluginAtTime:time];if(_eventDiagnostics++<12)os_log(OS_LOG_DEFAULT,"dayu_tool_osc_event type=%{public}ld part=%{public}ld x=%{public}.2f y=%{public}.2f plugin=%{public}d",(long)type,(long)part,x,y,plugin!=nil);[_viewerControls setBridge:[plugin viewerParameterBridge]];[_viewerControls setViewport:_imageRect];[_viewerControls prepareWithSize:NSMakeSize(_canvasWidth,_height) scale:_uiScale atTime:time];NSPoint canvasPoint=NSMakePoint(x,_height-y); if(_maskCapturing&&plugin!=_maskCaptureOwner){_maskCapturing=NO;_maskCaptureOwner=nil;return NO;} [self updateLevelFrom:plugin];_hslSampling=[plugin canvasHSLSampling]; if(_hslSampling){ if(type==NSEventTypeKeyDown&&key==27){[plugin finishCanvasHSLWithColor:nil];_hslSampling=NO;return YES;} if(type==NSEventTypeLeftMouseDown&&part==10030){[plugin selectCanvasHSLAtPoint:[self clampedDisplayUV:canvasPoint] atTime:time];_hslSampling=[plugin canvasHSLSampling];return YES;} if(type==NSEventTypeLeftMouseUp&&part==10030)return YES; } if(_stampSaving)return YES; if([self handleLevelEvent:type point:canvasPoint part:part key:key time:time plugin:plugin])return YES; if(!_viewerControls.stampArmed)[self clearStampCreation]; if(type==NSEventTypeKeyDown&&key==27&&_viewerControls.stampArmed){ _viewerControls.stampArmed=NO;[self clearStampCreation];return YES; } if(type==NSEventTypeLeftMouseDown&&part>=10018&&part<=10020){ [plugin cloneStampCommand:@[@"reference",@"manual",@"return"][part-10018] mask:_mask[@"id"] atTime:time];return YES; } if(type==NSEventTypeLeftMouseDown&&part>=10011&&part<=10013){ NSInteger direction=[_mask[@"tracking"]boolValue]?9:part-10012; [plugin trackCloneStamp:_mask[@"id"] direction:direction];return YES; } if(plugin&&_viewerControls.stampArmed&&NSWidth(_imageRect)>0&&NSHeight(_imageRect)>0){ NSPoint uv=_level.toSource([self clampedDisplayUV:canvasPoint]); uv=NSMakePoint(std::clamp(uv.x,0.,1.),std::clamp(uv.y,0.,1.)); if(type==NSEventTypeLeftMouseDown&&part==10014){ [_stampFailure release];_stampFailure=nil; if(!_stampHasSource){_stampSource=uv;_stampHasSource=YES;} else {_stampStart=_stampEnd=uv;_stampDragging=YES;} return YES; } if(_stampDragging&&(type==NSEventTypeLeftMouseDragged||type==NSEventTypeLeftMouseUp)){ _stampEnd=uv; if(type==NSEventTypeLeftMouseUp){ NSRect target=[self stampTarget];_stampDragging=NO; if(NSWidth(target)>=.001&&NSHeight(target)>=.001&&NSWidth(target)*NSWidth(_imageRect)>=3*_uiScale&&NSHeight(target)*NSHeight(_imageRect)>=3*_uiScale){ _stampSaving=YES; DYViewerParameterBridge *bridge=_viewerControls.bridge; [plugin addCloneStampFrom:_stampSource target:target atTime:time completion:^(NSString *failure){ @synchronized(self){ self->_stampSaving=NO; if(self->_viewerControls.bridge!=bridge||!self->_viewerControls.stampArmed){[self clearStampCreation];return;} self->_stampNeedsRedraw=YES; if(failure){ [self->_stampFailure release];self->_stampFailure=[failure copy]; }else{ self->_viewerControls.stampArmed=NO; [self clearStampCreation]; } } }]; } } return YES; } } BOOL ownedMask=_maskCapturing&&(type==NSEventTypeLeftMouseDragged||type==NSEventTypeLeftMouseUp); if(type==NSEventTypeKeyDown&&key==27&&[_viewerControls capturing])return [_viewerControls finishCapture]; BOOL penAction=type==NSEventTypeLeftMouseDown&&(part==10009||part==10010); if(!ownedMask&&!penAction&&type!=NSEventTypeKeyDown&&[_viewerControls event:type point:canvasPoint atTime:time]){ [self updateLevelFrom:plugin];_hslSampling=[plugin canvasHSLSampling]; if(_viewerControls.levelResetRequested){_viewerControls.levelResetRequested=NO;[self commitLevelState:@{} plugin:plugin];} else if(_viewerControls.levelMeasureRequested){_viewerControls.levelMeasureRequested=NO;NSMutableDictionary *state=[NSMutableDictionary dictionaryWithDictionary:_levelState?:@{}];state[@"levelMeasureOnly"]=@(![state[@"levelMeasureOnly"]boolValue]);[self commitLevelState:state plugin:plugin];} else if(_viewerControls.levelDirectionRequested){_viewerControls.levelDirectionRequested=NO;if(_levelPlaced)[self commitLevelReference:plugin];} return YES; } if(_levelMode)return NO; if(!plugin||![plugin toolCanvasVisible]||_imageRect.size.width<=0||_imageRect.size.height<=0){_maskCapturing=NO;return NO;} NSPoint point=_level.toSource([self displayUV:canvasPoint]); if(type==NSEventTypeLeftMouseDown){_maskCapturing=part>0&&part<10000;_maskCaptureOwner=_maskCapturing?plugin:nil;} [plugin toolCanvasEvent:type point:point part:part modifiers:modifiers key:key time:time];if(type==NSEventTypeLeftMouseUp||(type==NSEventTypeKeyDown&&key==27)){_maskCapturing=NO;_maskCaptureOwner=nil;}return YES; }} - (void)mouseDownAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{BOOL result=[self event:NSEventTypeLeftMouseDown x:x y:y part:part modifiers:m key:0 time:t];if(update)*update=result;} - (void)mouseDraggedAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{BOOL result=[self event:NSEventTypeLeftMouseDragged x:x y:y part:part modifiers:m key:0 time:t];if(update)*update=result;} - (void)mouseUpAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{BOOL result=[self event:NSEventTypeLeftMouseUp x:x y:y part:part modifiers:m key:0 time:t];if(update)*update=result;} - (void)keyDownAtPositionX:(double)x positionY:(double)y keyPressed:(unsigned short)key modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update didHandle:(BOOL*)handled atTime:(CMTime)t{BOOL result=(key==27||key==13||key==10||key==3||key==8||key==127)&&[self event:NSEventTypeKeyDown x:x y:y part:1 modifiers:m key:key time:t];if(update)*update=result;if(handled)*handled=result;} - (void)mouseMovedAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{@synchronized(self){ DYPlugIn*plugin=[self pluginAtTime:t];[_viewerControls setBridge:[plugin viewerParameterBridge]];[_viewerControls setViewport:_imageRect];[_viewerControls prepareWithSize:NSMakeSize(_canvasWidth,_height) scale:_uiScale atTime:t];[self updateLevelFrom:plugin];_hslSampling=[plugin canvasHSLSampling];NSPoint point=NSMakePoint(x,_height-y);NSInteger viewerHit=[_viewerControls partAtPoint:point];BOOL redraw=[_viewerControls mouseMoved:point];NSDictionary *mask=[plugin toolCanvasMaskAtTime:t];BOOL drawing=[mask[@"drawing"]boolValue]||[mask[@"drawShape"]boolValue];NSCursor *cursor=[_viewerControls headerAtPoint:point]?([_viewerControls capturing]?NSCursor.closedHandCursor:NSCursor.openHandCursor):viewerHit?NSCursor.pointingHandCursor:(part==10014||part==10015||part==10030)?NSCursor.crosshairCursor:part>=10000?NSCursor.pointingHandCursor:(drawing||part>=1000)?NSCursor.crosshairCursor:part?NSCursor.openHandCursor:NSCursor.arrowCursor;[[_apiManager apiForProtocol:@protocol(FxOnScreenControlAPI_v4)]setCursor:cursor];if(_levelMode&&_levelHasFirst&&!_levelDown&&!_levelSaving&&!viewerHit&&part==10015){ _levelLast=_level.toSource([self clampedDisplayUV:point]);redraw=YES; }else if(!_levelMode&&[mask[@"drawing"]boolValue]&&!viewerHit)[self event:NSEventTypeMouseMoved x:x y:y part:part modifiers:m key:0 time:t]; if(update)*update=_hslSampling||redraw||(!_levelMode&&[mask[@"drawing"]boolValue])||_stampNeedsRedraw;_stampNeedsRedraw=NO; }} - (void)mouseEnteredAtPositionX:(double)x positionY:(double)y modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{[self mouseMovedAtPositionX:x positionY:y activePart:0 modifiers:m forceUpdate:update atTime:t];} - (void)mouseExitedAtPositionX:(double)x positionY:(double)y modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{@synchronized(self){BOOL changed=[_viewerControls mouseExited];if(update)*update=changed;}} - (void)keyUpAtPositionX:(double)x positionY:(double)y keyPressed:(unsigned short)key modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update didHandle:(BOOL*)handled atTime:(CMTime)t{if(update)*update=NO;if(handled)*handled=NO;} @end