11#include "IGraphicsMac.h"
12#import "IGraphicsMac_view.h"
14#if defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
15#import <libEGL/libEGL.h>
21#pragma clang diagnostic ignored "-Wdeprecated-declarations"
24using namespace igraphics;
26static int GetSystemVersion()
31 if (NSAppKitVersionNumber >= 1266.0)
33 if (NSAppKitVersionNumber >= 1404.0)
41 Gestalt(gestaltSystemVersion,&a);
48StaticStorage<CoreTextFontDescriptor> sFontDescriptorCache;
52IGraphicsMac::IGraphicsMac(
IGEditorDelegate& dlg,
int w,
int h,
int fps,
float scale)
53: IGRAPHICS_DRAW_CLASS(dlg, w, h, fps, scale)
56 StaticStorage<CoreTextFontDescriptor>::Accessor storage(sFontDescriptorCache);
60IGraphicsMac::~IGraphicsMac()
62 StaticStorage<CoreTextFontDescriptor>::Accessor storage(sFontDescriptorCache);
68PlatformFontPtr IGraphicsMac::LoadPlatformFont(
const char* fontID,
const char* fileNameOrResID)
70 return CoreTextHelpers::LoadPlatformFont(fontID, fileNameOrResID, GetBundleID(), GetSharedResourcesSubPath());
73PlatformFontPtr IGraphicsMac::LoadPlatformFont(
const char* fontID,
const char* fontName, ETextStyle style)
75 return CoreTextHelpers::LoadPlatformFont(fontID, fontName, style);
78PlatformFontPtr IGraphicsMac::LoadPlatformFont(
const char* fontID,
void* pData,
int dataSize)
80 return CoreTextHelpers::LoadPlatformFont(fontID, pData, dataSize);
83void IGraphicsMac::CachePlatformFont(
const char* fontID,
const PlatformFontPtr& font)
85 CoreTextHelpers::CachePlatformFont(fontID, font, sFontDescriptorCache);
88float IGraphicsMac::MeasureText(
const IText& text,
const char* str,
IRECT& bounds)
const
90 return IGRAPHICS_DRAW_CLASS::MeasureText(text, str, bounds);
93void* IGraphicsMac::OpenWindow(
void* pParent)
97 IGRAPHICS_VIEW* pView = [[IGRAPHICS_VIEW alloc] initWithIGraphics:
this];
98 mView = (
void*) pView;
100#ifdef IGRAPHICS_ACCESSKIT
101 auto pAccessibility = std::make_unique<IGraphicsAccessibilityMac>(*
this, pView);
102 pView->mAccessibility = pAccessibility.get();
103 mAccessibility = std::move(pAccessibility);
107 OnViewInitialized([pView layer]);
108 SetScreenScale([[NSScreen mainScreen] backingScaleFactor]);
109 GetDelegate()->LayoutUI(
this);
111 GetDelegate()->OnUIOpen();
115 [(NSView*) pParent addSubview: pView];
121void IGraphicsMac::AttachPlatformView(
const IRECT& r,
void* pView)
123 NSView* pNewSubView = (NSView*) pView;
124 [pNewSubView setFrame:ToNSRect(
this, r)];
126 [(IGRAPHICS_VIEW*) mView addSubview:(NSView*) pNewSubView];
129void IGraphicsMac::RemovePlatformView(
void* pView)
131 [(NSView*) pView removeFromSuperview];
134void IGraphicsMac::HidePlatformView(
void* pView,
bool hide)
136 [(NSView*) pView setHidden:hide];
139void IGraphicsMac::CloseWindow()
143 IGRAPHICS_VIEW* pView = (IGRAPHICS_VIEW*) mView;
145#if defined IGRAPHICS_GL2 || defined IGRAPHICS_GL3
146 [[pView pixelFormat] release];
147 [[pView openGLContext] release];
148#elif defined IGRAPHICS_GLES2 || defined IGRAPHICS_GLES3
149 [pView deactivateGLContext];
150 eglDestroySurface([pView getEGLDisplay], [pView getEGLSurface]);
151 eglDestroyContext([pView getEGLDisplay], [pView getEGLContext]);
152 eglTerminate([pView getEGLDisplay]);
155 [pView removeAllToolTips];
157#ifdef IGRAPHICS_ACCESSKIT
158 pView->mAccessibility =
nullptr;
159 mAccessibility =
nullptr;
161 [pView removeFromSuperview];
169bool IGraphicsMac::WindowIsOpen()
174void IGraphicsMac::PlatformResize(
bool parentHasResized)
178 NSSize size = {
static_cast<CGFloat
>(WindowWidth()),
static_cast<CGFloat
>(WindowHeight()) };
180 [NSAnimationContext beginGrouping];
181 [[NSAnimationContext currentContext] setDuration:0.0];
182 [(IGRAPHICS_VIEW*) mView setFrameSize: size ];
184 [NSAnimationContext endGrouping];
190void IGraphicsMac::PointToScreen(
float& x,
float& y)
const
196 NSWindow* pWindow = [(IGRAPHICS_VIEW*) mView window];
197 NSPoint wndpt = [(IGRAPHICS_VIEW*) mView convertPoint:NSMakePoint(x, y) toView:nil];
198 NSPoint pt = [pWindow convertRectToScreen: NSMakeRect(wndpt.x, wndpt.y, 0.0, 0.0)].origin;
205void IGraphicsMac::ScreenToPoint(
float& x,
float& y)
const
209 NSWindow* pWindow = [(IGRAPHICS_VIEW*) mView window];
210 NSPoint wndpt = [pWindow convertRectFromScreen: NSMakeRect(x, y, 0.0, 0.0)].origin;
211 NSPoint pt = [(IGRAPHICS_VIEW*) mView convertPoint:NSMakePoint(wndpt.x, wndpt.y) fromView:nil];
213 x = pt.x / GetDrawScale();
214 y = pt.y / GetDrawScale();
218void IGraphicsMac::HideMouseCursor(
bool hide,
bool lock)
222#elif defined AUv3_API
223 if (!IsOOPAuv3AppExtension())
226 if (mCursorHidden == hide)
229 mCursorHidden = hide;
233 StoreCursorPosition();
234 CGDisplayHideCursor(kCGDirectMainDisplay);
239 DoCursorLock(mCursorX, mCursorY, mCursorX, mCursorY);
240 CGDisplayShowCursor(kCGDirectMainDisplay);
246void IGraphicsMac::MoveMouseCursor(
float x,
float y)
252 RepositionCursor(CGPoint{x, y});
253 StoreCursorPosition();
256void IGraphicsMac::DoCursorLock(
float x,
float y,
float& prevX,
float& prevY)
258 if (mCursorHidden && mCursorLock && !mTabletInput)
260 RepositionCursor(mCursorLockPosition);
266 mCursorX = prevX = x;
267 mCursorY = prevY = y;
271void IGraphicsMac::RepositionCursor(CGPoint point)
273 point = CGPoint{point.x, CGDisplayPixelsHigh(CGMainDisplayID()) - point.y};
274 CGAssociateMouseAndMouseCursorPosition(
false);
275 CGDisplayMoveCursorToPoint(CGMainDisplayID(), point);
276 CGAssociateMouseAndMouseCursorPosition(
true);
279void IGraphicsMac::StoreCursorPosition()
282 NSPoint mouse = [NSEvent mouseLocation];
283 mCursorX = mouse.x = std::round(mouse.x);
284 mCursorY = mouse.y = std::round(mouse.y);
285 mCursorLockPosition = CGPoint{mouse.x, mouse.y};
288 ScreenToPoint(mCursorX, mCursorY);
291void IGraphicsMac::GetMouseLocation(
float& x,
float&y)
const
294 NSPoint mouse = [NSEvent mouseLocation];
302EMsgBoxResult IGraphicsMac::ShowMessageBox(
const char* str,
const char* title, EMsgBoxType type, IMsgBoxCompletionHandlerFunc completionHandler)
304 ReleaseMouseCapture();
306 NSString* messageContent = @(str ? str :
"");
307 NSString* alertTitle = @(title ? title :
"");
309 NSAlert* alert = [[NSAlert alloc] init];
310 [alert setMessageText:alertTitle];
311 [alert setInformativeText:messageContent];
313 EMsgBoxResult result = kCANCEL;
318 [alert addButtonWithTitle:
@"OK"];
322 [alert addButtonWithTitle:
@"OK"];
323 [alert addButtonWithTitle:
@"Cancel"];
327 [alert addButtonWithTitle:
@"Yes"];
328 [alert addButtonWithTitle:
@"No"];
331 case kMB_RETRYCANCEL:
332 [alert addButtonWithTitle:
@"Retry"];
333 [alert addButtonWithTitle:
@"Cancel"];
336 case kMB_YESNOCANCEL:
337 [alert addButtonWithTitle:
@"Yes"];
338 [alert addButtonWithTitle:
@"No"];
339 [alert addButtonWithTitle:
@"Cancel"];
344 NSModalResponse response = [alert runModal];
352 result = (response == NSAlertFirstButtonReturn) ? kOK : kCANCEL;
355 result = (response == NSAlertFirstButtonReturn) ? kYES : kNO;
357 case kMB_RETRYCANCEL:
358 result = (response == NSAlertFirstButtonReturn) ? kRETRY : kCANCEL;
360 case kMB_YESNOCANCEL:
361 if (response == NSAlertFirstButtonReturn) result = kYES;
362 else if (response == NSAlertSecondButtonReturn) result = kNO;
363 else result = kCANCEL;
367 if (completionHandler)
369 completionHandler(result);
377void IGraphicsMac::ForceEndUserEdit()
381 [(IGRAPHICS_VIEW*) mView endUserInput];
385void IGraphicsMac::UpdateTooltips()
387 if (!(mView && TooltipsEnabled()))
392 [(IGRAPHICS_VIEW*) mView removeAllToolTips];
394 if (GetPopupMenuControl() && GetPopupMenuControl()->GetState() > IPopupMenuControl::kCollapsed)
399 auto func = [
this](
IControl* pControl)
401 if (pControl->GetTooltip() && !pControl->IsHidden())
403 IRECT pR = pControl->GetTargetRECT();
406 [(IGRAPHICS_VIEW*) mView registerToolTip: pR];
411 ForStandardControlsFunc(func);
416const char* IGraphicsMac::GetPlatformAPIStr()
421bool IGraphicsMac::RevealPathInExplorerOrFinder(WDL_String& path,
bool select)
423 BOOL success = FALSE;
429 NSString* pPath = [NSString stringWithUTF8String:path.Get()];
431 if([[NSFileManager defaultManager] fileExistsAtPath : pPath] == YES)
435 NSString* pParentDirectoryPath = [pPath stringByDeletingLastPathComponent];
437 if (pParentDirectoryPath)
439 success = [[NSWorkspace sharedWorkspace] openFile:pParentDirectoryPath];
442 success = [[NSWorkspace sharedWorkspace] selectFile: pPath inFileViewerRootedAtPath:pParentDirectoryPath];
446 success = [[NSWorkspace sharedWorkspace] openFile:pPath];
453 return (
bool) success;
456void IGraphicsMac::PromptForFile(WDL_String& fileName, WDL_String& path, EFileAction action,
const char* ext, IFileDialogCompletionHandlerFunc completionHandler)
464 NSString* pDefaultFileName = nil;
465 NSString* pDefaultPath = nil;
466 NSArray* pFileTypes = nil;
468 if (fileName.GetLength())
469 pDefaultFileName = [NSString stringWithUTF8String:fileName.Get()];
471 pDefaultFileName =
@"";
473 if (path.GetLength())
474 pDefaultPath = [NSString stringWithUTF8String:path.Get()];
480 if (CStringHasContents(ext))
481 pFileTypes = [[NSString stringWithUTF8String:ext] componentsSeparatedByString:
@" "];
483 auto doHandleResponse = [](NSPanel* pPanel, NSModalResponse response, WDL_String& fileName, WDL_String& path, IFileDialogCompletionHandlerFunc completionHandler){
484 if (response == NSOKButton)
486 NSString* pFullPath = [(NSSavePanel*) pPanel filename] ;
487 fileName.Set([pFullPath UTF8String]);
489 NSString* pTruncatedPath = [pFullPath stringByDeletingLastPathComponent];
493 path.Set([pTruncatedPath UTF8String]);
498 if (completionHandler)
499 completionHandler(fileName, path);
502 NSPanel* pPanel =
nullptr;
504 if (action == EFileAction::Save)
506 pPanel = [NSSavePanel savePanel];
508 [(NSSavePanel*) pPanel setAllowedFileTypes: pFileTypes];
509 [(NSSavePanel*) pPanel setDirectoryURL: [NSURL fileURLWithPath: pDefaultPath]];
510 [(NSSavePanel*) pPanel setNameFieldStringValue: pDefaultFileName];
511 [(NSSavePanel*) pPanel setAllowsOtherFileTypes: NO];
515 pPanel = [NSOpenPanel openPanel];
517 [(NSOpenPanel*) pPanel setAllowedFileTypes: pFileTypes];
518 [(NSOpenPanel*) pPanel setDirectoryURL: [NSURL fileURLWithPath: pDefaultPath]];
519 [(NSOpenPanel*) pPanel setCanChooseFiles:YES];
520 [(NSOpenPanel*) pPanel setCanChooseDirectories:NO];
521 [(NSOpenPanel*) pPanel setResolvesAliases:YES];
523 [pPanel setFloatingPanel: YES];
525 if (completionHandler)
527 NSWindow* pWindow = [(IGRAPHICS_VIEW*) mView window];
529 [(NSSavePanel*) pPanel beginSheetModalForWindow:pWindow completionHandler:^(NSModalResponse response) {
530 WDL_String fileNameAsync, pathAsync;
531 doHandleResponse(pPanel, response, fileNameAsync, pathAsync, completionHandler);
536 NSModalResponse response = [(NSSavePanel*) pPanel runModal];
537 doHandleResponse(pPanel, response, fileName, path,
nullptr);
541void IGraphicsMac::PromptForDirectory(WDL_String& dir, IFileDialogCompletionHandlerFunc completionHandler)
543 NSString* defaultPath;
547 defaultPath = [NSString stringWithUTF8String:dir.Get()];
551 defaultPath = [NSString stringWithUTF8String:DEFAULT_PATH];
552 dir.Set(DEFAULT_PATH);
555 NSOpenPanel* panelOpen = [NSOpenPanel openPanel];
557 [panelOpen setTitle:
@"Choose a Directory"];
558 [panelOpen setCanChooseFiles:NO];
559 [panelOpen setCanChooseDirectories:YES];
560 [panelOpen setResolvesAliases:YES];
561 [panelOpen setCanCreateDirectories:YES];
562 [panelOpen setFloatingPanel: YES];
563 [panelOpen setDirectoryURL: [NSURL fileURLWithPath: defaultPath]];
565 auto doHandleResponse = [](NSOpenPanel* pPanel, NSModalResponse response, WDL_String& pathAsync, IFileDialogCompletionHandlerFunc completionHandler){
566 if (response == NSOKButton)
568 NSString* fullPath = [pPanel filename] ;
569 pathAsync.Set([fullPath UTF8String]);
570 pathAsync.Append(
"/");
577 if (completionHandler)
579 WDL_String fileNameAsync;
580 completionHandler(fileNameAsync, pathAsync);
584 if (completionHandler)
586 NSWindow* pWindow = [(IGRAPHICS_VIEW*) mView window];
588 [panelOpen beginSheetModalForWindow:pWindow completionHandler:^(NSModalResponse response) {
589 WDL_String pathAsync;
590 doHandleResponse(panelOpen, response, pathAsync, completionHandler);
595 NSModalResponse response = [panelOpen runModal];
596 doHandleResponse(panelOpen, response, dir,
nullptr);
600bool IGraphicsMac::PromptForColor(
IColor& color,
const char* str, IColorPickerHandlerFunc func)
603 return [(IGRAPHICS_VIEW*) mView promptForColor:color : func];
612 dispatch_async(dispatch_get_main_queue(), ^{
617 NSRect areaRect = ToNSRect(
this, bounds);
618 pReturnMenu = [(IGRAPHICS_VIEW*) mView createPopupMenu: menu: areaRect];
621 if (pReturnMenu && pReturnMenu->GetFunction())
622 pReturnMenu->ExecFunction();
624 this->SetControlValueAfterPopupMenu(pReturnMenu);
630void IGraphicsMac::CreatePlatformTextEntry(
int paramIdx,
const IText& text,
const IRECT& bounds,
int length,
const char* str)
634 NSRect areaRect = ToNSRect(
this, bounds);
635 [(IGRAPHICS_VIEW*) mView createTextEntry: paramIdx : text: str: length: areaRect];
639ECursor IGraphicsMac::SetMouseCursor(ECursor cursorType)
642 [(IGRAPHICS_VIEW*) mView setMouseCursor: cursorType];
647bool IGraphicsMac::OpenURL(
const char* url,
const char* msgWindowTitle,
const char* confirmMsg,
const char* errMsgOnFailure)
649 #pragma REMINDER("Warning and error messages for OpenURL not implemented")
650 NSURL* pNSURL =
nullptr;
651 if (strstr(url,
"http"))
652 pNSURL = [NSURL URLWithString:[NSString stringWithUTF8String:url]];
654 pNSURL = [NSURL fileURLWithPath:[NSString stringWithUTF8String:url]];
658 bool ok = ([[NSWorkspace sharedWorkspace] openURL:pNSURL]);
664void* IGraphicsMac::GetWindow()
666 if (mView)
return mView;
671int IGraphicsMac::GetUserOSVersion()
673 return (
int) GetSystemVersion();
676bool IGraphicsMac::GetTextFromClipboard(WDL_String& str)
678 NSString* pTextOnClipboard = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
680 if (pTextOnClipboard == nil)
687 str.Set([pTextOnClipboard UTF8String]);
692bool IGraphicsMac::SetTextInClipboard(
const char* str)
694 NSString* pTextForClipboard = [NSString stringWithUTF8String:str];
695 [[NSPasteboard generalPasteboard] clearContents];
696 return [[NSPasteboard generalPasteboard] setString:pTextForClipboard forType:NSStringPboardType];
699bool IGraphicsMac::SetFilePathInClipboard(
const char* path)
701 NSPasteboard* pPasteboard = [NSPasteboard generalPasteboard];
702 [pPasteboard clearContents];
703 NSURL* pFileURL = [NSURL fileURLWithPath: [NSString stringWithUTF8String:path]];
704 BOOL success = [pPasteboard writeObjects: [NSArray arrayWithObject:pFileURL]];
705 return (
bool)success;
708bool IGraphicsMac::InitiateExternalFileDragDrop(
const char* path,
const IRECT& iconBounds)
710 NSPasteboardItem* pasteboardItem = [[NSPasteboardItem alloc] init];
711 NSURL* fileURL = [NSURL fileURLWithPath: [NSString stringWithUTF8String:path]];
712 [pasteboardItem setString:fileURL.absoluteString forType:NSPasteboardTypeFileURL];
714 NSDraggingItem* draggingItem = [[NSDraggingItem alloc] initWithPasteboardWriter:pasteboardItem];
715 NSRect draggingFrame = ToNSRect(
this, iconBounds);
716 NSImage* iconImage = [[NSWorkspace sharedWorkspace] iconForFile:fileURL.path];
717 [iconImage setSize:NSMakeSize(64, 64)];
718 [draggingItem setDraggingFrame:draggingFrame contents: iconImage];
720 IGRAPHICS_VIEW* view = (IGRAPHICS_VIEW*) mView;
721 NSDraggingSession* draggingSession = [view beginDraggingSessionWithItems:@[draggingItem] event:[NSApp currentEvent] source: view];
722 draggingSession.animatesToStartingPositionsOnCancelOrFail = YES;
723 draggingSession.draggingFormation = NSDraggingFormationNone;
725 ReleaseMouseCapture();
730EUIAppearance IGraphicsMac::GetUIAppearance()
const
732 if (@available(macOS 10.14, *)) {
735 IGRAPHICS_VIEW* pView = (IGRAPHICS_VIEW*) mView;
736 BOOL isDarkMode = [[[pView effectiveAppearance] name] isEqualToString: (NSAppearanceNameDarkAqua)];
737 return isDarkMode ? EUIAppearance::Dark : EUIAppearance::Light;
741 return EUIAppearance::Light;
744void IGraphicsMac::ActivateGLContext()
746 IGRAPHICS_VIEW* pView = (IGRAPHICS_VIEW*) mView;
747 [pView activateGLContext];
750void IGraphicsMac::DeactivateGLContext()
752 IGRAPHICS_VIEW* pView = (IGRAPHICS_VIEW*) mView;
753 [pView deactivateGLContext];
756#if defined IGRAPHICS_NANOVG
757 #include "IGraphicsNanoVG.cpp"
758#elif defined IGRAPHICS_SKIA
759 #include "IGraphicsSkia.cpp"
761 #error Either NO_IGRAPHICS or one and only one choice of graphics library must be defined!
This file contains the base IControl implementation, along with some base classes for specific types ...
The lowest level base class of an IGraphics control.
An editor delegate base class that uses IGraphics for the UI.
virtual ECursor SetMouseCursor(ECursor cursorType=ECursor::ARROW)
Sets the mouse cursor to one of ECursor (implementations should return the result of the base impleme...
Used to manage color data, independent of draw class/platform.
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,...