iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IGraphicsMac_view.mm
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
11#import <QuartzCore/QuartzCore.h>
12
13#if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
14#import <Metal/Metal.h>
15#endif
16
17#include "wdlutf8.h"
18
19#import "IGraphicsMac_view.h"
20#include "IControl.h"
21#include "IPlugParameter.h"
22#include "IPlugLogger.h"
23
24using namespace iplug;
25using namespace igraphics;
26
27static int MacKeyCodeToVK(int code)
28{
29 switch (code)
30 {
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;
76 }
77 return kVK_NONE;
78}
79
80static int MacKeyEventToVK(NSEvent* pEvent, int& flag)
81{
82 int code = kVK_NONE;
83
84 const NSInteger mod = [pEvent modifierFlags];
85
86 if (mod & NSShiftKeyMask) flag |= kFSHIFT;
87 if (mod & NSCommandKeyMask) flag |= kFCONTROL;
88 if (mod & NSAlternateKeyMask) flag |= kFALT;
89 if ((mod & NSControlKeyMask) /*&& !IsRightClickEmulateEnabled()*/) flag |= kFLWIN;
90
91 int rawcode = [pEvent keyCode];
92
93 code = MacKeyCodeToVK(rawcode);
94 if (code == kVK_NONE)
95 {
96 NSString *str = NULL;
97
98 if (!str || ![str length]) str = [pEvent charactersIgnoringModifiers];
99
100 if (!str || ![str length])
101 {
102 if (!code)
103 {
104 code = 1024 + rawcode; // raw code
105 flag |= kFVIRTKEY;
106 }
107 }
108 else
109 {
110 code = [str characterAtIndex:0];
111 if (code >= NSF1FunctionKey && code <= NSF24FunctionKey)
112 {
113 flag |= kFVIRTKEY;
114 code += kVK_F1 - NSF1FunctionKey;
115 }
116 else
117 {
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;
121 }
122 }
123 }
124 else
125 {
126 flag |= kFVIRTKEY;
127 if (code == 8) code = '\b';
128 }
129
130 if (!(flag & kFVIRTKEY)) flag &= ~kFSHIFT;
131
132 return code;
133}
134
135#ifndef IGRAPHICS_MENU_RCVR
136#warning The iPlug2 Obj-C namespace is not customized. Did you forget to include IPlugOBJCPrefix.pch?
137#endif
138
139@implementation IGRAPHICS_MENU_RCVR
140
141- (NSMenuItem*) menuItem
142{
143 return nsMenuItem;
144}
145
146- (void) onMenuSelection:(id) sender
147{
148 nsMenuItem = sender;
149}
150
151@end
152
153@implementation IGRAPHICS_MENU
154
155- (id) initWithIPopupMenuAndReceiver: (IPopupMenu*) pMenu : (NSView*) pView
156{
157 [self initWithTitle: @""];
158
159 NSMenuItem* nsMenuItem = nil;
160 NSMutableString* nsMenuItemTitle = nil;
161
162 [self setAutoenablesItems:NO];
163
164 int numItems = pMenu->NItems();
165
166 for (int i = 0; i < numItems; ++i)
167 {
168 IPopupMenu::Item* pMenuItem = pMenu->GetItem(i);
169
170 nsMenuItemTitle = [[[NSMutableString alloc] initWithUTF8String:pMenuItem->GetText()] autorelease];
171
172 if (pMenu->GetPrefix())
173 {
174 NSString* prefixString = 0;
175
176 switch (pMenu->GetPrefix())
177 {
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;
182 }
183
184 [nsMenuItemTitle insertString:prefixString atIndex:0];
185 }
186
187 if (pMenuItem->GetIsSeparator())
188 {
189 [self addItem:[NSMenuItem separatorItem]];
190 }
191 else if (pMenuItem->GetSubmenu())
192 {
193 nsMenuItem = [self addItemWithTitle:nsMenuItemTitle action:nil keyEquivalent:@""];
194 NSMenu* subMenu = [[IGRAPHICS_MENU alloc] initWithIPopupMenuAndReceiver:pMenuItem->GetSubmenu() :pView];
195 [self setSubmenu: subMenu forItem:nsMenuItem];
196 [subMenu release];
197 }
198 else
199 {
200 nsMenuItem = [self addItemWithTitle:nsMenuItemTitle action:@selector(onMenuSelection:) keyEquivalent:@""];
201
202 [nsMenuItem setTarget:pView];
203 }
204
205 if (nsMenuItem && !pMenuItem->GetIsSeparator())
206 {
207 [nsMenuItem setIndentationLevel:pMenuItem->GetIsTitle() ? 1 : 0 ];
208 [nsMenuItem setEnabled:pMenuItem->GetEnabled() ? YES : NO];
209 [nsMenuItem setState:pMenuItem->GetChecked() ? NSOnState : NSOffState];
210 }
211 }
212
213 mIPopupMenu = pMenu;
214
215 return self;
216}
217
218- (IPopupMenu*) iPopupMenu
219{
220 return mIPopupMenu;
221}
222
223@end
224
225@implementation IGRAPHICS_TEXTFIELD
226
227- (bool) becomeFirstResponder;
228{
229 bool success = [super becomeFirstResponder];
230 if (success)
231 {
232 NSTextView *textField = (NSTextView*) [self currentEditor];
233 if( [textField respondsToSelector: @selector(setInsertionPointColor:)] )
234 [textField setInsertionPointColor: [self textColor]];
235 }
236 return success;
237}
238
239@end
240
241// IGRAPHICS_TEXTFIELDCELL based on...
242
243// https://red-sweater.com/blog/148/what-a-difference-a-cell-makes
244
245// This source code is provided to you compliments of Red Sweater Software under the license as described below. NOTE: This is the MIT License.
246//
247// Copyright (c) 2006 Red Sweater Software
248//
249// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
250//
251// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
252//
253// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
254
255@implementation IGRAPHICS_TEXTFIELDCELL
256
257- (NSRect) drawingRectForBounds: (NSRect) inRect
258{
259 // Get the parent's idea of where we should draw
260 NSRect outRect = [super drawingRectForBounds:inRect];
261
262 // When the text field is being
263 // edited or selected, we have to turn off the magic because it screws up
264 // the configuration of the field editor. We sneak around this by
265 // intercepting selectWithFrame and editWithFrame and sneaking a
266 // reduced, centered rect in at the last minute.
267 if (mIsEditingOrSelecting == NO)
268 {
269 // Get our ideal size for current text
270 NSSize textSize = [self cellSize];
271
272 // Center that in the proposed rect
273 float heightDelta = outRect.size.height - textSize.height;
274
275 outRect.size.height -= heightDelta;
276 outRect.origin.y += (heightDelta / 2);
277 }
278
279 return outRect;
280}
281
282- (void) selectWithFrame: (NSRect) aRect inView: (NSView*) controlView editor: (NSText*) textObj delegate: (id) anObject start: (NSInteger) selStart length: (NSInteger) selLength
283{
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;
288}
289
290- (void) editWithFrame: (NSRect) aRect inView: (NSView*) controlView editor: (NSText*) textObj delegate: (id) anObject event: (NSEvent*) theEvent
291{
292 aRect = [self drawingRectForBounds:aRect];
293 mIsEditingOrSelecting = YES;
294 [super editWithFrame:aRect inView:controlView editor:textObj delegate:anObject event:theEvent];
295 mIsEditingOrSelecting = NO;
296}
297@end
298
299
300@implementation IGRAPHICS_FORMATTER
301
302- (void) dealloc
303{
304 [filterCharacterSet release];
305 [super dealloc];
306}
307
308- (BOOL) isPartialStringValid:(NSString*) partialString newEditingString:(NSString**) newString errorDescription:(NSString**) error
309{
310 if (filterCharacterSet != nil)
311 {
312 int i = 0;
313 int len = (int) [partialString length];
314
315 for (i = 0; i < len; i++)
316 {
317 if (![filterCharacterSet characterIsMember:[partialString characterAtIndex:i]])
318 {
319 return NO;
320 }
321 }
322 }
323
324 if (maxLength)
325 {
326 if ([partialString length] > maxLength)
327 {
328 return NO;
329 }
330 }
331
332 if (maxValue && [partialString intValue] > maxValue)
333 {
334 return NO;
335 }
336
337 return YES;
338}
339
340- (void) setAcceptableCharacterSet: (NSCharacterSet*) inCharacterSet
341{
342 [inCharacterSet retain];
343 [filterCharacterSet release];
344 filterCharacterSet = inCharacterSet;
345}
346
347- (void) setMaximumLength: (int) inLength
348{
349 maxLength = inLength;
350}
351
352- (void) setMaximumValue: (int) inValue
353{
354 maxValue = inValue;
355}
356
357- (NSString*) stringForObjectValue: (id) anObject
358{
359 if ([anObject isKindOfClass:[NSString class]])
360 {
361 return anObject;
362 }
363
364 return nil;
365}
366
367- (BOOL) getObjectValue: (id*) anObject forString:(NSString*) string errorDescription: (NSString **) error
368{
369 if (anObject && string)
370 {
371 *anObject = [NSString stringWithString:string];
372 }
373
374 return YES;
375}
376@end
377
378#pragma mark -
379
380extern StaticStorage<CoreTextFontDescriptor> sFontDescriptorCache;
381
382#ifdef IGRAPHICS_ACCESSKIT
383IGraphicsAccessibilityMac::IGraphicsAccessibilityMac(IGraphics& graphics, NSView* pView)
384: IGraphicsAccessibility(graphics)
385{
386 mAdapter = accesskit_macos_adapter_new((void*) pView, false, ActionHandler, this);
387}
388
389IGraphicsAccessibilityMac::~IGraphicsAccessibilityMac()
390{
391 accesskit_macos_adapter_free(mAdapter);
392}
393
394void IGraphicsAccessibilityMac::UpdateIfActive(accesskit_tree_update_factory factory, void* pUserData)
395{
396 if (accesskit_macos_queued_events* pEvents = accesskit_macos_adapter_update_if_active(mAdapter, factory, pUserData))
397 accesskit_macos_queued_events_raise(pEvents);
398}
399
400void IGraphicsAccessibilityMac::SetViewFocused(bool focused)
401{
402 if (focused == mViewFocused)
403 return;
404
405 mViewFocused = focused;
406
407 if (accesskit_macos_queued_events* pEvents = accesskit_macos_adapter_update_view_focus_state(mAdapter, focused))
408 accesskit_macos_queued_events_raise(pEvents);
409}
410
411NSArray* IGraphicsAccessibilityMac::GetChildren()
412{
413 return (NSArray*) accesskit_macos_adapter_view_children(mAdapter, ActivationHandler, this);
414}
415
416id IGraphicsAccessibilityMac::GetFocus()
417{
418 return (id) accesskit_macos_adapter_focus(mAdapter, ActivationHandler, this);
419}
420
421id IGraphicsAccessibilityMac::HitTest(NSPoint point)
422{
423 return (id) accesskit_macos_adapter_hit_test(mAdapter, point.x, point.y, ActivationHandler, this);
424}
425#endif
426
427@implementation IGRAPHICS_VIEW
428
429- (CALayer *)makeBackingLayer
430{
431 // CAMetalLayer is correct for both Metal and GLES - ANGLE uses Metal backend on macOS
432 // NB: this file is not ARC; the caller retains, so the layer must be autoreleased
433 // or it is stranded (with its drawable pool) every time the window closes
434#if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
435 return [[[CAMetalLayer alloc] init] autorelease];
436#else
437 return [[[CALayer alloc] init] autorelease];
438#endif
439}
440
441- (id) initWithIGraphics: (IGraphicsMac*) pGraphics
442{
443 TRACE
444
445 mGraphics = pGraphics;
446 NSRect r = NSMakeRect(0.f, 0.f, (float) pGraphics->WindowWidth(), (float) pGraphics->WindowHeight());
447 self = [super initWithFrame:r];
448
449 mMouseOutDuringDrag = false;
450
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]];
456
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]; // Create-rule +1, property assignment retains
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;
466 #endif
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
477 };
478 NSOpenGLPixelFormat* pPixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
479 NSOpenGLContext* pGLContext = [[NSOpenGLContext alloc] initWithFormat:pPixelFormat shareContext:nil];
480
481 #ifdef DEBUG
482 // CGLEnable([context CGLContextObj], kCGLCECrashOnRemovedFunctions); //SKIA_GL2 will crash
483 #endif
484
485 self.pixelFormat = pPixelFormat;
486 self.openGLContext = pGLContext;
487 self.wantsBestResolutionOpenGLSurface = YES;
488 #endif // IGRAPHICS_GL2 || defined IGRAPHICS_GL3
489
490 #if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
491 EGLDisplay display = eglGetPlatformDisplay(EGLenum(EGL_PLATFORM_ANGLE_ANGLE), 0, 0);
492
493 if (!display) {
494 DBGMSG("eglGetPlatformDisplay() returned error %i", eglGetError());
495 }
496
497 if (eglInitialize(display, nil, nil) == 0) {
498 DBGMSG("eglInitialize() returned error %i", eglGetError());
499 }
500
501 const EGLint configAttribs[9] = {
502 EGL_BLUE_SIZE, 8,
503 EGL_GREEN_SIZE, 8,
504 EGL_RED_SIZE, 8,
505 EGL_DEPTH_SIZE, 24,
506 EGL_NONE};
507 EGLint numConfigs = 0;
508 EGLConfig configs[1];
509
510 if (eglChooseConfig(display, configAttribs, configs, 1, &numConfigs) == 0) {
511 DBGMSG("eglChooseConfig() returned error %i", eglGetError());
512 }
513
514 if (!configs[0]) {
515 DBGMSG("Empty config returned in eglChooseConfig()");
516 }
517
518 #if defined IGRAPHICS_GLES2
519 const EGLint contextAttribs [5] = {
520 EGL_CONTEXT_MAJOR_VERSION, 2,
521 EGL_CONTEXT_MINOR_VERSION, 0,
522 EGL_NONE,
523 };
524 #elif defined IGRAPHICS_GLES3
525 const EGLint contextAttribs [5] = {
526 EGL_CONTEXT_MAJOR_VERSION, 3,
527 EGL_CONTEXT_MINOR_VERSION, 0,
528 EGL_NONE,
529 };
530 #endif
531
532 EGLContext context = eglCreateContext(display, configs[0], nullptr, contextAttribs);
533
534 if (!context) {
535 DBGMSG("eglCreateContext() returned error %d", eglGetError());
536 }
537
538 EGLSurface surface = eglCreateWindowSurface(display, configs[0], (__bridge EGLNativeWindowType) [self layer], nullptr);
539
540 if (!surface) {
541 DBGMSG("eglCreateWindowSurface() returned error %d", eglGetError());
542 }
543
544 mEGLSurface = surface;
545 mEGLDisplay = display;
546 mEGLContext = context;
547 #endif
548
549
550 #if !defined IGRAPHICS_GL2 && !defined IGRAPHICS_GL3
551 [self setTimer];
552 #endif
553
554 return self;
555}
556
557#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
558- (void) prepareOpenGL
559{
560 [super prepareOpenGL];
561
562 [self activateGLContext];
563
564 // Synchronize buffer swaps with vertical refresh rate
565 GLint swapInt = 1;
566 [[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
567
568 [self setTimer];
569}
570#endif
571
572static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* now, const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext)
573{
574 dispatch_source_t source = (dispatch_source_t) displayLinkContext;
575 dispatch_source_merge_data(source, 1);
576
577 return kCVReturnSuccess;
578}
579
580- (void) onTimer: (NSTimer*) pTimer
581{
582 [self render];
583}
584
585- (void) setTimer
586{
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, ^(){
590 [self render];
591 });
592 dispatch_resume(mDisplaySource);
593
594 CVReturn cvReturn;
595
596 cvReturn = CVDisplayLinkCreateWithActiveCGDisplays(&mDisplayLink);
597
598 assert(cvReturn == kCVReturnSuccess);
599
600 cvReturn = CVDisplayLinkSetOutputCallback(mDisplayLink, &displayLinkCallback, (void*) mDisplaySource);
601 assert(cvReturn == kCVReturnSuccess);
602
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);
607 #endif
608
609 CGDirectDisplayID viewDisplayID =
610 (CGDirectDisplayID) [self.window.screen.deviceDescription[@"NSScreenNumber"] unsignedIntegerValue];;
611
612 cvReturn = CVDisplayLinkSetCurrentCGDisplay(mDisplayLink, viewDisplayID);
613
614 assert(cvReturn == kCVReturnSuccess);
615
616 CVDisplayLinkStart(mDisplayLink);
617#else
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];
621#endif
622}
623
624- (void) killTimer
625{
626#ifdef IGRAPHICS_CVDISPLAYLINK
627 CVDisplayLinkStop(mDisplayLink);
628 dispatch_source_cancel(mDisplaySource);
629 CVDisplayLinkRelease(mDisplayLink);
630 mDisplayLink = nil;
631#else
632 [mTimer invalidate];
633 mTimer = nullptr;
634#endif
635}
636
637- (void) dealloc
638{
639 if([NSColorPanel sharedColorPanelExists])
640 [[NSColorPanel sharedColorPanel] close];
641
642 mColorPickerFunc = nullptr;
643 [mMoveCursor release];
644 [mTrackingArea release];
645 [[NSNotificationCenter defaultCenter] removeObserver:self];
646 [super dealloc];
647}
648
649
650- (BOOL) isOpaque
651{
652 return mGraphics ? YES : NO;
653}
654
655- (BOOL) isFlipped
656{
657 return YES;
658}
659
660- (void) viewDidChangeEffectiveAppearance
661{
662 if (@available(macOS 10.14, *)) {
663 BOOL isDarkMode = [[[self effectiveAppearance] name] isEqualToString: (NSAppearanceNameDarkAqua)];
664 mGraphics->OnAppearanceChanged(isDarkMode ? EUIAppearance::Dark : EUIAppearance::Light);
665 }
666}
667
668- (BOOL) acceptsFirstResponder
669{
670 return YES;
671}
672
673#ifdef IGRAPHICS_ACCESSKIT
674- (void) updateAccessibilityFocus
675{
676 if (mAccessibility)
677 {
678 NSWindow* pWindow = [self window];
679 mAccessibility->SetViewFocused(pWindow && [pWindow isKeyWindow] && [pWindow firstResponder] == self);
680 }
681}
682
683- (BOOL) becomeFirstResponder
684{
685 BOOL result = [super becomeFirstResponder];
686
687 // The window's first responder hasn't been updated yet
688 dispatch_async(dispatch_get_main_queue(), ^{ [self updateAccessibilityFocus]; });
689
690 return result;
691}
692
693- (BOOL) resignFirstResponder
694{
695 BOOL result = [super resignFirstResponder];
696 dispatch_async(dispatch_get_main_queue(), ^{ [self updateAccessibilityFocus]; });
697 return result;
698}
699
700- (void) windowKeyStateChanged: (NSNotification*) pNotification
701{
702 [self updateAccessibilityFocus];
703}
704
705- (NSArray*) accessibilityChildren
706{
707 NSArray* pChildren = [super accessibilityChildren];
708
709 if (mAccessibility)
710 {
711 NSArray* pControlChildren = mAccessibility->GetChildren();
712
713 // Any subviews (e.g. a text entry) come after the controls
714 if (pControlChildren)
715 pChildren = pChildren ? [pControlChildren arrayByAddingObjectsFromArray: pChildren] : pControlChildren;
716 }
717
718 return pChildren;
719}
720
721- (id) accessibilityFocusedUIElement
722{
723 if (mAccessibility && [[self window] firstResponder] == self)
724 {
725 id pElement = mAccessibility->GetFocus();
726
727 if (pElement)
728 return pElement;
729 }
730
731 return [super accessibilityFocusedUIElement];
732}
733
734- (id) accessibilityHitTest: (NSPoint) point
735{
736 // Subviews take priority, since they are on top of the controls
737 for (NSView* pSubview in [self subviews])
738 {
739 if (![pSubview isHidden] && NSPointInRect([self convertPoint: [[self window] convertPointFromScreen: point] fromView: nil], [pSubview frame]))
740 return [super accessibilityHitTest: point];
741 }
742
743 if (mAccessibility)
744 {
745 id pElement = mAccessibility->HitTest(point);
746
747 if (pElement)
748 return pElement;
749 }
750
751 return [super accessibilityHitTest: point];
752}
753#endif
754
755- (BOOL) acceptsFirstMouse: (NSEvent*) pEvent
756{
757 return YES;
758}
759
760- (void) viewDidMoveToWindow
761{
762 NSWindow* pWindow = [self window];
763
764#ifdef IGRAPHICS_ACCESSKIT
765 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
766 [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
767
768 if (pWindow)
769 {
770 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowKeyStateChanged:) name:NSWindowDidBecomeKeyNotification object:pWindow];
771 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowKeyStateChanged:) name:NSWindowDidResignKeyNotification object:pWindow];
772 }
773
774 dispatch_async(dispatch_get_main_queue(), ^{ [self updateAccessibilityFocus]; });
775#endif
776
777 if (pWindow)
778 {
779 [pWindow makeFirstResponder: self];
780 [pWindow setAcceptsMouseMovedEvents: YES];
781
782 CGFloat newScale = [pWindow backingScaleFactor];
783
784 if (mGraphics)
785 mGraphics->SetScreenScale(newScale);
786
787 #if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
788 [[NSNotificationCenter defaultCenter] addObserver:self
789 selector:@selector(frameDidChange:)
790 name:NSViewFrameDidChangeNotification
791 object:self];
792 #endif
793
794 #if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
795 [[NSNotificationCenter defaultCenter] addObserver:self
796 selector:@selector(frameDidChange:)
797 name:NSViewGlobalFrameDidChangeNotification
798 object:self];
799 #endif
800
801// [[NSNotificationCenter defaultCenter] addObserver:self
802// selector:@selector(windowResized:) name:NSWindowDidEndLiveResizeNotification
803// object:pWindow];
804//
805// [[NSNotificationCenter defaultCenter] addObserver:self
806// selector:@selector(windowFullscreened:) name:NSWindowDidEnterFullScreenNotification
807// object:pWindow];
808//
809// [[NSNotificationCenter defaultCenter] addObserver:self
810// selector:@selector(windowFullscreened:) name:NSWindowDidExitFullScreenNotification
811// object:pWindow];
812 }
813}
814
815- (void) viewDidChangeBackingProperties:(NSNotification*) pNotification
816{
817 NSWindow* pWindow = [self window];
818
819 if (!pWindow)
820 return;
821
822 CGFloat newScale = [pWindow backingScaleFactor];
823
824 mGraphics->SetPlatformContext(nullptr);
825
826 if (newScale != mGraphics->GetScreenScale())
827 mGraphics->SetScreenScale(newScale);
828
829 self.layer.contentsScale = [[self window] backingScaleFactor];
830
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)];
836#endif
837}
838
839- (CGContextRef) getCGContextRef
840{
841 CGContextRef pCGC = [NSGraphicsContext currentContext].CGContext;
842 return [NSGraphicsContext graphicsContextWithCGContext: pCGC flipped: YES].CGContext;
843}
844
845// not called for layer backed views
846- (void) drawRect: (NSRect) bounds
847{
848 #if defined IGRAPHICS_CPU
849 if (mGraphics)
850 {
851 mGraphics->SetPlatformContext([self getCGContextRef]);
852
853 if (mGraphics->GetPlatformContext())
854 {
855 const NSRect *rects;
856 NSInteger numRects;
857 [self getRectsBeingDrawn:&rects count:&numRects];
858 IRECTList drawRects;
859
860 for (int i = 0; i < numRects; i++)
861 drawRects.Add(ToIRECT(mGraphics, &rects[i]));
862
863 mGraphics->Draw(drawRects);
864 }
865 }
866 #endif
867}
868
869- (void) render
870{
871 mDirtyRects.Clear();
872
873 if (mGraphics->IsDirty(mDirtyRects))
874 {
875 mGraphics->SetAllControlsClean();
876
877 #if defined IGRAPHICS_CPU
878 for (int i = 0; i < mDirtyRects.Size(); i++)
879 [self setNeedsDisplayInRect:ToNSRect(mGraphics, mDirtyRects.Get(i))];
880 #else
881 IGraphics::ScopedGLContext scopedGLCtx {mGraphics};
882 // so just draw on each frame, if something is dirty
883 mGraphics->Draw(mDirtyRects);
884 [self swapBuffers]; // No-op for Metal
885 #endif
886 }
887}
888
889- (void) getMouseXY: (NSEvent*) pEvent : (float&) x : (float&) y
890{
891 if (mGraphics)
892 {
893 NSPoint pt = [self convertPoint:[pEvent locationInWindow] fromView:nil];
894 x = pt.x / mGraphics->GetDrawScale();
895 y = pt.y / mGraphics->GetDrawScale();
896
897 mGraphics->DoCursorLock(x, y, mPrevX, mPrevY);
898 mGraphics->SetTabletInput(pEvent.subtype == NSTabletPointEventSubtype);
899 }
900}
901
902- (IMouseInfo) getMouseLeft: (NSEvent*) pEvent
903{
904 IMouseInfo info;
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));
908
909 return info;
910}
911
912- (IMouseInfo) getMouseRight: (NSEvent*) pEvent
913{
914 IMouseInfo info;
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));
918
919 return info;
920}
921
922- (void) updateTrackingAreas
923{
924 [super updateTrackingAreas]; // This is needed to get mouseEntered and mouseExited
925
926 if (mTrackingArea != nil)
927 {
928 [self removeTrackingArea:mTrackingArea];
929 [mTrackingArea release];
930 }
931
932 int opts = (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingEnabledDuringMouseDrag);
933 mTrackingArea = [ [NSTrackingArea alloc] initWithRect:[self bounds] options:opts owner:self userInfo:nil];
934 [self addTrackingArea:mTrackingArea];
935}
936
937- (void) mouseEntered: (NSEvent*) pEvent
938{
939 mMouseOutDuringDrag = false;
940
941 if (mGraphics)
942 {
943 mGraphics->OnSetCursor();
944 }
945}
946
947- (void) mouseExited: (NSEvent*) pEvent
948{
949 if (mGraphics)
950 {
951 if (!mGraphics->ControlIsCaptured())
952 {
953 mGraphics->OnMouseOut();
954 }
955 else
956 {
957 mMouseOutDuringDrag = true;
958 }
959 }
960}
961
962- (void) mouseDown: (NSEvent*) pEvent
963{
964 IMouseInfo info = [self getMouseLeft:pEvent];
965 if (mGraphics)
966 {
967 if (([pEvent clickCount] - 1) % 2)
968 {
969 mGraphics->OnMouseDblClick(info.x, info.y, info.ms);
970 }
971 else
972 {
973 std::vector<IMouseInfo> list {info};
974 mGraphics->OnMouseDown(list);
975 }
976 }
977}
978
979- (void) mouseUp: (NSEvent*) pEvent
980{
981 IMouseInfo info = [self getMouseLeft:pEvent];
982 if (mGraphics)
983 {
984 std::vector<IMouseInfo> list {info};
985 mGraphics->OnMouseUp(list);
986
987 if (mMouseOutDuringDrag)
988 {
989 mGraphics->OnMouseOut();
990 mMouseOutDuringDrag = false;
991 }
992 }
993}
994
995- (void) mouseDragged: (NSEvent*) pEvent
996{
997 // Cache previous values before retrieving the new mouse position (which will update them)
998 float prevX = mPrevX;
999 float prevY = mPrevY;
1000 IMouseInfo info = [self getMouseLeft:pEvent];
1001 if (mGraphics && !mGraphics->IsInPlatformTextEntry())
1002 {
1003 info.dX = info.x - prevX;
1004 info.dY = info.y - prevY;
1005 std::vector<IMouseInfo> list {info};
1006 mGraphics->OnMouseDrag(list);
1007 }
1008}
1009
1010- (void) rightMouseDown: (NSEvent*) pEvent
1011{
1012 IMouseInfo info = [self getMouseRight:pEvent];
1013 if (mGraphics)
1014 {
1015 if (([pEvent clickCount] - 1) % 2)
1016 {
1017 mGraphics->OnMouseDblClick(info.x, info.y, info.ms);
1018 }
1019 else
1020 {
1021 std::vector<IMouseInfo> list {info};
1022 mGraphics->OnMouseDown(list);
1023 }
1024 }
1025}
1026
1027- (void) rightMouseUp: (NSEvent*) pEvent
1028{
1029 IMouseInfo info = [self getMouseRight:pEvent];
1030 if (mGraphics)
1031 {
1032 std::vector<IMouseInfo> list {info};
1033 mGraphics->OnMouseUp(list);
1034 }
1035}
1036
1037- (void) rightMouseDragged: (NSEvent*) pEvent
1038{
1039 // Cache previous values before retrieving the new mouse position (which will update them)
1040 float prevX = mPrevX;
1041 float prevY = mPrevY;
1042 IMouseInfo info = [self getMouseRight:pEvent];
1043
1044 if (mGraphics && !mTextFieldView)
1045 {
1046 info.dX = info.x - prevX;
1047 info.dY = info.y - prevY;
1048 std::vector<IMouseInfo> list {info};
1049 mGraphics->OnMouseDrag(list);
1050 }
1051}
1052
1053- (void) mouseMoved: (NSEvent*) pEvent
1054{
1055 IMouseInfo info = [self getMouseLeft:pEvent];
1056 if (mGraphics)
1057 mGraphics->OnMouseOver(info.x, info.y, info.ms);
1058}
1059
1060- (void) keyDown: (NSEvent*) pEvent
1061{
1062 int flag = 0;
1063 int code = MacKeyEventToVK(pEvent, flag);
1064 NSString *s = [pEvent charactersIgnoringModifiers];
1065
1066 unichar c = 0;
1067
1068 if ([s length] == 1)
1069 c = [s characterAtIndex:0];
1070
1071 if(!static_cast<bool>(flag & kFVIRTKEY))
1072 {
1073 code = kVK_NONE;
1074 }
1075
1076 char utf8[5];
1077 WDL_MakeUTFChar(utf8, c, 4);
1078
1079 IKeyPress keyPress {utf8, code, static_cast<bool>(flag & kFSHIFT),
1080 static_cast<bool>(flag & kFCONTROL),
1081 static_cast<bool>(flag & kFALT)};
1082
1083 bool handle = mGraphics->OnKeyDown(mPrevX, mPrevY, keyPress);
1084
1085 if (!handle)
1086 {
1087 [[self nextResponder] keyDown:pEvent];
1088 }
1089}
1090
1091- (void) keyUp: (NSEvent*) pEvent
1092{
1093 int flag = 0;
1094 int code = MacKeyEventToVK(pEvent, flag);
1095 NSString *s = [pEvent charactersIgnoringModifiers];
1096
1097 unichar c = 0;
1098
1099 if ([s length] == 1)
1100 c = [s characterAtIndex:0];
1101
1102 if(!static_cast<bool>(flag & kFVIRTKEY))
1103 {
1104 code = kVK_NONE;
1105 }
1106
1107 char utf8[5];
1108 WDL_MakeUTFChar(utf8, c, 4);
1109
1110 IKeyPress keyPress {utf8, code, static_cast<bool>(flag & kFSHIFT),
1111 static_cast<bool>(flag & kFCONTROL),
1112 static_cast<bool>(flag & kFALT)};
1113
1114 bool handle = mGraphics->OnKeyUp(mPrevX, mPrevY, keyPress);
1115
1116 if (!handle)
1117 {
1118 [[self nextResponder] keyUp:pEvent];
1119 }
1120}
1121
1122- (void) scrollWheel: (NSEvent*) pEvent
1123{
1124 if (mTextFieldView) [self endUserInput ];
1125 IMouseInfo info = [self getMouseLeft:pEvent];
1126 float d = [pEvent deltaY];
1127 if (mGraphics)
1128 mGraphics->OnMouseWheel(info.x, info.y, info.ms, d);
1129}
1130
1131static void MakeCursorFromName(NSCursor*& cursor, const char *name)
1132{
1133 // get paths and intialise images etc.
1134 const char* basePath = "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors/";
1135
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]];
1141
1142 // get info from dictionary
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);
1153
1154 for (int scale = 1; scale <= 4; scale++)
1155 {
1156 // 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];
1161
1162 // apply shadow
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);
1170
1171 // add to cursor inmge
1172 NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:shadowCGImage];
1173 [rep setSize:[fileImage size]];
1174 [cursorImage addRepresentation:rep];
1175
1176 // release
1177 [rep release];
1178 CGContextRelease(shadowContext);
1179 CGImageRelease(shadowCGImage);
1180 }
1181
1182 // create cursor
1183 cursor = [[NSCursor alloc] initWithImage:cursorImage hotSpot:NSMakePoint(hotX, hotY)];
1184
1185 // release
1186 [cursorImage release];
1187 [fileImage release];
1188 CGColorRelease(shadowColor);
1189}
1190
1191- (void) setMouseCursor: (ECursor) cursorType
1192{
1193 NSCursor* pCursor = nullptr;
1194
1195 bool helpCurrent = false;
1196 bool helpRequested = false;
1197
1198 switch (cursorType)
1199 {
1200 case ECursor::ARROW: pCursor = [NSCursor arrowCursor]; break;
1201 case ECursor::IBEAM: pCursor = [NSCursor IBeamCursor]; break;
1202 case ECursor::WAIT:
1203 if ([NSCursor respondsToSelector:@selector(busyButClickableCursor)])
1204 pCursor = [NSCursor performSelector:@selector(busyButClickableCursor)];
1205 break;
1206 case ECursor::CROSS: pCursor = [NSCursor crosshairCursor]; break;
1207 case ECursor::UPARROW:
1208 if ([NSCursor respondsToSelector:@selector(_windowResizeNorthCursor)])
1209 pCursor = [NSCursor performSelector:@selector(_windowResizeNorthCursor)];
1210 else
1211 pCursor = [NSCursor resizeUpCursor];
1212 break;
1213 case ECursor::SIZENWSE:
1214 if ([NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)])
1215 pCursor = [NSCursor performSelector:@selector(_windowResizeNorthWestSouthEastCursor)];
1216 break;
1217 case ECursor::SIZENESW:
1218 if ([NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)])
1219 pCursor = [NSCursor performSelector:@selector(_windowResizeNorthEastSouthWestCursor)];
1220 break;
1221 case ECursor::SIZEWE:
1222 if ([NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)])
1223 pCursor = [NSCursor performSelector:@selector(_windowResizeEastWestCursor)];
1224 else
1225 pCursor = [NSCursor resizeLeftRightCursor];
1226 break;
1227 case ECursor::SIZENS:
1228 if ([NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)])
1229 pCursor = [NSCursor performSelector:@selector(_windowResizeNorthSouthCursor)];
1230 else
1231 pCursor = [NSCursor resizeUpDownCursor];
1232 break;
1233 case ECursor::SIZEALL:
1234 {
1235 if (!mMoveCursor)
1236 MakeCursorFromName(mMoveCursor, "move");
1237 pCursor = mMoveCursor;
1238 break;
1239 }
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)];
1245 break;
1246 case ECursor::HELP:
1247 if ([NSCursor respondsToSelector:@selector(_helpCursor)])
1248 pCursor = [NSCursor performSelector:@selector(_helpCursor)];
1249 helpRequested = true;
1250 break;
1251 default: pCursor = [NSCursor arrowCursor]; break;
1252 }
1253
1254 if ([NSCursor respondsToSelector:@selector(helpCursorShown)])
1255 helpCurrent = [NSCursor performSelector:@selector(helpCursorShown)];
1256
1257 if (helpCurrent && !helpRequested)
1258 {
1259 // N.B. - suppress warnings for this call only
1260#pragma clang diagnostic push
1261#pragma clang diagnostic ignored "-Wobjc-method-access"
1262 [NSCursor _setHelpCursor : false];
1263#pragma clang diagnostic pop
1264 }
1265
1266 if (!pCursor)
1267 pCursor = [NSCursor arrowCursor];
1268
1269 [pCursor set];
1270}
1271
1272- (void) removeFromSuperview
1273{
1274 if (mTextFieldView)
1275 [self endUserInput ];
1276
1277 mGraphics->SetPlatformContext(nullptr);
1278
1279 //For some APIs (AUv2) this is where we know about the window being closed, close via delegate
1280 mGraphics->GetDelegate()->CloseWindow();
1281 [super removeFromSuperview];
1282}
1283
1284- (void) controlTextDidEndEditing: (NSNotification*) aNotification
1285{
1286 char* txt = (char*)[[mTextFieldView stringValue] UTF8String];
1287
1288 mGraphics->SetControlValueAfterTextEdit(txt);
1289 mGraphics->SetAllControlsDirty();
1290
1291 [self endUserInput ];
1292}
1293
1294// Escape cancels text entry (as on Windows) instead of committing it.
1295- (BOOL) control: (NSControl*) control textView: (NSTextView*) textView doCommandBySelector: (SEL) commandSelector
1296{
1297 if (commandSelector == @selector(cancelOperation:))
1298 {
1299 [self endUserInput ];
1300 mGraphics->SetAllControlsDirty();
1301 return YES;
1302 }
1303 return NO;
1304}
1305
1306- (IPopupMenu*) createPopupMenu: (IPopupMenu&) menu : (NSRect) bounds;
1307{
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};
1311
1312 NSMenuItem* pSelectedItem = nil;
1313
1314 auto selectedItemIdx = menu.GetChosenItemIdx();
1315
1316 if (selectedItemIdx > -1)
1317 {
1318 pSelectedItem = [pNSMenu itemAtIndex:selectedItemIdx];
1319 }
1320
1321 if (pSelectedItem != nil)
1322 {
1323 wp = {bounds.origin.x, bounds.origin.y};
1324 }
1325
1326 [pNSMenu popUpMenuPositioningItem:pSelectedItem atLocation:wp inView:self];
1327
1328 NSMenuItem* pChosenItem = [pDummyView menuItem];
1329 NSMenu* pChosenMenu = [pChosenItem menu];
1330 IPopupMenu* pIPopupMenu = [(IGRAPHICS_MENU*) pChosenMenu iPopupMenu];
1331
1332 long chosenItemIdx = [pChosenMenu indexOfItem: pChosenItem];
1333
1334 if (chosenItemIdx > -1 && pIPopupMenu)
1335 {
1336 pIPopupMenu->SetChosenItemIdx((int) chosenItemIdx);
1337 return pIPopupMenu;
1338 }
1339 else
1340 return nullptr;
1341}
1342
1343- (void) createTextEntry: (int) paramIdx : (const IText&) text : (const char*) str : (int) length : (NSRect) areaRect;
1344{
1345 if (mTextFieldView)
1346 return;
1347
1348 mTextFieldView = [[IGRAPHICS_TEXTFIELD alloc] initWithFrame: areaRect];
1349
1350 if (text.mVAlign == EVAlign::Middle)
1351 {
1352 IGRAPHICS_TEXTFIELDCELL* pCell = [[IGRAPHICS_TEXTFIELDCELL alloc] initTextCell:@"textfield"];
1353 [mTextFieldView setCell: pCell];
1354 [mTextFieldView setEditable: TRUE];
1355 [mTextFieldView setDrawsBackground: TRUE];
1356 }
1357
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];
1363
1364 switch (text.mAlign)
1365 {
1366 case EAlign::Near:
1367 [mTextFieldView setAlignment: NSLeftTextAlignment];
1368 break;
1369 case EAlign::Center:
1370 [mTextFieldView setAlignment: NSCenterTextAlignment];
1371 break;
1372 case EAlign::Far:
1373 [mTextFieldView setAlignment: NSRightTextAlignment];
1374 break;
1375 default:
1376 break;
1377 }
1378
1379 const IParam* pParam = paramIdx > kNoParameter ? mGraphics->GetDelegate()->GetParam(paramIdx) : nullptr;
1380
1381 // set up formatter
1382 if (pParam)
1383 {
1384 NSMutableCharacterSet *characterSet = [[NSMutableCharacterSet alloc] init];
1385
1386 switch ( pParam->Type() )
1387 {
1388 case IParam::kTypeEnum:
1389 case IParam::kTypeInt:
1390 case IParam::kTypeBool:
1391 [characterSet addCharactersInString:@"0123456789-+"];
1392 break;
1393 case IParam::kTypeDouble:
1394 [characterSet addCharactersInString:@"0123456789.-+"];
1395 break;
1396 default:
1397 break;
1398 }
1399
1400 [mTextFieldView setFormatter:[[[IGRAPHICS_FORMATTER alloc] init] autorelease]];
1401 [[mTextFieldView formatter] setAcceptableCharacterSet:characterSet];
1402 [[mTextFieldView formatter] setMaximumLength:length];
1403 [characterSet release];
1404 }
1405
1406 [[mTextFieldView cell] setLineBreakMode: NSLineBreakByTruncatingTail];
1407 [mTextFieldView setAllowsEditingTextAttributes:NO];
1408 [mTextFieldView setTextColor:ToNSColor(text.mTextEntryFGColor)];
1409 [mTextFieldView setBackgroundColor:ToNSColor(text.mTextEntryBGColor)];
1410
1411 [mTextFieldView setStringValue: [NSString stringWithUTF8String:str]];
1412
1413#ifndef COCOA_TEXTENTRY_BORDERED
1414 [mTextFieldView setBordered: NO];
1415 [mTextFieldView setFocusRingType:NSFocusRingTypeNone];
1416#endif
1417
1418 [mTextFieldView setDelegate: self];
1419
1420 [self addSubview: mTextFieldView];
1421 NSWindow* pWindow = [self window];
1422 [pWindow makeKeyAndOrderFront:nil];
1423 [pWindow makeFirstResponder: mTextFieldView];
1424}
1425
1426- (void) endUserInput
1427{
1428 [mTextFieldView setDelegate: nil];
1429 [mTextFieldView removeFromSuperview];
1430
1431 NSWindow* pWindow = [self window];
1432 [pWindow makeFirstResponder: self];
1433
1434 mTextFieldView = nullptr;
1435 mGraphics->ClearInTextEntryControl();
1436}
1437
1438- (BOOL) promptForColor: (IColor&) color : (IColorPickerHandlerFunc) func;
1439{
1440 NSColorPanel* colorPanel = [NSColorPanel sharedColorPanel];
1441 mColorPickerFunc = func;
1442
1443 [colorPanel setTarget:self];
1444 [colorPanel setShowsAlpha: TRUE];
1445 [colorPanel setAction:@selector(onColorPicked:)];
1446 [colorPanel setColor:ToNSColor(color)];
1447 [colorPanel orderFront:nil];
1448
1449 return colorPanel != nil;
1450}
1451
1452- (void) onColorPicked: (NSColorPanel*) pColorPanel
1453{
1454 mColorPickerFunc(FromNSColor([pColorPanel color]));
1455}
1456
1457- (NSString*) view: (NSView*) pView stringForToolTip: (NSToolTipTag) tag point: (NSPoint) point userData: (void*) pData
1458{
1459 int c = mGraphics ? GetMouseOver(mGraphics) : -1;
1460 if (c < 0) return @"";
1461
1462 const char* tooltip = mGraphics->GetControl(c)->GetTooltip();
1463 return CStringHasContents(tooltip) ? [NSString stringWithUTF8String:tooltip] : @"";
1464}
1465
1466- (void) registerToolTip: (IRECT&) bounds
1467{
1468 [self addToolTipRect: ToNSRect(mGraphics, bounds) owner: self userData: nil];
1469}
1470
1471- (NSDragOperation) draggingEntered: (id<NSDraggingInfo>) sender
1472{
1473 NSPasteboard *pPasteBoard = [sender draggingPasteboard];
1474
1475 if ([[pPasteBoard types] containsObject:NSFilenamesPboardType])
1476 return NSDragOperationGeneric;
1477 else
1478 return NSDragOperationNone;
1479}
1480
1481- (BOOL) performDragOperation: (id<NSDraggingInfo>) sender
1482{
1483 NSPasteboard* pPasteBoard = [sender draggingPasteboard];
1484
1485 if ([[pPasteBoard types] containsObject:NSFilenamesPboardType])
1486 {
1487 NSArray* pFiles = [pPasteBoard propertyListForType:NSFilenamesPboardType];
1488 NSPoint point = [sender draggingLocation];
1489 NSPoint relativePoint = [self convertPoint: point fromView:nil];
1490
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)
1495 {
1496 NSString* pFirstFile = [pFiles firstObject];
1497 mGraphics->OnDrop([pFirstFile UTF8String], x, y);
1498 }
1499 else if ([pFiles count] > 1)
1500 {
1501 std::vector<const char*> paths([pFiles count]);
1502 for (auto i = 0; i < [pFiles count]; i++)
1503 {
1504 NSString* pFile = [pFiles objectAtIndex: i];
1505 paths[i] = [pFile UTF8String];
1506 }
1507 mGraphics->OnDropMultiple(paths, x, y);
1508 }
1509 }
1510 return YES;
1511}
1512
1513- (NSDragOperation)draggingSession:(NSDraggingSession*) session sourceOperationMaskForDraggingContext:(NSDraggingContext)context
1514{
1515 return NSDragOperationCopy;
1516}
1517
1518#if defined IGRAPHICS_METAL || defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1519- (void) frameDidChange:(NSNotification*) pNotification
1520{
1521 CGFloat scale = [[self window] backingScaleFactor];
1522
1523 [(CAMetalLayer*)[self layer] setDrawableSize:CGSizeMake(self.frame.size.width * scale,
1524 self.frame.size.height * scale)];
1525}
1526#endif
1527#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
1528- (void) frameDidChange:(NSNotification*) pNotification
1529{
1530 [self activateGLContext];
1531}
1532#endif
1533
1534//- (void) windowResized: (NSNotification*) notification;
1535//{
1536// if(!mGraphics)
1537// return;
1538//
1539// NSSize windowSize = [[self window] frame].size;
1540// NSRect viewFrameInWindowCoords = [self convertRect: [self bounds] toView: nil];
1541//
1542// float width = windowSize.width - viewFrameInWindowCoords.origin.x;
1543// float height = windowSize.height - viewFrameInWindowCoords.origin.y;
1544//
1545// float scaleX = width / mGraphics->Width();
1546// float scaleY = height / mGraphics->Height();
1547//
1548// if(mGraphics->GetUIResizerMode() == EUIResizerMode::Scale)
1549// mGraphics->Resize(width, height, mGraphics->GetDrawScale());
1550// else // EUIResizerMode::Size
1551// mGraphics->Resize(mGraphics->Width(), mGraphics->Height(), Clip(std::min(scaleX, scaleY), 0.1f, 10.f));
1552//}
1553//
1554//- (void) windowFullscreened: (NSNotification*) pNotification;
1555//{
1556// NSSize windowSize = [[self window] frame].size;
1557// NSRect viewFrameInWindowCoords = [self convertRect: [self bounds] toView: nil];
1558//
1559// float width = windowSize.width - viewFrameInWindowCoords.origin.x;
1560// float height = windowSize.height - viewFrameInWindowCoords.origin.y;
1561//
1562// float scaleX = width / mGraphics->Width();
1563// float scaleY = height / mGraphics->Height();
1564//
1565// if(mGraphics->GetUIResizerMode() == EUIResizerMode::Scale)
1566// mGraphics->Resize(width, height, mGraphics->GetDrawScale());
1567// else // EUIResizerMode::Size
1568// mGraphics->Resize(mGraphics->Width(), mGraphics->Height(), Clip(std::min(scaleX, scaleY), 0.1f, 10.f));
1569//}
1570
1571- (void) activateGLContext
1572{
1573#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
1574 [[self openGLContext] makeCurrentContext];
1575#endif
1576
1577#if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1578 if (mEGLDisplay != EGL_NO_DISPLAY && mEGLContext != EGL_NO_CONTEXT)
1579 eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
1580#endif
1581}
1582
1583- (void) deactivateGLContext
1584{
1585#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
1586 [NSOpenGLContext clearCurrentContext];
1587#endif
1588
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);
1592#endif
1593}
1594
1595- (void) swapBuffers
1596{
1597#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
1598 [[self openGLContext] flushBuffer];
1599#endif
1600
1601#if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1602 if (mEGLDisplay != EGL_NO_DISPLAY && mEGLSurface != EGL_NO_SURFACE)
1603 eglSwapBuffers(mEGLDisplay, mEGLSurface);
1604#endif
1605}
1606
1607#if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
1608- (EGLDisplay) getEGLDisplay
1609{
1610 return mEGLDisplay;
1611}
1612
1613- (EGLSurface) getEGLSurface
1614{
1615 return mEGLSurface;
1616}
1617
1618- (EGLContext) getEGLContext
1619{
1620 return mEGLContext;
1621}
1622#endif
1623
1624@end
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.
Definition: IGraphics.h:87
IGraphics platform class for macOS.
Definition: IGraphicsMac.h:24
IPlug's parameter class.
EParamType Type() const
Get the parameter's type.
A class to specify an item of a pop up menu.
A class for setting the contents of a pop up menu.
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...
Definition: IPlugStructs.h:615
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,...