11#import <QuartzCore/QuartzCore.h>
13#if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
14#import <Metal/Metal.h>
19#import "IGraphicsMac_view.h"
25using namespace igraphics;
27static int MacKeyCodeToVK(
int code)
31 case 51:
return kVK_BACK;
32 case 65:
return kVK_DECIMAL;
33 case 67:
return kVK_MULTIPLY;
34 case 69:
return kVK_ADD;
35 case 71:
return kVK_NUMLOCK;
36 case 75:
return kVK_DIVIDE;
37 case 76:
return kVK_RETURN | 0x8000;
38 case 78:
return kVK_SUBTRACT;
39 case 81:
return kVK_SEPARATOR;
40 case 82:
return kVK_NUMPAD0;
41 case 83:
return kVK_NUMPAD1;
42 case 84:
return kVK_NUMPAD2;
43 case 85:
return kVK_NUMPAD3;
44 case 86:
return kVK_NUMPAD4;
45 case 87:
return kVK_NUMPAD5;
46 case 88:
return kVK_NUMPAD6;
47 case 89:
return kVK_NUMPAD7;
48 case 91:
return kVK_NUMPAD8;
49 case 92:
return kVK_NUMPAD9;
50 case 96:
return kVK_F5;
51 case 97:
return kVK_F6;
52 case 98:
return kVK_F7;
53 case 99:
return kVK_F3;
54 case 100:
return kVK_F8;
55 case 101:
return kVK_F9;
56 case 109:
return kVK_F10;
57 case 103:
return kVK_F11;
58 case 111:
return kVK_F12;
59 case 114:
return kVK_INSERT;
60 case 115:
return kVK_HOME;
61 case 117:
return kVK_DELETE;
62 case 116:
return kVK_PRIOR;
63 case 118:
return kVK_F4;
64 case 119:
return kVK_END;
65 case 120:
return kVK_F2;
66 case 121:
return kVK_NEXT;
67 case 122:
return kVK_F1;
68 case 123:
return kVK_LEFT;
69 case 124:
return kVK_RIGHT;
70 case 125:
return kVK_DOWN;
71 case 126:
return kVK_UP;
72 case 0x69:
return kVK_F13;
73 case 0x6B:
return kVK_F14;
74 case 0x71:
return kVK_F15;
75 case 0x6A:
return kVK_F16;
80static int MacKeyEventToVK(NSEvent* pEvent,
int& flag)
84 const NSInteger mod = [pEvent modifierFlags];
86 if (mod & NSShiftKeyMask) flag |= kFSHIFT;
87 if (mod & NSCommandKeyMask) flag |= kFCONTROL;
88 if (mod & NSAlternateKeyMask) flag |= kFALT;
89 if ((mod & NSControlKeyMask) ) flag |= kFLWIN;
91 int rawcode = [pEvent keyCode];
93 code = MacKeyCodeToVK(rawcode);
98 if (!str || ![str length]) str = [pEvent charactersIgnoringModifiers];
100 if (!str || ![str length])
104 code = 1024 + rawcode;
110 code = [str characterAtIndex:0];
111 if (code >= NSF1FunctionKey && code <= NSF24FunctionKey)
114 code += kVK_F1 - NSF1FunctionKey;
118 if (code >=
'a' && code <=
'z') code +=
'A'-
'a';
119 if (code == 25 && (flag & kFSHIFT)) code = kVK_TAB;
120 if (isalnum(code) || code==
' ' || code ==
'\r' || code ==
'\n' || code ==27 || code == kVK_TAB) flag |= kFVIRTKEY;
127 if (code == 8) code =
'\b';
130 if (!(flag & kFVIRTKEY)) flag &= ~kFSHIFT;
135#ifndef IGRAPHICS_MENU_RCVR
136#warning The iPlug2 Obj-C namespace is not customized. Did you forget to include IPlugOBJCPrefix.pch?
139@implementation IGRAPHICS_MENU_RCVR
141- (NSMenuItem*) menuItem
146- (void) onMenuSelection:(
id) sender
153@implementation IGRAPHICS_MENU
155- (id) initWithIPopupMenuAndReceiver: (
IPopupMenu*) pMenu : (NSView*) pView
157 [
self initWithTitle: @""];
159 NSMenuItem* nsMenuItem = nil;
160 NSMutableString* nsMenuItemTitle = nil;
162 [
self setAutoenablesItems:NO];
164 int numItems = pMenu->NItems();
166 for (
int i = 0; i < numItems; ++i)
170 nsMenuItemTitle = [[[NSMutableString alloc] initWithUTF8String:pMenuItem->GetText()] autorelease];
172 if (pMenu->GetPrefix())
174 NSString* prefixString = 0;
176 switch (pMenu->GetPrefix())
178 case 0: prefixString = [NSString stringWithUTF8String:
""]; break;
179 case 1: prefixString = [NSString stringWithFormat:
@"%1d: ", i+1]; break;
180 case 2: prefixString = [NSString stringWithFormat:
@"%02d: ", i+1]; break;
181 case 3: prefixString = [NSString stringWithFormat:
@"%03d: ", i+1]; break;
184 [nsMenuItemTitle insertString:prefixString atIndex:0];
187 if (pMenuItem->GetIsSeparator())
189 [self addItem:[NSMenuItem separatorItem]];
191 else if (pMenuItem->GetSubmenu())
193 nsMenuItem = [self addItemWithTitle:nsMenuItemTitle action:nil keyEquivalent:
@""];
194 NSMenu* subMenu = [[IGRAPHICS_MENU alloc] initWithIPopupMenuAndReceiver:pMenuItem->GetSubmenu() :pView];
195 [self setSubmenu: subMenu forItem:nsMenuItem];
200 nsMenuItem = [self addItemWithTitle:nsMenuItemTitle action:@selector(onMenuSelection:) keyEquivalent:
@""];
202 [nsMenuItem setTarget:pView];
205 if (nsMenuItem && !pMenuItem->GetIsSeparator())
207 [nsMenuItem setIndentationLevel:pMenuItem->GetIsTitle() ? 1 : 0 ];
208 [nsMenuItem setEnabled:pMenuItem->GetEnabled() ? YES : NO];
209 [nsMenuItem setState:pMenuItem->GetChecked() ? NSOnState : NSOffState];
225@implementation IGRAPHICS_TEXTFIELD
227- (bool) becomeFirstResponder;
229 bool success = [
super becomeFirstResponder];
232 NSTextView *textField = (NSTextView*) [self currentEditor];
233 if( [textField respondsToSelector:
@selector(setInsertionPointColor:)] )
234 [textField setInsertionPointColor: [
self textColor]];
255@implementation IGRAPHICS_TEXTFIELDCELL
257- (NSRect) drawingRectForBounds: (NSRect) inRect
260 NSRect outRect = [
super drawingRectForBounds:inRect];
267 if (mIsEditingOrSelecting == NO)
270 NSSize textSize = [
self cellSize];
273 float heightDelta = outRect.size.height - textSize.height;
275 outRect.size.height -= heightDelta;
276 outRect.origin.y += (heightDelta / 2);
282- (void) selectWithFrame: (NSRect) aRect inView: (NSView*) controlView editor: (NSText*) textObj delegate: (
id) anObject start: (NSInteger) selStart length: (NSInteger) selLength
284 aRect = [
self drawingRectForBounds:aRect];
285 mIsEditingOrSelecting = YES;
286 [
super selectWithFrame:aRect inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
287 mIsEditingOrSelecting = NO;
290- (void) editWithFrame: (NSRect) aRect inView: (NSView*) controlView editor: (NSText*) textObj delegate: (
id) anObject event: (NSEvent*) theEvent
292 aRect = [
self drawingRectForBounds:aRect];
293 mIsEditingOrSelecting = YES;
294 [
super editWithFrame:aRect inView:controlView editor:textObj delegate:anObject event:theEvent];
295 mIsEditingOrSelecting = NO;
300@implementation IGRAPHICS_FORMATTER
304 [filterCharacterSet release];
308- (BOOL) isPartialStringValid:(NSString*) partialString newEditingString:(NSString**) newString errorDescription:(NSString**) error
310 if (filterCharacterSet != nil)
313 int len = (int) [partialString length];
315 for (i = 0; i < len; i++)
317 if (![filterCharacterSet characterIsMember:[partialString characterAtIndex:i]])
326 if ([partialString length] > maxLength)
332 if (maxValue && [partialString intValue] > maxValue)
340- (void) setAcceptableCharacterSet: (NSCharacterSet*) inCharacterSet
342 [inCharacterSet retain];
343 [filterCharacterSet release];
344 filterCharacterSet = inCharacterSet;
347- (void) setMaximumLength: (
int) inLength
349 maxLength = inLength;
352- (void) setMaximumValue: (
int) inValue
357- (NSString*) stringForObjectValue: (
id) anObject
359 if ([anObject isKindOfClass:[NSString
class]])
367- (BOOL) getObjectValue: (
id*) anObject forString:(NSString*) string errorDescription: (NSString **) error
369 if (anObject &&
string)
371 *anObject = [NSString stringWithString:string];
380extern StaticStorage<CoreTextFontDescriptor> sFontDescriptorCache;
382#ifdef IGRAPHICS_ACCESSKIT
383IGraphicsAccessibilityMac::IGraphicsAccessibilityMac(
IGraphics& graphics, NSView* pView)
384: IGraphicsAccessibility(graphics)
386 mAdapter = accesskit_macos_adapter_new((
void*) pView,
false, ActionHandler,
this);
389IGraphicsAccessibilityMac::~IGraphicsAccessibilityMac()
391 accesskit_macos_adapter_free(mAdapter);
394void IGraphicsAccessibilityMac::UpdateIfActive(accesskit_tree_update_factory factory,
void* pUserData)
396 if (accesskit_macos_queued_events* pEvents = accesskit_macos_adapter_update_if_active(mAdapter, factory, pUserData))
397 accesskit_macos_queued_events_raise(pEvents);
400void IGraphicsAccessibilityMac::SetViewFocused(
bool focused)
402 if (focused == mViewFocused)
405 mViewFocused = focused;
407 if (accesskit_macos_queued_events* pEvents = accesskit_macos_adapter_update_view_focus_state(mAdapter, focused))
408 accesskit_macos_queued_events_raise(pEvents);
411NSArray* IGraphicsAccessibilityMac::GetChildren()
413 return (NSArray*) accesskit_macos_adapter_view_children(mAdapter, ActivationHandler,
this);
416id IGraphicsAccessibilityMac::GetFocus()
418 return (
id) accesskit_macos_adapter_focus(mAdapter, ActivationHandler,
this);
421id IGraphicsAccessibilityMac::HitTest(NSPoint point)
423 return (
id) accesskit_macos_adapter_hit_test(mAdapter, point.x, point.y, ActivationHandler,
this);
427@implementation IGRAPHICS_VIEW
429- (CALayer *)makeBackingLayer
434#if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
435 return [[[CAMetalLayer alloc] init] autorelease];
437 return [[[CALayer alloc] init] autorelease];
445 mGraphics = pGraphics;
446 NSRect r = NSMakeRect(0.f, 0.f, (
float) pGraphics->WindowWidth(), (
float) pGraphics->WindowHeight());
447 self = [
super initWithFrame:r];
449 mMouseOutDuringDrag =
false;
451 self.layer.frame = r;
452 self.wantsLayer = YES;
453 self.layer.opaque = YES;
454 self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawDuringViewResize;
455 [
self registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, nil]];
457 #if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
458 CAMetalLayer* mtlLayer = (CAMetalLayer*) self.layer;
459 [mtlLayer setPixelFormat:MTLPixelFormatBGRA8Unorm];
460 mtlLayer.device = [MTLCreateSystemDefaultDevice() autorelease];
461 mtlLayer.framebufferOnly = YES;
462 #elif defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
463 NSOpenGLPixelFormatAttribute profile = NSOpenGLProfileVersionLegacy;
464 #if defined IGRAPHICS_GL3
465 profile = (NSOpenGLPixelFormatAttribute)NSOpenGLProfileVersion3_2Core;
467 const NSOpenGLPixelFormatAttribute attrs[] = {
468 NSOpenGLPFAAccelerated,
469 NSOpenGLPFANoRecovery,
470 NSOpenGLPFADoubleBuffer,
471 NSOpenGLPFAAlphaSize, 8,
472 NSOpenGLPFAColorSize, 24,
473 NSOpenGLPFADepthSize, 0,
474 NSOpenGLPFAStencilSize, 8,
475 NSOpenGLPFAOpenGLProfile, profile,
476 (NSOpenGLPixelFormatAttribute) 0
478 NSOpenGLPixelFormat* pPixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
479 NSOpenGLContext* pGLContext = [[NSOpenGLContext alloc] initWithFormat:pPixelFormat shareContext:nil];
485 self.pixelFormat = pPixelFormat;
486 self.openGLContext = pGLContext;
487 self.wantsBestResolutionOpenGLSurface = YES;
490 #if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
491 EGLDisplay display = eglGetPlatformDisplay(EGLenum(EGL_PLATFORM_ANGLE_ANGLE), 0, 0);
494 DBGMSG(
"eglGetPlatformDisplay() returned error %i", eglGetError());
497 if (eglInitialize(display, nil, nil) == 0) {
498 DBGMSG(
"eglInitialize() returned error %i", eglGetError());
501 const EGLint configAttribs[9] = {
507 EGLint numConfigs = 0;
508 EGLConfig configs[1];
510 if (eglChooseConfig(display, configAttribs, configs, 1, &numConfigs) == 0) {
511 DBGMSG(
"eglChooseConfig() returned error %i", eglGetError());
515 DBGMSG(
"Empty config returned in eglChooseConfig()");
518 #if defined IGRAPHICS_GLES2
519 const EGLint contextAttribs [5] = {
520 EGL_CONTEXT_MAJOR_VERSION, 2,
521 EGL_CONTEXT_MINOR_VERSION, 0,
524 #elif defined IGRAPHICS_GLES3
525 const EGLint contextAttribs [5] = {
526 EGL_CONTEXT_MAJOR_VERSION, 3,
527 EGL_CONTEXT_MINOR_VERSION, 0,
532 EGLContext context = eglCreateContext(display, configs[0],
nullptr, contextAttribs);
535 DBGMSG(
"eglCreateContext() returned error %d", eglGetError());
538 EGLSurface surface = eglCreateWindowSurface(display, configs[0], (__bridge EGLNativeWindowType) [self layer],
nullptr);
541 DBGMSG(
"eglCreateWindowSurface() returned error %d", eglGetError());
544 mEGLSurface = surface;
545 mEGLDisplay = display;
546 mEGLContext = context;
550 #if !defined IGRAPHICS_GL2 && !defined IGRAPHICS_GL3
557#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
558- (void) prepareOpenGL
560 [
super prepareOpenGL];
562 [
self activateGLContext];
566 [[
self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
572static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink,
const CVTimeStamp* now,
const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut,
void* displayLinkContext)
574 dispatch_source_t source = (dispatch_source_t) displayLinkContext;
575 dispatch_source_merge_data(source, 1);
577 return kCVReturnSuccess;
580- (void) onTimer: (NSTimer*) pTimer
587#ifdef IGRAPHICS_CVDISPLAYLINK
588 mDisplaySource = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
589 dispatch_source_set_event_handler(mDisplaySource, ^(){
592 dispatch_resume(mDisplaySource);
596 cvReturn = CVDisplayLinkCreateWithActiveCGDisplays(&mDisplayLink);
598 assert(cvReturn == kCVReturnSuccess);
600 cvReturn = CVDisplayLinkSetOutputCallback(mDisplayLink, &displayLinkCallback, (
void*) mDisplaySource);
601 assert(cvReturn == kCVReturnSuccess);
603 #if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
604 CGLContextObj cglContext = [[
self openGLContext] CGLContextObj];
605 CGLPixelFormatObj cglPixelFormat = [[
self pixelFormat] CGLPixelFormatObj];
606 CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(mDisplayLink, cglContext, cglPixelFormat);
609 CGDirectDisplayID viewDisplayID =
610 (CGDirectDisplayID) [self.window.screen.deviceDescription[
@"NSScreenNumber"] unsignedIntegerValue];;
612 cvReturn = CVDisplayLinkSetCurrentCGDisplay(mDisplayLink, viewDisplayID);
614 assert(cvReturn == kCVReturnSuccess);
616 CVDisplayLinkStart(mDisplayLink);
618 double sec = 1.0 / (double) mGraphics->FPS();
619 mTimer = [NSTimer timerWithTimeInterval:sec target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
620 [[NSRunLoop currentRunLoop] addTimer: mTimer forMode: (NSString*) kCFRunLoopCommonModes];
626#ifdef IGRAPHICS_CVDISPLAYLINK
627 CVDisplayLinkStop(mDisplayLink);
628 dispatch_source_cancel(mDisplaySource);
629 CVDisplayLinkRelease(mDisplayLink);
639 if([NSColorPanel sharedColorPanelExists])
640 [[NSColorPanel sharedColorPanel] close];
642 mColorPickerFunc =
nullptr;
643 [mMoveCursor release];
644 [mTrackingArea release];
645 [[NSNotificationCenter defaultCenter] removeObserver:self];
652 return mGraphics ? YES : NO;
660- (void) viewDidChangeEffectiveAppearance
662 if (@available(macOS 10.14, *)) {
663 BOOL isDarkMode = [[[
self effectiveAppearance] name] isEqualToString: (NSAppearanceNameDarkAqua)];
664 mGraphics->OnAppearanceChanged(isDarkMode ? EUIAppearance::Dark : EUIAppearance::Light);
668- (BOOL) acceptsFirstResponder
673#ifdef IGRAPHICS_ACCESSKIT
674- (void) updateAccessibilityFocus
678 NSWindow* pWindow = [
self window];
679 mAccessibility->SetViewFocused(pWindow && [pWindow isKeyWindow] && [pWindow firstResponder] == self);
683- (BOOL) becomeFirstResponder
685 BOOL result = [
super becomeFirstResponder];
688 dispatch_async(dispatch_get_main_queue(), ^{ [
self updateAccessibilityFocus]; });
693- (BOOL) resignFirstResponder
695 BOOL result = [
super resignFirstResponder];
696 dispatch_async(dispatch_get_main_queue(), ^{ [
self updateAccessibilityFocus]; });
700- (void) windowKeyStateChanged: (NSNotification*) pNotification
702 [
self updateAccessibilityFocus];
705- (NSArray*) accessibilityChildren
707 NSArray* pChildren = [
super accessibilityChildren];
711 NSArray* pControlChildren = mAccessibility->GetChildren();
714 if (pControlChildren)
715 pChildren = pChildren ? [pControlChildren arrayByAddingObjectsFromArray: pChildren] : pControlChildren;
721- (id) accessibilityFocusedUIElement
723 if (mAccessibility && [[self window] firstResponder] == self)
725 id pElement = mAccessibility->GetFocus();
731 return [
super accessibilityFocusedUIElement];
734- (id) accessibilityHitTest: (NSPoint) point
737 for (NSView* pSubview in [self subviews])
739 if (![pSubview isHidden] && NSPointInRect([self convertPoint: [[self window] convertPointFromScreen: point] fromView: nil], [pSubview frame]))
740 return [
super accessibilityHitTest: point];
745 id pElement = mAccessibility->HitTest(point);
751 return [
super accessibilityHitTest: point];
755- (BOOL) acceptsFirstMouse: (NSEvent*) pEvent
760- (void) viewDidMoveToWindow
762 NSWindow* pWindow = [
self window];
764#ifdef IGRAPHICS_ACCESSKIT
765 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
766 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
770 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowKeyStateChanged:) name:NSWindowDidBecomeKeyNotification object:pWindow];
771 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowKeyStateChanged:) name:NSWindowDidResignKeyNotification object:pWindow];
774 dispatch_async(dispatch_get_main_queue(), ^{ [
self updateAccessibilityFocus]; });
779 [pWindow makeFirstResponder: self];
780 [pWindow setAcceptsMouseMovedEvents: YES];
782 CGFloat newScale = [pWindow backingScaleFactor];
785 mGraphics->SetScreenScale(newScale);
787 #if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
788 [[NSNotificationCenter defaultCenter] addObserver:self
789 selector:@selector(frameDidChange:)
790 name:NSViewFrameDidChangeNotification
794 #if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
795 [[NSNotificationCenter defaultCenter] addObserver:self
796 selector:@selector(frameDidChange:)
797 name:NSViewGlobalFrameDidChangeNotification
815- (void) viewDidChangeBackingProperties:(NSNotification*) pNotification
817 NSWindow* pWindow = [
self window];
822 CGFloat newScale = [pWindow backingScaleFactor];
824 mGraphics->SetPlatformContext(
nullptr);
826 if (newScale != mGraphics->GetScreenScale())
827 mGraphics->SetScreenScale(newScale);
829 self.layer.contentsScale = [[
self window] backingScaleFactor];
831#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
832 self.layer.contentsScale = 1./newScale;
833#elif defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
834 [(CAMetalLayer*)[
self layer] setDrawableSize:CGSizeMake(self.frame.size.width * newScale,
835 self.frame.size.height * newScale)];
839- (CGContextRef) getCGContextRef
841 CGContextRef pCGC = [NSGraphicsContext currentContext].CGContext;
842 return [NSGraphicsContext graphicsContextWithCGContext: pCGC flipped: YES].CGContext;
846- (void) drawRect: (NSRect) bounds
848 #if defined IGRAPHICS_CPU
851 mGraphics->SetPlatformContext([self getCGContextRef]);
853 if (mGraphics->GetPlatformContext())
857 [
self getRectsBeingDrawn:&rects count:&numRects];
860 for (
int i = 0; i < numRects; i++)
861 drawRects.Add(ToIRECT(mGraphics, &rects[i]));
863 mGraphics->Draw(drawRects);
873 if (mGraphics->IsDirty(mDirtyRects))
875 mGraphics->SetAllControlsClean();
877 #if defined IGRAPHICS_CPU
878 for (int i = 0; i < mDirtyRects.Size(); i++)
879 [self setNeedsDisplayInRect:ToNSRect(mGraphics, mDirtyRects.Get(i))];
881 IGraphics::ScopedGLContext scopedGLCtx {mGraphics};
883 mGraphics->Draw(mDirtyRects);
889- (void) getMouseXY: (NSEvent*) pEvent : (
float&) x : (
float&) y
893 NSPoint pt = [
self convertPoint:[pEvent locationInWindow] fromView:nil];
894 x = pt.x / mGraphics->GetDrawScale();
895 y = pt.y / mGraphics->GetDrawScale();
897 mGraphics->DoCursorLock(x, y, mPrevX, mPrevY);
898 mGraphics->SetTabletInput(pEvent.subtype == NSTabletPointEventSubtype);
905 [
self getMouseXY:pEvent : info.x : info.y];
906 int mods = (int) [pEvent modifierFlags];
907 info.ms =
IMouseMod(
true, (mods & NSCommandKeyMask), (mods & NSShiftKeyMask), (mods & NSControlKeyMask), (mods & NSAlternateKeyMask));
912- (
IMouseInfo) getMouseRight: (NSEvent*) pEvent
915 [
self getMouseXY:pEvent : info.x : info.y];
916 int mods = (int) [pEvent modifierFlags];
917 info.ms =
IMouseMod(
false,
true, (mods & NSShiftKeyMask), (mods & NSControlKeyMask), (mods & NSAlternateKeyMask));
922- (void) updateTrackingAreas
924 [
super updateTrackingAreas];
926 if (mTrackingArea != nil)
928 [
self removeTrackingArea:mTrackingArea];
929 [mTrackingArea release];
932 int opts = (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingEnabledDuringMouseDrag);
933 mTrackingArea = [ [NSTrackingArea alloc] initWithRect:[
self bounds] options:opts owner:self userInfo:nil];
934 [
self addTrackingArea:mTrackingArea];
937- (void) mouseEntered: (NSEvent*) pEvent
939 mMouseOutDuringDrag =
false;
943 mGraphics->OnSetCursor();
947- (void) mouseExited: (NSEvent*) pEvent
951 if (!mGraphics->ControlIsCaptured())
953 mGraphics->OnMouseOut();
957 mMouseOutDuringDrag =
true;
962- (void) mouseDown: (NSEvent*) pEvent
967 if (([pEvent clickCount] - 1) % 2)
969 mGraphics->OnMouseDblClick(info.x, info.y, info.ms);
973 std::vector<IMouseInfo> list {info};
974 mGraphics->OnMouseDown(list);
979- (void) mouseUp: (NSEvent*) pEvent
984 std::vector<IMouseInfo> list {info};
985 mGraphics->OnMouseUp(list);
987 if (mMouseOutDuringDrag)
989 mGraphics->OnMouseOut();
990 mMouseOutDuringDrag =
false;
995- (void) mouseDragged: (NSEvent*) pEvent
998 float prevX = mPrevX;
999 float prevY = mPrevY;
1000 IMouseInfo info = [
self getMouseLeft:pEvent];
1001 if (mGraphics && !mGraphics->IsInPlatformTextEntry())
1003 info.dX = info.x - prevX;
1004 info.dY = info.y - prevY;
1005 std::vector<IMouseInfo> list {info};
1006 mGraphics->OnMouseDrag(list);
1010- (void) rightMouseDown: (NSEvent*) pEvent
1012 IMouseInfo info = [
self getMouseRight:pEvent];
1015 if (([pEvent clickCount] - 1) % 2)
1017 mGraphics->OnMouseDblClick(info.x, info.y, info.ms);
1021 std::vector<IMouseInfo> list {info};
1022 mGraphics->OnMouseDown(list);
1027- (void) rightMouseUp: (NSEvent*) pEvent
1029 IMouseInfo info = [
self getMouseRight:pEvent];
1032 std::vector<IMouseInfo> list {info};
1033 mGraphics->OnMouseUp(list);
1037- (void) rightMouseDragged: (NSEvent*) pEvent
1040 float prevX = mPrevX;
1041 float prevY = mPrevY;
1042 IMouseInfo info = [
self getMouseRight:pEvent];
1044 if (mGraphics && !mTextFieldView)
1046 info.dX = info.x - prevX;
1047 info.dY = info.y - prevY;
1048 std::vector<IMouseInfo> list {info};
1049 mGraphics->OnMouseDrag(list);
1053- (void) mouseMoved: (NSEvent*) pEvent
1055 IMouseInfo info = [
self getMouseLeft:pEvent];
1057 mGraphics->OnMouseOver(info.x, info.y, info.ms);
1060- (void) keyDown: (NSEvent*) pEvent
1063 int code = MacKeyEventToVK(pEvent, flag);
1064 NSString *s = [pEvent charactersIgnoringModifiers];
1068 if ([s length] == 1)
1069 c = [s characterAtIndex:0];
1071 if(!
static_cast<bool>(flag & kFVIRTKEY))
1077 WDL_MakeUTFChar(utf8, c, 4);
1079 IKeyPress keyPress {utf8, code,
static_cast<bool>(flag & kFSHIFT),
1080 static_cast<bool>(flag & kFCONTROL),
1081 static_cast<bool>(flag & kFALT)};
1083 bool handle = mGraphics->OnKeyDown(mPrevX, mPrevY, keyPress);
1087 [[
self nextResponder] keyDown:pEvent];
1091- (void) keyUp: (NSEvent*) pEvent
1094 int code = MacKeyEventToVK(pEvent, flag);
1095 NSString *s = [pEvent charactersIgnoringModifiers];
1099 if ([s length] == 1)
1100 c = [s characterAtIndex:0];
1102 if(!
static_cast<bool>(flag & kFVIRTKEY))
1108 WDL_MakeUTFChar(utf8, c, 4);
1110 IKeyPress keyPress {utf8, code,
static_cast<bool>(flag & kFSHIFT),
1111 static_cast<bool>(flag & kFCONTROL),
1112 static_cast<bool>(flag & kFALT)};
1114 bool handle = mGraphics->OnKeyUp(mPrevX, mPrevY, keyPress);
1118 [[
self nextResponder] keyUp:pEvent];
1122- (void) scrollWheel: (NSEvent*) pEvent
1124 if (mTextFieldView) [
self endUserInput ];
1125 IMouseInfo info = [
self getMouseLeft:pEvent];
1126 float d = [pEvent deltaY];
1128 mGraphics->OnMouseWheel(info.x, info.y, info.ms, d);
1131static void MakeCursorFromName(NSCursor*& cursor,
const char *name)
1134 const char* basePath =
"/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors/";
1136 NSString* imagePath = [NSString stringWithFormat:@"%s%s/cursor.pdf", basePath, name];
1137 NSString* infoPath = [NSString stringWithFormat:@"file:%s%s/info.plist", basePath, name];
1138 NSImage* fileImage = [[NSImage alloc] initByReferencingFile: imagePath];
1139 NSImage *cursorImage = [[NSImage alloc] initWithSize:[fileImage size]];
1140 NSDictionary* info = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:infoPath]];
1143 double hotX = [info[@"hotx-scaled"] doubleValue];
1144 double hotY = [info[@"hoty-scaled"] doubleValue];
1145 double blur = [info[@"blur"] doubleValue];
1146 double offsetX = [info[@"shadowoffsetx"] doubleValue];
1147 double offsetY = [info[@"shadowoffsety"] doubleValue];
1148 double red = [info[@"shadowcolor"][0] doubleValue];
1149 double green = [info[@"shadowcolor"][1] doubleValue];
1150 double blue = [info[@"shadowcolor"][2] doubleValue];
1151 double alpha = [info[@"shadowcolor"][3] doubleValue];
1152 CGColorRef shadowColor = CGColorCreateGenericRGB(red, green, blue, alpha);
1154 for (
int scale = 1; scale <= 4; scale++)
1157 NSAffineTransform* xform = [NSAffineTransform transform];
1158 [xform scaleBy:scale];
1159 id hints = @{ NSImageHintCTM: xform };
1160 CGImageRef rasterCGImage = [fileImage CGImageForProposedRect:NULL context:nil hints:hints];
1163 size_t width = CGImageGetWidth(rasterCGImage);
1164 size_t height = CGImageGetHeight(rasterCGImage);
1165 CGSize offset = CGSize {
static_cast<CGFloat
>(offsetX * scale),
static_cast<CGFloat
>(offsetY * scale) };
1166 CGContextRef shadowContext = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(rasterCGImage), 0, CGImageGetColorSpace(rasterCGImage), CGImageGetBitmapInfo(rasterCGImage));
1167 CGContextSetShadowWithColor(shadowContext, offset, blur * scale, shadowColor);
1168 CGContextDrawImage(shadowContext, CGRectMake(0, 0, width, height), rasterCGImage);
1169 CGImageRef shadowCGImage = CGBitmapContextCreateImage(shadowContext);
1172 NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:shadowCGImage];
1173 [rep setSize:[fileImage size]];
1174 [cursorImage addRepresentation:rep];
1178 CGContextRelease(shadowContext);
1179 CGImageRelease(shadowCGImage);
1183 cursor = [[NSCursor alloc] initWithImage:cursorImage hotSpot:NSMakePoint(hotX, hotY)];
1186 [cursorImage release];
1187 [fileImage release];
1188 CGColorRelease(shadowColor);
1191- (void) setMouseCursor: (ECursor) cursorType
1193 NSCursor* pCursor =
nullptr;
1195 bool helpCurrent =
false;
1196 bool helpRequested =
false;
1200 case ECursor::ARROW: pCursor = [NSCursor arrowCursor];
break;
1201 case ECursor::IBEAM: pCursor = [NSCursor IBeamCursor];
break;
1203 if ([NSCursor respondsToSelector:
@selector(busyButClickableCursor)])
1204 pCursor = [NSCursor performSelector:@selector(busyButClickableCursor)];
1206 case ECursor::CROSS: pCursor = [NSCursor crosshairCursor];
break;
1207 case ECursor::UPARROW:
1208 if ([NSCursor respondsToSelector:
@selector(_windowResizeNorthCursor)])
1209 pCursor = [NSCursor performSelector:@selector(_windowResizeNorthCursor)];
1211 pCursor = [NSCursor resizeUpCursor];
1213 case ECursor::SIZENWSE:
1214 if ([NSCursor respondsToSelector:
@selector(_windowResizeNorthWestSouthEastCursor)])
1215 pCursor = [NSCursor performSelector:@selector(_windowResizeNorthWestSouthEastCursor)];
1217 case ECursor::SIZENESW:
1218 if ([NSCursor respondsToSelector:
@selector(_windowResizeNorthEastSouthWestCursor)])
1219 pCursor = [NSCursor performSelector:@selector(_windowResizeNorthEastSouthWestCursor)];
1221 case ECursor::SIZEWE:
1222 if ([NSCursor respondsToSelector:
@selector(_windowResizeEastWestCursor)])
1223 pCursor = [NSCursor performSelector:@selector(_windowResizeEastWestCursor)];
1225 pCursor = [NSCursor resizeLeftRightCursor];
1227 case ECursor::SIZENS:
1228 if ([NSCursor respondsToSelector:
@selector(_windowResizeNorthSouthCursor)])
1229 pCursor = [NSCursor performSelector:@selector(_windowResizeNorthSouthCursor)];
1231 pCursor = [NSCursor resizeUpDownCursor];
1233 case ECursor::SIZEALL:
1236 MakeCursorFromName(mMoveCursor,
"move");
1237 pCursor = mMoveCursor;
1240 case ECursor::INO: pCursor = [NSCursor operationNotAllowedCursor];
break;
1241 case ECursor::HAND: pCursor = [NSCursor pointingHandCursor];
break;
1242 case ECursor::APPSTARTING:
1243 if ([NSCursor respondsToSelector:
@selector(busyButClickableCursor)])
1244 pCursor = [NSCursor performSelector:@selector(busyButClickableCursor)];
1247 if ([NSCursor respondsToSelector:
@selector(_helpCursor)])
1248 pCursor = [NSCursor performSelector:@selector(_helpCursor)];
1249 helpRequested =
true;
1251 default: pCursor = [NSCursor arrowCursor];
break;
1254 if ([NSCursor respondsToSelector:
@selector(helpCursorShown)])
1255 helpCurrent = [NSCursor performSelector:@selector(helpCursorShown)];
1257 if (helpCurrent && !helpRequested)
1260#pragma clang diagnostic push
1261#pragma clang diagnostic ignored "-Wobjc-method-access"
1262 [NSCursor _setHelpCursor : false];
1263#pragma clang diagnostic pop
1267 pCursor = [NSCursor arrowCursor];
1272- (void) removeFromSuperview
1275 [
self endUserInput ];
1277 mGraphics->SetPlatformContext(
nullptr);
1280 mGraphics->GetDelegate()->CloseWindow();
1281 [
super removeFromSuperview];
1284- (void) controlTextDidEndEditing: (NSNotification*) aNotification
1286 char* txt = (
char*)[[mTextFieldView stringValue] UTF8String];
1288 mGraphics->SetControlValueAfterTextEdit(txt);
1289 mGraphics->SetAllControlsDirty();
1291 [
self endUserInput ];
1295- (BOOL) control: (NSControl*) control textView: (NSTextView*) textView doCommandBySelector: (
SEL) commandSelector
1297 if (commandSelector ==
@selector(cancelOperation:))
1299 [
self endUserInput ];
1300 mGraphics->SetAllControlsDirty();
1308 IGRAPHICS_MENU_RCVR* pDummyView = [[[IGRAPHICS_MENU_RCVR alloc] initWithFrame:bounds] autorelease];
1309 NSMenu* pNSMenu = [[[IGRAPHICS_MENU alloc] initWithIPopupMenuAndReceiver:&menu : pDummyView] autorelease];
1310 NSPoint wp = {bounds.origin.x, bounds.origin.y + bounds.size.height + 4};
1312 NSMenuItem* pSelectedItem = nil;
1314 auto selectedItemIdx = menu.GetChosenItemIdx();
1316 if (selectedItemIdx > -1)
1318 pSelectedItem = [pNSMenu itemAtIndex:selectedItemIdx];
1321 if (pSelectedItem != nil)
1323 wp = {bounds.origin.x, bounds.origin.y};
1326 [pNSMenu popUpMenuPositioningItem:pSelectedItem atLocation:wp inView:self];
1328 NSMenuItem* pChosenItem = [pDummyView menuItem];
1329 NSMenu* pChosenMenu = [pChosenItem menu];
1330 IPopupMenu* pIPopupMenu = [(IGRAPHICS_MENU*) pChosenMenu iPopupMenu];
1332 long chosenItemIdx = [pChosenMenu indexOfItem: pChosenItem];
1334 if (chosenItemIdx > -1 && pIPopupMenu)
1336 pIPopupMenu->SetChosenItemIdx((
int) chosenItemIdx);
1343- (void) createTextEntry: (
int) paramIdx : (const
IText&) text : (const
char*) str : (
int) length : (NSRect) areaRect;
1348 mTextFieldView = [[IGRAPHICS_TEXTFIELD alloc] initWithFrame: areaRect];
1350 if (text.mVAlign == EVAlign::Middle)
1352 IGRAPHICS_TEXTFIELDCELL* pCell = [[IGRAPHICS_TEXTFIELDCELL alloc] initTextCell:@"textfield"];
1353 [mTextFieldView setCell: pCell];
1354 [mTextFieldView setEditable: TRUE];
1355 [mTextFieldView setDrawsBackground: TRUE];
1358 CoreTextFontDescriptor* CTFontDescriptor = CoreTextHelpers::GetCTFontDescriptor(text, sFontDescriptorCache);
1359 double ratio = CTFontDescriptor->GetEMRatio() * mGraphics->GetDrawScale();
1360 NSFontDescriptor* fontDescriptor = (NSFontDescriptor*) CTFontDescriptor->GetDescriptor();
1361 NSFont* font = [NSFont fontWithDescriptor: fontDescriptor size: text.mSize * ratio];
1362 [mTextFieldView setFont: font];
1364 switch (text.mAlign)
1367 [mTextFieldView setAlignment: NSLeftTextAlignment];
1369 case EAlign::Center:
1370 [mTextFieldView setAlignment: NSCenterTextAlignment];
1373 [mTextFieldView setAlignment: NSRightTextAlignment];
1379 const IParam* pParam = paramIdx > kNoParameter ? mGraphics->GetDelegate()->GetParam(paramIdx) :
nullptr;
1384 NSMutableCharacterSet *characterSet = [[NSMutableCharacterSet alloc] init];
1386 switch ( pParam->
Type() )
1388 case IParam::kTypeEnum:
1389 case IParam::kTypeInt:
1390 case IParam::kTypeBool:
1391 [characterSet addCharactersInString:@"0123456789-+"];
1393 case IParam::kTypeDouble:
1394 [characterSet addCharactersInString:@"0123456789.-+"];
1400 [mTextFieldView setFormatter:[[[IGRAPHICS_FORMATTER alloc] init] autorelease]];
1401 [[mTextFieldView formatter] setAcceptableCharacterSet:characterSet];
1402 [[mTextFieldView formatter] setMaximumLength:length];
1403 [characterSet release];
1406 [[mTextFieldView cell] setLineBreakMode: NSLineBreakByTruncatingTail];
1407 [mTextFieldView setAllowsEditingTextAttributes:NO];
1408 [mTextFieldView setTextColor:ToNSColor(text.mTextEntryFGColor)];
1409 [mTextFieldView setBackgroundColor:ToNSColor(text.mTextEntryBGColor)];
1411 [mTextFieldView setStringValue: [NSString stringWithUTF8String:str]];
1413#ifndef COCOA_TEXTENTRY_BORDERED
1414 [mTextFieldView setBordered: NO];
1415 [mTextFieldView setFocusRingType:NSFocusRingTypeNone];
1418 [mTextFieldView setDelegate: self];
1420 [
self addSubview: mTextFieldView];
1421 NSWindow* pWindow = [
self window];
1422 [pWindow makeKeyAndOrderFront:nil];
1423 [pWindow makeFirstResponder: mTextFieldView];
1426- (void) endUserInput
1428 [mTextFieldView setDelegate: nil];
1429 [mTextFieldView removeFromSuperview];
1431 NSWindow* pWindow = [
self window];
1432 [pWindow makeFirstResponder: self];
1434 mTextFieldView =
nullptr;
1435 mGraphics->ClearInTextEntryControl();
1438- (BOOL) promptForColor: (
IColor&) color : (IColorPickerHandlerFunc) func;
1440 NSColorPanel* colorPanel = [NSColorPanel sharedColorPanel];
1441 mColorPickerFunc = func;
1443 [colorPanel setTarget:self];
1444 [colorPanel setShowsAlpha: TRUE];
1445 [colorPanel setAction:@selector(onColorPicked:)];
1446 [colorPanel setColor:ToNSColor(color)];
1447 [colorPanel orderFront:nil];
1449 return colorPanel != nil;
1452- (void) onColorPicked: (NSColorPanel*) pColorPanel
1454 mColorPickerFunc(FromNSColor([pColorPanel color]));
1457- (NSString*) view: (NSView*) pView stringForToolTip: (NSToolTipTag) tag point: (NSPoint) point userData: (
void*) pData
1459 int c = mGraphics ? GetMouseOver(mGraphics) : -1;
1460 if (c < 0)
return @"";
1462 const char* tooltip = mGraphics->GetControl(c)->GetTooltip();
1463 return CStringHasContents(tooltip) ? [NSString stringWithUTF8String:tooltip] :
@"";
1466- (void) registerToolTip: (
IRECT&) bounds
1468 [
self addToolTipRect: ToNSRect(mGraphics, bounds) owner: self userData: nil];
1471- (NSDragOperation) draggingEntered: (
id<NSDraggingInfo>) sender
1473 NSPasteboard *pPasteBoard = [sender draggingPasteboard];
1475 if ([[pPasteBoard types] containsObject:NSFilenamesPboardType])
1476 return NSDragOperationGeneric;
1478 return NSDragOperationNone;
1481- (BOOL) performDragOperation: (
id<NSDraggingInfo>) sender
1483 NSPasteboard* pPasteBoard = [sender draggingPasteboard];
1485 if ([[pPasteBoard types] containsObject:NSFilenamesPboardType])
1487 NSArray* pFiles = [pPasteBoard propertyListForType:NSFilenamesPboardType];
1488 NSPoint point = [sender draggingLocation];
1489 NSPoint relativePoint = [
self convertPoint: point fromView:nil];
1491 const float scale = mGraphics->GetDrawScale();
1492 const float x = relativePoint.x / scale;
1493 const float y = relativePoint.y / scale;
1494 if ([pFiles count] == 1)
1496 NSString* pFirstFile = [pFiles firstObject];
1497 mGraphics->OnDrop([pFirstFile UTF8String], x, y);
1499 else if ([pFiles count] > 1)
1501 std::vector<const char*> paths([pFiles count]);
1502 for (
auto i = 0; i < [pFiles count]; i++)
1504 NSString* pFile = [pFiles objectAtIndex: i];
1505 paths[i] = [pFile UTF8String];
1507 mGraphics->OnDropMultiple(paths, x, y);
1513- (NSDragOperation)draggingSession:(NSDraggingSession*) session sourceOperationMaskForDraggingContext:(NSDraggingContext)context
1515 return NSDragOperationCopy;
1518#if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1519- (void) frameDidChange:(NSNotification*) pNotification
1521 CGFloat scale = [[
self window] backingScaleFactor];
1523 [(CAMetalLayer*)[
self layer] setDrawableSize:CGSizeMake(self.frame.size.width * scale,
1524 self.frame.size.height * scale)];
1527#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
1528- (void) frameDidChange:(NSNotification*) pNotification
1530 [
self activateGLContext];
1571- (void) activateGLContext
1573#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
1574 [[
self openGLContext] makeCurrentContext];
1577#if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1578 if (mEGLDisplay != EGL_NO_DISPLAY && mEGLContext != EGL_NO_CONTEXT)
1579 eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
1583- (void) deactivateGLContext
1585#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
1586 [NSOpenGLContext clearCurrentContext];
1589#if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1590 if (mEGLDisplay != EGL_NO_DISPLAY)
1591 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1597#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
1598 [[
self openGLContext] flushBuffer];
1601#if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1602 if (mEGLDisplay != EGL_NO_DISPLAY && mEGLSurface != EGL_NO_SURFACE)
1603 eglSwapBuffers(mEGLDisplay, mEGLSurface);
1607#if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1608- (EGLDisplay) getEGLDisplay
1613- (EGLSurface) getEGLSurface
1618- (EGLContext) getEGLContext
This file contains the base IControl implementation, along with some base classes for specific types ...
IPlug logging a.k.a tracing functionality.
The lowest level base class of an IGraphics context.
IGraphics platform class for macOS.
EParamType Type() const
Get the parameter's type.
Used to manage a list of rectangular areas and optimize them for drawing to the screen.
Used to group mouse coordinates with mouse modifier information.
Used to manage color data, independent of draw class/platform.
Used for key press info, such as ASCII representation, virtual key (mapped to win32 codes) and modifi...
Used to manage mouse modifiers i.e.
Used to manage a rectangular area, independent of draw class/platform.
IText is used to manage font and text/text entry style for a piece of text on the UI,...