Blender V5.3
GHOST_SystemCocoa.mm
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
6
10#include "GHOST_EventKey.hh"
11#include "GHOST_EventString.hh"
13#include "GHOST_EventWheel.hh"
14#include "GHOST_TimerManager.hh"
15#include "GHOST_TimerTask.hh"
16#include "GHOST_WindowCocoa.hh"
18
19/* Don't generate OpenGL deprecation warning. This is a known thing, and is not something easily
20 * solvable in a short term. */
21#ifdef __clang__
22# pragma clang diagnostic ignored "-Wdeprecated-declarations"
23#endif
24
25#ifdef WITH_METAL_BACKEND
26# include "GHOST_ContextMTL.hh"
27#endif
28
29#ifdef WITH_VULKAN_BACKEND
30# include "GHOST_ContextVK.hh"
31#endif
32
33#ifdef WITH_INPUT_NDOF
35#endif
36
37/* For the currently not ported to Cocoa keyboard layout functions (64bit & 10.6 compatible) */
38#include <Carbon/Carbon.h>
39#include <sys/time.h>
40
41/* --------------------------------------------------------------------
42 * Keymaps, mouse converters.
43 */
44
45static GHOST_TButton convertButton(int button)
46{
47 switch (button) {
48 case 0:
50 case 1:
52 case 2:
54 case 3:
56 case 4:
58 case 5:
60 case 6:
62 default:
64 }
65}
66
74static GHOST_TKey convertKey(int rawCode, unichar recvChar)
75{
76 // printf("\nrecvchar %c 0x%x",recvChar,recvChar);
77 switch (rawCode) {
78 /* Physical key-codes: (not used due to map changes in international keyboards). */
79#if 0
80 case kVK_ANSI_A: return GHOST_kKeyA;
81 case kVK_ANSI_B: return GHOST_kKeyB;
82 case kVK_ANSI_C: return GHOST_kKeyC;
83 case kVK_ANSI_D: return GHOST_kKeyD;
84 case kVK_ANSI_E: return GHOST_kKeyE;
85 case kVK_ANSI_F: return GHOST_kKeyF;
86 case kVK_ANSI_G: return GHOST_kKeyG;
87 case kVK_ANSI_H: return GHOST_kKeyH;
88 case kVK_ANSI_I: return GHOST_kKeyI;
89 case kVK_ANSI_J: return GHOST_kKeyJ;
90 case kVK_ANSI_K: return GHOST_kKeyK;
91 case kVK_ANSI_L: return GHOST_kKeyL;
92 case kVK_ANSI_M: return GHOST_kKeyM;
93 case kVK_ANSI_N: return GHOST_kKeyN;
94 case kVK_ANSI_O: return GHOST_kKeyO;
95 case kVK_ANSI_P: return GHOST_kKeyP;
96 case kVK_ANSI_Q: return GHOST_kKeyQ;
97 case kVK_ANSI_R: return GHOST_kKeyR;
98 case kVK_ANSI_S: return GHOST_kKeyS;
99 case kVK_ANSI_T: return GHOST_kKeyT;
100 case kVK_ANSI_U: return GHOST_kKeyU;
101 case kVK_ANSI_V: return GHOST_kKeyV;
102 case kVK_ANSI_W: return GHOST_kKeyW;
103 case kVK_ANSI_X: return GHOST_kKeyX;
104 case kVK_ANSI_Y: return GHOST_kKeyY;
105 case kVK_ANSI_Z: return GHOST_kKeyZ;
106#endif
107 /* Numbers keys: mapped to handle some international keyboard (e.g. French). */
108 case kVK_ANSI_1:
109 return GHOST_kKey1;
110 case kVK_ANSI_2:
111 return GHOST_kKey2;
112 case kVK_ANSI_3:
113 return GHOST_kKey3;
114 case kVK_ANSI_4:
115 return GHOST_kKey4;
116 case kVK_ANSI_5:
117 return GHOST_kKey5;
118 case kVK_ANSI_6:
119 return GHOST_kKey6;
120 case kVK_ANSI_7:
121 return GHOST_kKey7;
122 case kVK_ANSI_8:
123 return GHOST_kKey8;
124 case kVK_ANSI_9:
125 return GHOST_kKey9;
126 case kVK_ANSI_0:
127 return GHOST_kKey0;
128
129 case kVK_ANSI_Keypad0:
130 return GHOST_kKeyNumpad0;
131 case kVK_ANSI_Keypad1:
132 return GHOST_kKeyNumpad1;
133 case kVK_ANSI_Keypad2:
134 return GHOST_kKeyNumpad2;
135 case kVK_ANSI_Keypad3:
136 return GHOST_kKeyNumpad3;
137 case kVK_ANSI_Keypad4:
138 return GHOST_kKeyNumpad4;
139 case kVK_ANSI_Keypad5:
140 return GHOST_kKeyNumpad5;
141 case kVK_ANSI_Keypad6:
142 return GHOST_kKeyNumpad6;
143 case kVK_ANSI_Keypad7:
144 return GHOST_kKeyNumpad7;
145 case kVK_ANSI_Keypad8:
146 return GHOST_kKeyNumpad8;
147 case kVK_ANSI_Keypad9:
148 return GHOST_kKeyNumpad9;
149 case kVK_ANSI_KeypadDecimal:
151 case kVK_ANSI_KeypadEnter:
153 case kVK_ANSI_KeypadPlus:
155 case kVK_ANSI_KeypadMinus:
157 case kVK_ANSI_KeypadMultiply:
159 case kVK_ANSI_KeypadDivide:
161 case kVK_ANSI_KeypadClear:
162 return GHOST_kKeyUnknown;
163
164 case kVK_F1:
165 return GHOST_kKeyF1;
166 case kVK_F2:
167 return GHOST_kKeyF2;
168 case kVK_F3:
169 return GHOST_kKeyF3;
170 case kVK_F4:
171 return GHOST_kKeyF4;
172 case kVK_F5:
173 return GHOST_kKeyF5;
174 case kVK_F6:
175 return GHOST_kKeyF6;
176 case kVK_F7:
177 return GHOST_kKeyF7;
178 case kVK_F8:
179 return GHOST_kKeyF8;
180 case kVK_F9:
181 return GHOST_kKeyF9;
182 case kVK_F10:
183 return GHOST_kKeyF10;
184 case kVK_F11:
185 return GHOST_kKeyF11;
186 case kVK_F12:
187 return GHOST_kKeyF12;
188 case kVK_F13:
189 return GHOST_kKeyF13;
190 case kVK_F14:
191 return GHOST_kKeyF14;
192 case kVK_F15:
193 return GHOST_kKeyF15;
194 case kVK_F16:
195 return GHOST_kKeyF16;
196 case kVK_F17:
197 return GHOST_kKeyF17;
198 case kVK_F18:
199 return GHOST_kKeyF18;
200 case kVK_F19:
201 return GHOST_kKeyF19;
202 case kVK_F20:
203 return GHOST_kKeyF20;
204
205 case kVK_UpArrow:
206 return GHOST_kKeyUpArrow;
207 case kVK_DownArrow:
208 return GHOST_kKeyDownArrow;
209 case kVK_LeftArrow:
210 return GHOST_kKeyLeftArrow;
211 case kVK_RightArrow:
213
214 case kVK_Return:
215 return GHOST_kKeyEnter;
216 case kVK_Delete:
217 return GHOST_kKeyBackSpace;
218 case kVK_ForwardDelete:
219 return GHOST_kKeyDelete;
220 case kVK_Escape:
221 return GHOST_kKeyEsc;
222 case kVK_Tab:
223 return GHOST_kKeyTab;
224 case kVK_Space:
225 return GHOST_kKeySpace;
226
227 case kVK_Home:
228 return GHOST_kKeyHome;
229 case kVK_End:
230 return GHOST_kKeyEnd;
231 case kVK_PageUp:
232 return GHOST_kKeyUpPage;
233 case kVK_PageDown:
234 return GHOST_kKeyDownPage;
235#if 0
236 /* These constants with "ANSI" in the name are labeled according to the key position on an
237 * ANSI-standard US keyboard. Therefore they may not match the physical key label on other
238 * keyboard layouts. */
239 case kVK_ANSI_Minus: return GHOST_kKeyMinus;
240 case kVK_ANSI_Equal: return GHOST_kKeyEqual;
241 case kVK_ANSI_Comma: return GHOST_kKeyComma;
242 case kVK_ANSI_Period: return GHOST_kKeyPeriod;
243 case kVK_ANSI_Slash: return GHOST_kKeySlash;
244 case kVK_ANSI_Semicolon: return GHOST_kKeySemicolon;
245 case kVK_ANSI_Quote: return GHOST_kKeyQuote;
246 case kVK_ANSI_Backslash: return GHOST_kKeyBackslash;
247 case kVK_ANSI_LeftBracket: return GHOST_kKeyLeftBracket;
248 case kVK_ANSI_RightBracket: return GHOST_kKeyRightBracket;
249 case kVK_ANSI_Grave: return GHOST_kKeyAccentGrave;
250 case kVK_ISO_Section: return GHOST_kKeyUnknown;
251#endif
252 case kVK_VolumeUp:
253 case kVK_VolumeDown:
254 case kVK_Mute:
255 return GHOST_kKeyUnknown;
256
257 default: {
258 /* Alphanumerical or punctuation key that is remappable in international keyboards. */
259 if ((recvChar >= 'A') && (recvChar <= 'Z')) {
260 return (GHOST_TKey)(recvChar - 'A' + GHOST_kKeyA);
261 }
262
263 if ((recvChar >= 'a') && (recvChar <= 'z')) {
264 return (GHOST_TKey)(recvChar - 'a' + GHOST_kKeyA);
265 }
266 else {
267 /* Leopard and Snow Leopard 64bit compatible API. */
268 const TISInputSourceRef kbdTISHandle = TISCopyCurrentKeyboardLayoutInputSource();
269 /* The keyboard layout. */
270 const CFDataRef uchrHandle = static_cast<CFDataRef>(
271 TISGetInputSourceProperty(kbdTISHandle, kTISPropertyUnicodeKeyLayoutData));
272 CFRelease(kbdTISHandle);
273
274 /* Get actual character value of the "remappable" keys in international keyboards,
275 * if keyboard layout is not correctly reported (e.g. some non Apple keyboards in Tiger),
276 * then fall back on using the received #charactersIgnoringModifiers. */
277 if (uchrHandle) {
278 UInt32 deadKeyState = 0;
279 UniCharCount actualStrLength = 0;
280
281 UCKeyTranslate((UCKeyboardLayout *)CFDataGetBytePtr(uchrHandle),
282 rawCode,
283 kUCKeyActionDown,
284 0,
285 LMGetKbdType(),
286 kUCKeyTranslateNoDeadKeysMask,
287 &deadKeyState,
288 1,
289 &actualStrLength,
290 &recvChar);
291 }
292
293 switch (recvChar) {
294 case '-':
295 return GHOST_kKeyMinus;
296 case '+':
297 return GHOST_kKeyPlus;
298 case '=':
299 return GHOST_kKeyEqual;
300 case ',':
301 return GHOST_kKeyComma;
302 case '.':
303 return GHOST_kKeyPeriod;
304 case '/':
305 return GHOST_kKeySlash;
306 case ';':
307 return GHOST_kKeySemicolon;
308 case '\'':
309 return GHOST_kKeyQuote;
310 case '\\':
311 return GHOST_kKeyBackslash;
312 case '[':
314 case ']':
316 case '`':
317 case '<': /* The position of '`' is equivalent to this symbol in the French layout. */
319 default:
320 return GHOST_kKeyUnknown;
321 }
322 }
323 }
324 }
325 return GHOST_kKeyUnknown;
326}
327
328/* --------------------------------------------------------------------
329 * Utility functions.
330 */
331
332#define FIRSTFILEBUFLG 512
333static bool g_hasFirstFile = false;
335
336/* TODO: Need to investigate this.
337 * Function called too early in creator.c to have g_hasFirstFile == true */
339{
340 if (g_hasFirstFile) {
341 memcpy(buf, g_firstFileBuf, FIRSTFILEBUFLG);
342 buf[FIRSTFILEBUFLG - 1] = '\0';
343 return 1;
344 }
345 return 0;
346}
347
348/* --------------------------------------------------------------------
349 * Cocoa objects.
350 */
351
356@interface CocoaAppDelegate : NSObject <NSApplicationDelegate>
357
358@property(nonatomic, readonly, assign) GHOST_SystemCocoa *systemCocoa;
359
360- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)systemCocoa;
361- (void)dealloc;
362- (void)applicationDidFinishLaunching:(NSNotification *)aNotification;
363- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename;
364- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
365- (void)applicationWillTerminate:(NSNotification *)aNotification;
366- (void)applicationWillBecomeActive:(NSNotification *)aNotification;
367- (void)toggleFullScreen:(NSNotification *)notification;
368- (void)windowWillClose:(NSNotification *)notification;
369
370- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app;
371
372@end
373
374@implementation CocoaAppDelegate : NSObject
375
376@synthesize systemCocoa = system_cocoa_;
377
378- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)systemCocoa
379{
380 self = [super init];
381
382 if (self) {
383 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
384 [center addObserver:self
385 selector:@selector(windowWillClose:)
386 name:NSWindowWillCloseNotification
387 object:nil];
388 system_cocoa_ = systemCocoa;
389 }
390
391 return self;
392}
393
394- (void)dealloc
395{
396 @autoreleasepool {
397 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
398 [center removeObserver:self name:NSWindowWillCloseNotification object:nil];
399 [super dealloc];
400 }
401}
402
403- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
404{
405 if (system_cocoa_->window_focus_) {
406 /* Raise application to front, convenient when starting from the terminal
407 * and important for launching the animation player. we call this after the
408 * application finishes launching, as doing it earlier can make us end up
409 * with a front-most window but an inactive application. */
410 [NSApp activateIgnoringOtherApps:YES];
411 }
412
413 [NSEvent setMouseCoalescingEnabled:NO];
414}
415
416- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
417{
418 return system_cocoa_->handleOpenDocumentRequest(filename);
419}
420
421- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
422{
423 /* TODO: implement graceful termination through Cocoa mechanism
424 * to avoid session log off to be canceled. */
425 /* Note that Command-Q is already handled by key-handler. */
426 system_cocoa_->handleQuitRequest();
427 return NSTerminateCancel;
428}
429
430/* To avoid canceling a log off process, we must use Cocoa termination process
431 * And this function is the only chance to perform clean up
432 * So WM_exit needs to be called directly, as the event loop will never run before termination. */
433- (void)applicationWillTerminate:(NSNotification *)aNotification
434{
435#if 0
436 WM_exit(C, EXIT_SUCCESS);
437#endif
438}
439
440- (void)applicationWillBecomeActive:(NSNotification *)aNotification
441{
442 system_cocoa_->handleApplicationBecomeActiveEvent();
443}
444
445- (void)toggleFullScreen:(NSNotification *)notification
446{
447}
448
449/* The purpose of this function is to make sure closing "About" window does not
450 * leave Blender with no key windows. This is needed due to a custom event loop
451 * nature of the application: for some reason only using [NSApp run] will ensure
452 * correct behavior in this case.
453 *
454 * This is similar to an issue solved in SDL:
455 * https://bugzilla.libsdl.org/show_bug.cgi?id=1825
456 *
457 * Our solution is different, since we want Blender to keep track of what is
458 * the key window during normal operation. In order to do so we exploit the
459 * fact that "About" window is never in the orderedWindows array: we only force
460 * key window from here if the closing one is not in the orderedWindows. This
461 * saves lack of key windows when closing "About", but does not interfere with
462 * Blender's window manager when closing Blender's windows.
463 *
464 * NOTE: It also receives notifiers when menus are closed on macOS 14.
465 * Presumably it considers menus to be windows. */
466- (void)windowWillClose:(NSNotification *)notification
467{
468 @autoreleasepool {
469 NSWindow *closing_window = (NSWindow *)[notification object];
470
471 if (![closing_window isKeyWindow]) {
472 /* If the window wasn't key then its either none of the windows are key or another window
473 * is a key. The former situation is a bit strange, but probably forcing a key window is not
474 * something desirable. The latter situation is when we definitely do not want to change the
475 * key window.
476 *
477 * Ignoring non-key windows also avoids the code which ensures ordering below from running
478 * when the notifier is received for menus on macOS 14. */
479 return;
480 }
481
482 const NSInteger index = [[NSApp orderedWindows] indexOfObject:closing_window];
483 if (index != NSNotFound) {
484 return;
485 }
486 /* Find first suitable window from the current space. */
487 for (NSWindow *current_window in [NSApp orderedWindows]) {
488 if (current_window == closing_window) {
489 continue;
490 }
491 if (current_window.isOnActiveSpace && current_window.canBecomeKeyWindow) {
492 [current_window makeKeyAndOrderFront:nil];
493 return;
494 }
495 }
496 /* If that didn't find any windows, we try to find any suitable window of the application. */
497 for (NSNumber *window_number in [NSWindow windowNumbersWithOptions:0]) {
498 NSWindow *current_window = [NSApp windowWithWindowNumber:[window_number integerValue]];
499 if (current_window == closing_window) {
500 continue;
501 }
502 if ([current_window canBecomeKeyWindow]) {
503 [current_window makeKeyAndOrderFront:nil];
504 return;
505 }
506 }
507 }
508}
509
510/* Explicitly opt-in to the secure coding for the restorable state.
511 *
512 * This is something that only has affect on macOS 12+, and is implicitly
513 * enabled on macOS 14.
514 *
515 * For the details see
516 * https://sector7.computest.nl/post/2022-08-process-injection-breaking-all-macos-security-layers-with-a-single-vulnerability/
517 */
518- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app
519{
520 return YES;
521}
522
523@end
524
525/* --------------------------------------------------------------------
526 * Initialization / Finalization.
527 */
528
542
544{
545 /* The application delegate integrates the Cocoa application with the GHOST system.
546 *
547 * Since the GHOST system is about to be fully destroyed release the application delegate as
548 * well, so it does not point back to a freed system, forcing the delegate to be created with the
549 * new GHOST system in init(). */
550 @autoreleasepool {
551 CocoaAppDelegate *appDelegate = (CocoaAppDelegate *)[NSApp delegate];
552 if (appDelegate) {
553 [NSApp setDelegate:nil];
554 [appDelegate release];
555 }
556 }
557}
558
560{
562 if (success) {
563
564#ifdef WITH_INPUT_NDOF
565 ndof_manager_ = new GHOST_NDOFManagerCocoa(*this);
566#endif
567
568 // ProcessSerialNumber psn;
569
570 /* Carbon stuff to move window & menu to foreground. */
571#if 0
572 if (!GetCurrentProcess(&psn)) {
573 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
574 SetFrontProcess(&psn);
575 }
576#endif
577
578 @autoreleasepool {
579 [NSApplication sharedApplication]; /* initializes `NSApp`. */
580
581 if ([NSApp mainMenu] == nil) {
582 NSMenu *mainMenubar = [[NSMenu alloc] init];
583 NSMenuItem *menuItem;
584 NSMenu *windowMenu;
585 NSMenu *appMenu;
586
587 /* Create the application menu. */
588 appMenu = [[NSMenu alloc] initWithTitle:@"Blender"];
589
590 [appMenu addItemWithTitle:@"About Blender"
591 action:@selector(orderFrontStandardAboutPanel:)
592 keyEquivalent:@""];
593 [appMenu addItem:[NSMenuItem separatorItem]];
594
595 menuItem = [appMenu addItemWithTitle:@"Hide Blender"
596 action:@selector(hide:)
597 keyEquivalent:@"h"];
598 menuItem.keyEquivalentModifierMask = NSEventModifierFlagCommand;
599
600 menuItem = [appMenu addItemWithTitle:@"Hide Others"
601 action:@selector(hideOtherApplications:)
602 keyEquivalent:@"h"];
603 menuItem.keyEquivalentModifierMask = (NSEventModifierFlagOption |
604 NSEventModifierFlagCommand);
605
606 [appMenu addItemWithTitle:@"Show All"
607 action:@selector(unhideAllApplications:)
608 keyEquivalent:@""];
609
610 menuItem = [appMenu addItemWithTitle:@"Quit Blender"
611 action:@selector(terminate:)
612 keyEquivalent:@"q"];
613 menuItem.keyEquivalentModifierMask = NSEventModifierFlagCommand;
614
615 menuItem = [[NSMenuItem alloc] init];
616 menuItem.submenu = appMenu;
617
618 [mainMenubar addItem:menuItem];
619 [menuItem release];
620 [appMenu release];
621
622 /* Create the window menu. */
623 windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
624
625 menuItem = [windowMenu addItemWithTitle:@"Minimize"
626 action:@selector(performMiniaturize:)
627 keyEquivalent:@"m"];
628 menuItem.keyEquivalentModifierMask = NSEventModifierFlagCommand;
629
630 [windowMenu addItemWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""];
631
632 menuItem = [windowMenu addItemWithTitle:@"Enter Full Screen"
633 action:@selector(toggleFullScreen:)
634 keyEquivalent:@"f"];
635 menuItem.keyEquivalentModifierMask = NSEventModifierFlagControl |
636 NSEventModifierFlagCommand;
637
638 menuItem = [windowMenu addItemWithTitle:@"Close"
639 action:@selector(performClose:)
640 keyEquivalent:@"w"];
641 menuItem.keyEquivalentModifierMask = NSEventModifierFlagCommand;
642
643 menuItem = [[NSMenuItem alloc] init];
644 menuItem.submenu = windowMenu;
645
646 [mainMenubar addItem:menuItem];
647 [menuItem release];
648
649 [NSApp setMainMenu:mainMenubar];
650 [NSApp setWindowsMenu:windowMenu];
651 [windowMenu release];
652 }
653
654 if ([NSApp delegate] == nil) {
655 CocoaAppDelegate *appDelegate = [[CocoaAppDelegate alloc] initWithSystemCocoa:this];
656 [NSApp setDelegate:appDelegate];
657 }
658
659 /* AppKit provides automatic window tabbing. Blender is a single-tabbed
660 * application without a macOS tab bar, and should explicitly opt-out of this.
661 * This is also controlled by the macOS user default #NSWindowTabbingEnabled. */
662 NSWindow.allowsAutomaticWindowTabbing = NO;
663
664 if (background_mode_) {
665 /* Do not display the application in the Dock when started in background-mode,
666 * without which the app icon would bounce indefinitely. */
667 [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];
668 }
669
670 [NSApp finishLaunching];
671 }
672 }
673 return success;
674}
675
676/* --------------------------------------------------------------------
677 * Window management.
678 */
679
681{
682 /* For comparing to NSEvent timestamp, this particular API function matches. */
683 return (uint64_t)([[NSProcessInfo processInfo] systemUptime] * 1000);
684}
685
687{
688 @autoreleasepool {
689 return [[NSScreen screens] count];
690 }
691}
692
693void GHOST_SystemCocoa::getMainDisplayDimensions(uint32_t &width, uint32_t &height) const
694{
695 @autoreleasepool {
696 /* Get visible frame, that is frame excluding dock and top menu bar. */
697 const NSRect frame = [GHOST_WindowCocoa::getPrimaryScreen() visibleFrame];
698
699 /* Returns max window contents (excluding title bar...). */
700 const NSRect contentRect = [NSWindow
701 contentRectForFrameRect:frame
702 styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
703 NSWindowStyleMaskMiniaturizable)];
704
705 width = contentRect.size.width;
706 height = contentRect.size.height;
707 }
708}
709
710void GHOST_SystemCocoa::getAllDisplayDimensions(uint32_t &width, uint32_t &height) const
711{
712 /* TODO! */
713 getMainDisplayDimensions(width, height);
714}
715
717 int32_t left,
718 int32_t top,
719 uint32_t width,
720 uint32_t height,
722 GHOST_GPUSettings gpu_settings,
723 const bool /*exclusive*/,
724 const bool is_dialog,
725 const GHOST_IWindow *parent_window)
726{
727 const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings);
728 GHOST_IWindow *window = nullptr;
729 @autoreleasepool {
730 /* Get the available rect for including window contents. */
731 const NSRect primaryScreenFrame = [GHOST_WindowCocoa::getPrimaryScreen() visibleFrame];
732 const NSRect primaryScreenContentRect = [NSWindow
733 contentRectForFrameRect:primaryScreenFrame
734 styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
735 NSWindowStyleMaskMiniaturizable)];
736
737 const int32_t bottom = primaryScreenContentRect.size.height - top - height;
738
739 window = new GHOST_WindowCocoa(this,
740 title,
741 left,
742 bottom,
743 width,
744 height,
745 state,
746 gpu_settings.context_type,
747 context_params,
748 is_dialog,
749 (GHOST_WindowCocoa *)parent_window,
750 gpu_settings.preferred_device);
751
752 if (window->getValid()) {
753 /* Store the pointer to the window. */
754 GHOST_ASSERT(window_manager_, "window_manager_ not initialized");
755 window_manager_->addWindow(window);
757 /* Need to tell window manager the new window is the active one
758 * (Cocoa does not send the event activate upon window creation). */
759 pushEvent(
760 std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowActivate, window));
761 pushEvent(std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowSize, window));
762 }
763 else {
764 GHOST_PRINT("GHOST_SystemCocoa::createWindow(): window invalid\n");
765 delete window;
766 window = nullptr;
767 }
768 }
769 return window;
770}
771
778{
779 const GHOST_ContextParams context_params_offscreen =
781
782 switch (gpu_settings.context_type) {
783#ifdef WITH_VULKAN_BACKEND
784 case GHOST_kDrawingContextTypeVulkan: {
785 GHOST_Context *context = new GHOST_ContextVK(
786 context_params_offscreen, nullptr, 1, 2, gpu_settings.preferred_device);
787 if (context->initializeDrawingContext()) {
788 return context;
789 }
790 delete context;
791 return nullptr;
792 }
793#endif
794
795#ifdef WITH_METAL_BACKEND
796 case GHOST_kDrawingContextTypeMetal: {
797 GHOST_Context *context = new GHOST_ContextMTL(context_params_offscreen, nullptr, nullptr);
798 if (context->initializeDrawingContext()) {
799 return context;
800 }
801 delete context;
802 return nullptr;
803 }
804#endif
805
806 default:
807 /* Unsupported backend. */
808 return nullptr;
809 }
810}
811
818{
819 delete context;
820
821 return GHOST_kSuccess;
822}
823
825{
826 const NSPoint scr_co = NSMakePoint(x, y);
827
828 @autoreleasepool {
829 const int windowNumberAtPoint = [NSWindow windowNumberAtPoint:scr_co
830 belowWindowWithWindowNumber:0];
831 NSWindow *nswindow = [NSApp windowWithWindowNumber:windowNumberAtPoint];
832
833 if (nswindow == nil) {
834 return nil;
835 }
836
837 return window_manager_->getWindowAssociatedWithOSWindow((const void *)nswindow);
838 }
839}
840
845{
846 const NSPoint mouseLoc = [NSEvent mouseLocation];
847
848 /* Returns the mouse location in screen coordinates. */
849 x = int32_t(mouseLoc.x);
850 y = int32_t(mouseLoc.y);
851 return GHOST_kSuccess;
852}
853
854/* Private CoreGraphicsSPI used to read the Accessibility cursor scale factor.
855 * Available since macOS 10.7, but not in the public headers. */
856extern "C" {
857typedef int CGSConnectionID;
859CGError CGSGetCursorScale(CGSConnectionID connection, CGFloat *scale);
860}
861
863{
864 /* Apply the Accessibility pointer-size scale (1.0 .. 4.0) to a default base size.
865 *
866 * Take care, for hardware cursors this is already applied on-top of the cursor bitmap,
867 * there doesn't seem to be a way to express that the cursor data is pre-scaled.
868 * Therefore, a larger cursor will work but look blurry.
869 * Only use this for software cursors. */
870 const CGFloat default_size = 21.0;
871
872 CGFloat scale = 1.0;
873 if (CGSGetCursorScale(CGSMainConnectionID(), &scale) != kCGErrorSuccess || !(scale > 0.0)) {
874 scale = 1.0;
875 }
876 return lround(default_size * scale);
877}
878
883{
885 if (!window) {
886 return GHOST_kFailure;
887 }
888
889 /* Cursor and mouse dissociation placed here not to interfere with continuous grab
890 * (in cont. grab setMouseCursorPosition is directly called). */
891 CGAssociateMouseAndMouseCursorPosition(false);
893 CGAssociateMouseAndMouseCursorPosition(true);
894
895 /* Force mouse move event (not pushed by Cocoa). */
896 pushEvent(std::make_unique<GHOST_EventCursor>(
899
900 return GHOST_kSuccess;
901}
902
904{
905 @autoreleasepool {
906 NSColorSampler *sampler = [[NSColorSampler alloc] init];
907 __block BOOL selectCompleted = NO;
908 __block BOOL samplingSucceeded = NO;
909
910 [sampler showSamplerWithSelectionHandler:^(NSColor *selectedColor) {
911 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)),
912 dispatch_get_main_queue(),
913 ^{
914 if (selectedColor != nil) {
915 NSColor *rgbColor = [selectedColor
916 colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]];
917 if (rgbColor) {
918 r_color[0] = [rgbColor redComponent];
919 r_color[1] = [rgbColor greenComponent];
920 r_color[2] = [rgbColor blueComponent];
921 }
922 samplingSucceeded = YES;
923 }
924 selectCompleted = YES;
925 });
926 }];
927
928 while (!selectCompleted) {
929 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
930 beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
931 }
932
933 return samplingSucceeded ? GHOST_kSuccess : GHOST_kFailure;
934 }
935}
936
938{
939 float xf = float(x), yf = float(y);
941 if (!window) {
942 return GHOST_kFailure;
943 }
944
945 @autoreleasepool {
946 NSScreen *windowScreen = window->getScreen();
947 const NSRect screenRect = windowScreen.frame;
948
949 /* Set position relative to current screen. */
950 xf -= screenRect.origin.x;
951 yf -= screenRect.origin.y;
952
953 /* Quartz Display Services uses the old coordinates (top left origin). */
954 yf = screenRect.size.height - yf;
955
956 CGDisplayMoveCursorToPoint((CGDirectDisplayID)[[[windowScreen deviceDescription]
957 objectForKey:@"NSScreenNumber"] unsignedIntValue],
958 CGPointMake(xf, yf));
959
960 /* See https://stackoverflow.com/a/17559012. By default, hardware events
961 * will be suppressed for 500ms after a synthetic mouse event. For unknown
962 * reasons CGEventSourceSetLocalEventsSuppressionInterval does not work,
963 * however calling CGAssociateMouseAndMouseCursorPosition also removes the
964 * delay, even if this is undocumented. */
965 CGAssociateMouseAndMouseCursorPosition(true);
966 }
967 return GHOST_kSuccess;
968}
969
971{
972 keys.set(GHOST_kModifierKeyLeftOS, (modifier_mask_ & NSEventModifierFlagCommand) ? true : false);
973 keys.set(GHOST_kModifierKeyLeftAlt, (modifier_mask_ & NSEventModifierFlagOption) ? true : false);
975 (modifier_mask_ & NSEventModifierFlagShift) ? true : false);
977 (modifier_mask_ & NSEventModifierFlagControl) ? true : false);
978
979 return GHOST_kSuccess;
980}
981
983{
984 const UInt32 button_state = GetCurrentEventButtonState();
985
986 buttons.clear();
987 buttons.set(GHOST_kButtonMaskLeft, button_state & (1 << 0));
988 buttons.set(GHOST_kButtonMaskRight, button_state & (1 << 1));
989 buttons.set(GHOST_kButtonMaskMiddle, button_state & (1 << 2));
990 buttons.set(GHOST_kButtonMaskButton4, button_state & (1 << 3));
991 buttons.set(GHOST_kButtonMaskButton5, button_state & (1 << 4));
992 return GHOST_kSuccess;
993}
994
996{
999 /* NOTE: order the following flags as they they're declared in the source. */
1000 ~(
1001 /* Cocoa has no support for a primary selection clipboard. */
1003 /* Cocoa doesn't define a Hyper modifier key,
1004 * it's possible another modifier could be optionally used in it's place. */
1006 /* No support yet for dynamic cursor generation. */
1008}
1009
1010/* --------------------------------------------------------------------
1011 * Event handlers.
1012 */
1013
1017bool GHOST_SystemCocoa::processEvents(bool /*waitForEvent*/)
1018{
1019 bool anyProcessed = false;
1020 NSEvent *event;
1021
1022 /* TODO: implement timer? */
1023#if 0
1024 do {
1025 GHOST_TimerManager* timerMgr = getTimerManager();
1026
1027 if (waitForEvent) {
1028 uint64_t next = timerMgr->nextFireTime();
1029 double timeOut;
1030
1031 if (next == GHOST_kFireTimeNever) {
1032 timeOut = kEventDurationForever;
1033 }
1034 else {
1035 timeOut = (double)(next - getMilliSeconds())/1000.0;
1036 if (timeOut < 0.0) {
1037 timeOut = 0.0;
1038 }
1039 }
1040
1041 ::ReceiveNextEvent(0, nullptr, timeOut, false, &event);
1042 }
1043
1044 if (timerMgr->fireTimers(getMilliSeconds())) {
1045 anyProcessed = true;
1046 }
1047#endif
1048 do {
1049 @autoreleasepool {
1050 event = [NSApp nextEventMatchingMask:NSEventMaskAny
1051 untilDate:[NSDate distantPast]
1052 inMode:NSDefaultRunLoopMode
1053 dequeue:YES];
1054 if (event == nil) {
1055 break;
1056 }
1057
1058 anyProcessed = true;
1059
1060 /* Send event to NSApp to ensure Mac wide events are handled,
1061 * this will send events to BlenderWindow which will call back
1062 * to handleKeyEvent, handleMouseEvent and handleTabletEvent. */
1063
1064 /* There is on special exception for Control+(Shift)+Tab.
1065 * We do not get keyDown events delivered to the view because they are
1066 * special hotkeys to switch between views, so override directly */
1067
1068 if (event.type == NSEventTypeKeyDown && event.keyCode == kVK_Tab &&
1069 (event.modifierFlags & NSEventModifierFlagControl))
1070 {
1071 handleKeyEvent(event);
1072 }
1073 else {
1074 /* For some reason NSApp is swallowing the key up events when modifier
1075 * key is pressed, even if there seems to be no apparent reason to do
1076 * so, as a workaround we always handle these up events. */
1077 if (event.type == NSEventTypeKeyUp &&
1078 (event.modifierFlags & (NSEventModifierFlagCommand | NSEventModifierFlagOption)))
1079 {
1080 handleKeyEvent(event);
1081 }
1082
1083 [NSApp sendEvent:event];
1084 }
1085 }
1086 } while (event != nil);
1087#if 0
1088 } while (waitForEvent && !anyProcessed); /* Needed only for timer implementation. */
1089#endif
1090
1093 }
1094
1097 return true;
1098 }
1099
1101
1102 return anyProcessed;
1103}
1104
1105/* NOTE: called from #NSApplication delegate. */
1107{
1108 @autoreleasepool {
1109 for (GHOST_IWindow *iwindow : window_manager_->getWindows()) {
1110 GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)iwindow;
1111 if (window->isDialog()) {
1112 [window->getViewWindow() makeKeyAndOrderFront:nil];
1113 }
1114 }
1115
1116 /* Update the modifiers key mask, as its status may have changed when the application
1117 * was not active (that is when update events are sent to another application). */
1119
1120 if (!window) {
1122 return GHOST_kFailure;
1123 }
1124
1126
1127 const unsigned int modifiers = [[[NSApplication sharedApplication] currentEvent]
1128 modifierFlags];
1129
1130 if ((modifiers & NSEventModifierFlagShift) != (modifier_mask_ & NSEventModifierFlagShift)) {
1131 pushEvent(std::make_unique<GHOST_EventKey>(
1133 (modifiers & NSEventModifierFlagShift) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp,
1134 window,
1136 false));
1137 }
1138 if ((modifiers & NSEventModifierFlagControl) != (modifier_mask_ & NSEventModifierFlagControl))
1139 {
1140 pushEvent(std::make_unique<GHOST_EventKey>(
1142 (modifiers & NSEventModifierFlagControl) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp,
1143 window,
1145 false));
1146 }
1147 if ((modifiers & NSEventModifierFlagOption) != (modifier_mask_ & NSEventModifierFlagOption)) {
1148 pushEvent(std::make_unique<GHOST_EventKey>(
1150 (modifiers & NSEventModifierFlagOption) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp,
1151 window,
1153 false));
1154 }
1155 if ((modifiers & NSEventModifierFlagCommand) != (modifier_mask_ & NSEventModifierFlagCommand))
1156 {
1157 pushEvent(std::make_unique<GHOST_EventKey>(
1159 (modifiers & NSEventModifierFlagCommand) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp,
1160 window,
1162 false));
1163 }
1164
1165 modifier_mask_ = modifiers;
1166
1168 }
1169 return GHOST_kSuccess;
1170}
1171
1173{
1174 for (GHOST_IWindow *iwindow : window_manager_->getWindows()) {
1175 GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)iwindow;
1176 if (window->isDialog()) {
1177 return true;
1178 }
1179 }
1180 return false;
1181}
1182
1187
1188/* NOTE: called from #NSWindow delegate. */
1190 GHOST_WindowCocoa *window)
1191{
1192 if (!validWindow(window)) {
1193 return GHOST_kFailure;
1194 }
1195 switch (eventType) {
1197 pushEvent(std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowClose, window));
1198 break;
1201 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
1202 pushEvent(
1203 std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowActivate, window));
1204 break;
1207 pushEvent(
1208 std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowDeactivate, window));
1209 break;
1211 if (native_pixel_) {
1212 window->setNativePixelSize();
1213 pushEvent(std::make_unique<GHOST_Event>(
1215 }
1216 pushEvent(
1217 std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowUpdate, window));
1218 break;
1220 pushEvent(std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowMove, window));
1221 break;
1224 /* Enforce only one resize message per event loop
1225 * (coalescing all the live resize messages). */
1226 window->updateDrawingSize();
1227 window->updateDrawingContext();
1228 pushEvent(
1229 std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowSize, window));
1230 /* Mouse up event is trapped by the resizing event loop,
1231 * so send it anyway to the window manager. */
1232 pushEvent(std::make_unique<GHOST_EventButton>(getMilliSeconds(),
1234 window,
1236 GHOST_TABLET_DATA_NONE));
1237 // ignore_window_sized_messages_ = true;
1238 }
1239 break;
1241 window->updateDrawingSize();
1242
1243 if (native_pixel_) {
1244 window->setNativePixelSize();
1245 pushEvent(std::make_unique<GHOST_Event>(
1247 }
1248
1249 default:
1250 return GHOST_kFailure;
1251 break;
1252 }
1253
1255 return GHOST_kSuccess;
1256}
1257
1263static NSSize getNSImagePixelSize(NSImage *image)
1264{
1265 /* Assuming the NSImage instance only contains one single image. */
1266 @autoreleasepool {
1267 NSImageRep *imageRepresentation = [[image representations] firstObject];
1268 return NSMakeSize(imageRepresentation.pixelsWide, imageRepresentation.pixelsHigh);
1269 }
1270}
1271
1278{
1279 const NSSize imageSize = getNSImagePixelSize(image);
1282
1283 if (!ibuf) {
1284 return nullptr;
1285 }
1286
1287 @autoreleasepool {
1288 NSBitmapImageRep *bitmapImage = nil;
1289 for (NSImageRep *representation in [image representations]) {
1290 if ([representation isKindOfClass:[NSBitmapImageRep class]]) {
1291 bitmapImage = (NSBitmapImageRep *)representation;
1292 break;
1293 }
1294 }
1295
1296 if (bitmapImage == nil || bitmapImage.bitsPerPixel != 32 || bitmapImage.isPlanar ||
1297 bitmapImage.bitmapFormat & (NSBitmapFormatAlphaFirst | NSBitmapFormatFloatingPointSamples))
1298 {
1299 return nullptr;
1300 }
1301
1302 uint8_t *ibuf_data = ibuf->byte_data_for_write();
1303 uint8_t *bmp_data = (uint8_t *)bitmapImage.bitmapData;
1304
1305 /* Vertical Flip. */
1306 for (int y = 0; y < imageSize.height; y++) {
1307 const int row_byte_count = 4 * imageSize.width;
1308 const int ibuf_off = (imageSize.height - y - 1) * row_byte_count;
1309 const int bmp_off = y * row_byte_count;
1310 memcpy(ibuf_data + ibuf_off, bmp_data + bmp_off, row_byte_count);
1311 }
1312 }
1313
1314 return ibuf;
1315}
1316
1317/* NOTE: called from #NSWindow subclass. */
1319 GHOST_TDragnDropTypes draggedObjectType,
1320 GHOST_WindowCocoa *window,
1321 int mouseX,
1322 int mouseY,
1323 void *data)
1324{
1325 if (!validWindow(window)) {
1326 return GHOST_kFailure;
1327 }
1328 switch (eventType) {
1332 window->clientToScreenIntern(mouseX, mouseY, mouseX, mouseY);
1333 pushEvent(std::make_unique<GHOST_EventDragnDrop>(
1334 getMilliSeconds(), eventType, draggedObjectType, window, mouseX, mouseY, nullptr));
1335 break;
1336
1338 if (!data) {
1339 return GHOST_kFailure;
1340 }
1341
1342 GHOST_TDragnDropDataPtr eventData;
1343 @autoreleasepool {
1344 switch (draggedObjectType) {
1346 NSArray *droppedArray = (NSArray *)data;
1347
1348 GHOST_TStringArray *strArray = (GHOST_TStringArray *)malloc(
1349 sizeof(GHOST_TStringArray));
1350 if (!strArray) {
1351 return GHOST_kFailure;
1352 }
1353
1354 strArray->count = droppedArray.count;
1355 if (strArray->count == 0) {
1356 free(strArray);
1357 return GHOST_kFailure;
1358 }
1359
1360 strArray->strings = (uint8_t **)malloc(strArray->count * sizeof(uint8_t *));
1361
1362 for (int i = 0; i < strArray->count; i++) {
1363 NSString *droppedStr = [droppedArray objectAtIndex:i];
1364 const size_t pastedTextSize = [droppedStr
1365 lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1366 uint8_t *temp_buff = (uint8_t *)malloc(pastedTextSize + 1);
1367
1368 if (!temp_buff) {
1369 strArray->count = i;
1370 break;
1371 }
1372
1373 memcpy(temp_buff,
1374 [droppedStr cStringUsingEncoding:NSUTF8StringEncoding],
1375 pastedTextSize);
1376 temp_buff[pastedTextSize] = '\0';
1377
1378 strArray->strings[i] = temp_buff;
1379 }
1380
1381 eventData = static_cast<GHOST_TDragnDropDataPtr>(strArray);
1382 break;
1383 }
1385 NSString *droppedStr = (NSString *)data;
1386 const size_t pastedTextSize = [droppedStr
1387 lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1388 uint8_t *temp_buff = (uint8_t *)malloc(pastedTextSize + 1);
1389
1390 if (temp_buff == nullptr) {
1391 return GHOST_kFailure;
1392 }
1393
1394 memcpy(
1395 temp_buff, [droppedStr cStringUsingEncoding:NSUTF8StringEncoding], pastedTextSize);
1396 temp_buff[pastedTextSize] = '\0';
1397
1398 eventData = static_cast<GHOST_TDragnDropDataPtr>(temp_buff);
1399 break;
1400 }
1402 NSImage *droppedImg = static_cast<NSImage *>(data);
1403 blender::ImBuf *ibuf = NSImageToImBuf(droppedImg);
1404
1405 eventData = static_cast<GHOST_TDragnDropDataPtr>(ibuf);
1406
1407 [droppedImg release];
1408 break;
1409 }
1410 default:
1411 return GHOST_kFailure;
1412 break;
1413 }
1414 }
1415
1416 window->clientToScreenIntern(mouseX, mouseY, mouseX, mouseY);
1417 pushEvent(std::make_unique<GHOST_EventDragnDrop>(
1418 getMilliSeconds(), eventType, draggedObjectType, window, mouseX, mouseY, eventData));
1419
1420 break;
1421 }
1422 default:
1423 return GHOST_kFailure;
1424 }
1426 return GHOST_kSuccess;
1427}
1428
1430{
1432
1433 /* Discard quit event if we are in cursor grab sequence. */
1434 if (window && window->getCursorGrabModeIsWarp()) {
1435 return;
1436 }
1437
1438 /* Push the event to Blender so it can open a dialog if needed. */
1439 pushEvent(std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventQuitRequest, window));
1441}
1442
1444{
1445 NSString *filepath = (NSString *)filepathStr;
1446
1447 /* Check for blender opened windows and make the front-most key.
1448 * In case blender is minimized, opened on another desktop space,
1449 * or in full-screen mode. */
1450 @autoreleasepool {
1451 NSArray *windowsList = [NSApp orderedWindows];
1452 if ([windowsList count]) {
1453 [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
1454 }
1455
1456 GHOST_Window *window = window_manager_->getWindows().empty() ?
1457 nullptr :
1459
1460 if (!window) {
1461 return NO;
1462 }
1463
1464 /* Discard event if we are in cursor grab sequence,
1465 * it'll lead to "stuck cursor" situation if the alert panel is raised. */
1466 if (window && window->getCursorGrabModeIsWarp()) {
1467 return NO;
1468 }
1469
1470 const size_t filenameTextSize = [filepath lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1471 char *temp_buff = (char *)malloc(filenameTextSize + 1);
1472
1473 if (temp_buff == nullptr) {
1474 return GHOST_kFailure;
1475 }
1476
1477 memcpy(temp_buff, [filepath cStringUsingEncoding:NSUTF8StringEncoding], filenameTextSize);
1478 temp_buff[filenameTextSize] = '\0';
1479
1480 pushEvent(std::make_unique<GHOST_EventString>(getMilliSeconds(),
1482 window,
1483 static_cast<GHOST_TEventDataPtr>(temp_buff)));
1484 }
1485 return YES;
1486}
1487
1489{
1490 NSEvent *event = (NSEvent *)eventPtr;
1491
1493 (const void *)event.window);
1494 if (!window) {
1495 // printf("\nW failure for event 0x%x",event.type);
1496 return GHOST_kFailure;
1497 }
1498
1499 GHOST_TabletData &ct = ((GHOST_WindowCocoa *)window)->GetCocoaTabletData();
1500
1501 switch (eventType) {
1502 case NSEventTypeTabletPoint:
1503 /* workaround 2 corner-cases:
1504 * 1. if event.isEnteringProximity was not triggered since program-start.
1505 * 2. device is not sending event.pointingDeviceType, due no eraser. */
1506 if (ct.Active == GHOST_kTabletModeNone) {
1508 }
1509
1510 ct.Pressure = event.pressure;
1511 /* Range: -1 (left) to 1 (right). */
1512 ct.Xtilt = event.tilt.x;
1513 /* On macOS, the y tilt behavior is inverted from what we expect: negative
1514 * meaning a tilt toward the user, positive meaning away from the user.
1515 * Convert to what Blender expects: -1.0 (away from user) to +1.0 (toward user). */
1516 ct.Ytilt = -event.tilt.y;
1517 break;
1518
1519 case NSEventTypeTabletProximity:
1520 /* Reset tablet data when device enters proximity or leaves. */
1521 ct = GHOST_TABLET_DATA_NONE;
1522 if (event.isEnteringProximity) {
1523 /* Pointer is entering tablet area proximity. */
1524 switch (event.pointingDeviceType) {
1525 case NSPointingDeviceTypePen:
1527 break;
1528 case NSPointingDeviceTypeEraser:
1530 break;
1531 case NSPointingDeviceTypeCursor:
1532 case NSPointingDeviceTypeUnknown:
1533 default:
1534 break;
1535 }
1536 }
1537 break;
1538
1539 default:
1540 GHOST_ASSERT(FALSE, "GHOST_SystemCocoa::handleTabletEvent : unknown event received");
1541 return GHOST_kFailure;
1542 break;
1543 }
1544 return GHOST_kSuccess;
1545}
1546
1548{
1549 NSEvent *event = (NSEvent *)eventPtr;
1550
1551 switch (event.subtype) {
1552 case NSEventSubtypeTabletPoint:
1553 handleTabletEvent(eventPtr, NSEventTypeTabletPoint);
1554 return true;
1555 case NSEventSubtypeTabletProximity:
1556 handleTabletEvent(eventPtr, NSEventTypeTabletProximity);
1557 return true;
1558 default:
1559 /* No tablet event included: do nothing. */
1560 return false;
1561 }
1562}
1563
1565{
1566 NSEvent *event = (NSEvent *)eventPtr;
1567
1568 /* event.window returns other windows if mouse-over, that's OSX input standard
1569 * however, if mouse exits window(s), the windows become inactive, until you click.
1570 * We then fall back to the active window from ghost. */
1572 ->getWindowAssociatedWithOSWindow((const void *)event.window);
1573 if (!window) {
1575 if (!window) {
1576 // printf("\nW failure for event 0x%x", event.type);
1577 return GHOST_kFailure;
1578 }
1579 }
1580
1581 switch (event.type) {
1582 case NSEventTypeLeftMouseDown:
1583 handleTabletEvent(event); /* Update window tablet state to be included in event. */
1584 pushEvent(std::make_unique<GHOST_EventButton>(event.timestamp * 1000,
1586 window,
1588 window->GetCocoaTabletData()));
1589 break;
1590 case NSEventTypeRightMouseDown:
1591 handleTabletEvent(event); /* Update window tablet state to be included in event. */
1592 pushEvent(std::make_unique<GHOST_EventButton>(event.timestamp * 1000,
1594 window,
1596 window->GetCocoaTabletData()));
1597 break;
1598 case NSEventTypeOtherMouseDown:
1599 handleTabletEvent(event); /* Handle tablet events combined with mouse events. */
1600 pushEvent(std::make_unique<GHOST_EventButton>(event.timestamp * 1000,
1602 window,
1603 convertButton(event.buttonNumber),
1604 window->GetCocoaTabletData()));
1605 break;
1606 case NSEventTypeLeftMouseUp:
1607 handleTabletEvent(event); /* Update window tablet state to be included in event. */
1608 pushEvent(std::make_unique<GHOST_EventButton>(event.timestamp * 1000,
1610 window,
1612 window->GetCocoaTabletData()));
1613 break;
1614 case NSEventTypeRightMouseUp:
1615 handleTabletEvent(event); /* Update window tablet state to be included in event. */
1616 pushEvent(std::make_unique<GHOST_EventButton>(event.timestamp * 1000,
1618 window,
1620 window->GetCocoaTabletData()));
1621 break;
1622 case NSEventTypeOtherMouseUp:
1623 handleTabletEvent(event); /* Update window tablet state to be included in event. */
1624 pushEvent(std::make_unique<GHOST_EventButton>(event.timestamp * 1000,
1626 window,
1627 convertButton(event.buttonNumber),
1628 window->GetCocoaTabletData()));
1629 break;
1630 case NSEventTypeLeftMouseDragged:
1631 case NSEventTypeRightMouseDragged:
1632 case NSEventTypeOtherMouseDragged:
1633 handleTabletEvent(event); /* Update window tablet state to be included in event. */
1634
1635 case NSEventTypeMouseMoved: {
1636 /* TODO: CHECK IF THIS IS A TABLET EVENT */
1637 bool is_tablet = false;
1638
1639 if (window->getCursorGrabModeIsWarp() && !is_tablet) {
1640 /* Wrap cursor at area/window boundaries. */
1641 GHOST_Rect bounds;
1642 if (window->getCursorGrabBounds(bounds) == GHOST_kFailure) {
1643 /* Fall back to window bounds. */
1644 window->getClientBounds(bounds);
1645 }
1646
1647 GHOST_Rect corrected_bounds;
1648 /* Wrapping bounds are in window local coordinates, using GHOST (top-left) origin. */
1649 if (window->getCursorGrabMode() == GHOST_kGrabHide) {
1650 /* If the cursor is hidden, use the entire window. */
1651 corrected_bounds.t_ = 0;
1652 corrected_bounds.l_ = 0;
1653
1654 NSWindow *cocoa_window = (NSWindow *)window->getOSWindow();
1655 const NSSize frame_size = cocoa_window.frame.size;
1656
1657 corrected_bounds.b_ = frame_size.height;
1658 corrected_bounds.r_ = frame_size.width;
1659 }
1660 else {
1661 /* If the cursor is visible, use custom grab bounds provided in Cocoa bottom-left origin.
1662 * Flip them to use a GHOST top-left origin. */
1663 GHOST_Rect window_bounds;
1664 window->getClientBounds(window_bounds);
1665 window->screenToClient(bounds.l_, bounds.b_, corrected_bounds.l_, corrected_bounds.t_);
1666 window->screenToClient(bounds.r_, bounds.t_, corrected_bounds.r_, corrected_bounds.b_);
1667
1668 corrected_bounds.b_ = (window_bounds.b_ - window_bounds.t_) - corrected_bounds.b_;
1669 corrected_bounds.t_ = (window_bounds.b_ - window_bounds.t_) - corrected_bounds.t_;
1670 }
1671
1672 /* Clip the grabbing bounds to the current monitor bounds to prevent the cursor from
1673 * getting stuck at the edge of the screen. First compute the visible window frame: */
1674 NSWindow *cocoa_window = (NSWindow *)window->getOSWindow();
1675 NSRect screen_visible_frame = window->getScreen().visibleFrame;
1676 NSRect window_visible_frame = NSIntersectionRect(cocoa_window.frame, screen_visible_frame);
1677 NSRect local_visible_frame = [cocoa_window convertRectFromScreen:window_visible_frame];
1678
1679 GHOST_Rect visible_rect;
1680 visible_rect.l_ = local_visible_frame.origin.x;
1681 visible_rect.t_ = local_visible_frame.origin.y;
1682 visible_rect.r_ = local_visible_frame.origin.x + local_visible_frame.size.width;
1683 visible_rect.b_ = local_visible_frame.origin.y + local_visible_frame.size.height;
1684
1685 /* Then clip the corrected bound using the visible window rect. */
1686 visible_rect.clip(corrected_bounds);
1687
1688 /* Get accumulation from previous mouse warps. */
1689 int32_t x_accum, y_accum;
1690 window->getCursorGrabAccum(x_accum, y_accum);
1691
1692 /* Get the current software mouse pointer location, theoretically unaffected by pending
1693 * events that may still be referring to a location before warping. In practice extra
1694 * logic still need to be used to prevent interferences from stale events. */
1695 const NSPoint mousePos = event.window.mouseLocationOutsideOfEventStream;
1696 /* Casting. */
1697 const int32_t x_mouse = mousePos.x;
1698 const int32_t y_mouse = mousePos.y;
1699
1700 /* Warp mouse cursor if needed. */
1701 int32_t warped_x_mouse = x_mouse;
1702 int32_t warped_y_mouse = y_mouse;
1703 corrected_bounds.wrapPoint(warped_x_mouse, warped_y_mouse, 4, window->getCursorGrabAxis());
1704
1705 /* Set new cursor position. */
1706 if (x_mouse != warped_x_mouse || y_mouse != warped_y_mouse) {
1707 /* After warping, we can still receive unwrapped mouse that occurred slightly before or
1708 * after the current event at close timestamps, causing the wrapping to be applied a
1709 * second time, leading to a visual jump. Ignore these events by returning early.
1710 * Using a small empirical future covering threshold, see PR #148158 for details. */
1711 const NSTimeInterval timestamp = event.timestamp;
1712 const NSTimeInterval stale_event_threshold = 0.003;
1713 if (timestamp < (last_warp_timestamp_ + stale_event_threshold)) {
1714 break;
1715 }
1716
1717 int32_t warped_x, warped_y;
1718 window->clientToScreenIntern(warped_x_mouse, warped_y_mouse, warped_x, warped_y);
1719 setMouseCursorPosition(warped_x, warped_y); /* wrap */
1720 window->setCursorGrabAccum(x_accum + (x_mouse - warped_x_mouse),
1721 y_accum + (y_mouse - warped_y_mouse));
1722
1723 /* This is the current time that matches NSEvent timestamp. */
1724 last_warp_timestamp_ = [[NSProcessInfo processInfo] systemUptime];
1725 }
1726
1727 /* Generate event. */
1728 int32_t x, y;
1729 window->clientToScreenIntern(x_mouse + x_accum, y_mouse + y_accum, x, y);
1730 pushEvent(std::make_unique<GHOST_EventCursor>(event.timestamp * 1000,
1732 window,
1733 x,
1734 y,
1735 window->GetCocoaTabletData()));
1736 }
1737 else {
1738 /* Normal cursor operation: send mouse position in window. */
1739 const NSPoint mousePos = event.locationInWindow;
1740 int32_t x, y;
1741
1742 window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
1743 pushEvent(std::make_unique<GHOST_EventCursor>(event.timestamp * 1000,
1745 window,
1746 x,
1747 y,
1748 window->GetCocoaTabletData()));
1749 }
1750 break;
1751 }
1752 case NSEventTypeScrollWheel: {
1753 const NSEventPhase momentumPhase = event.momentumPhase;
1754 const NSEventPhase phase = event.phase;
1755
1756 /* when pressing a key while momentum scrolling continues after
1757 * lifting fingers off the trackpad, the action can unexpectedly
1758 * change from e.g. scrolling to zooming. this works around the
1759 * issue by ignoring momentum scroll after a key press */
1760 if (momentumPhase) {
1762 break;
1763 }
1764 }
1765 else {
1767 }
1768
1769 /* we assume phases are only set for gestures from trackpad or magic
1770 * mouse events. note that using tablet at the same time may not work
1771 * since this is a static variable */
1772 if (phase == NSEventPhaseBegan && multitouch_gestures_) {
1773 multi_touch_scroll_ = true;
1774 }
1775 else if (phase == NSEventPhaseEnded) {
1776 multi_touch_scroll_ = false;
1777 }
1778
1779 /* Standard scroll-wheel case, if no swiping happened,
1780 * and no momentum (kinetic scroll) works. */
1781 if (!multi_touch_scroll_ && momentumPhase == NSEventPhaseNone) {
1782 /* Horizontal scrolling. */
1783 if (event.deltaX != 0.0) {
1784 const int32_t delta = event.deltaX > 0.0 ? 1 : -1;
1785 /* On macOS, shift + vertical scroll events will be transformed into shift + horizontal
1786 * events by the OS input layer. Counteract this behavior by transforming them back into
1787 * shift + vertical scroll event. See PR #148122 for more details. */
1788 const GHOST_TEventWheelAxis direction = modifier_mask_ & NSEventModifierFlagShift ?
1791
1792 pushEvent(std::make_unique<GHOST_EventWheel>(
1793 event.timestamp * 1000, window, direction, delta));
1794 }
1795 /* Vertical scrolling. */
1796 if (event.deltaY != 0.0) {
1797 const int32_t delta = event.deltaY > 0.0 ? 1 : -1;
1798 pushEvent(std::make_unique<GHOST_EventWheel>(
1799 event.timestamp * 1000, window, GHOST_kEventWheelAxisVertical, delta));
1800 }
1801 }
1802 else {
1803 const NSPoint mousePos = event.locationInWindow;
1804
1805 /* with 10.7 nice scrolling deltas are supported */
1806 double dx = event.scrollingDeltaX;
1807 double dy = event.scrollingDeltaY;
1808
1809 /* However, WACOM tablet (intuos5) needs old deltas,
1810 * it then has momentum and phase at zero. */
1811 if (phase == NSEventPhaseNone && momentumPhase == NSEventPhaseNone) {
1812 dx = event.deltaX;
1813 dy = event.deltaY;
1814 }
1815
1816 int32_t x, y;
1817 window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
1818
1819 BlenderWindow *view_window = (BlenderWindow *)window->getOSWindow();
1820
1821 @autoreleasepool {
1822 const NSPoint delta = [[view_window contentView]
1823 convertPointToBacking:NSMakePoint(dx, dy)];
1824 pushEvent(std::make_unique<GHOST_EventTrackpad>(event.timestamp * 1000,
1825 window,
1827 x,
1828 y,
1829 delta.x,
1830 delta.y,
1831 event.isDirectionInvertedFromDevice));
1832 }
1833 }
1834 break;
1835 }
1836 case NSEventTypeMagnify: {
1837 const NSPoint mousePos = event.locationInWindow;
1838 int32_t x, y;
1839 window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
1840 pushEvent(std::make_unique<GHOST_EventTrackpad>(event.timestamp * 1000,
1841 window,
1843 x,
1844 y,
1845 event.magnification * 125.0 + 0.1,
1846 0,
1847 false));
1848 break;
1849 }
1850 case NSEventTypeSmartMagnify: {
1851 const NSPoint mousePos = event.locationInWindow;
1852 int32_t x, y;
1853 window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
1854 pushEvent(std::make_unique<GHOST_EventTrackpad>(
1855 event.timestamp * 1000, window, GHOST_kTrackpadEventSmartMagnify, x, y, 0, 0, false));
1856 break;
1857 }
1858 case NSEventTypeRotate: {
1859 const NSPoint mousePos = event.locationInWindow;
1860 int32_t x, y;
1861 window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
1862 pushEvent(std::make_unique<GHOST_EventTrackpad>(event.timestamp * 1000,
1863 window,
1865 x,
1866 y,
1867 event.rotation * -5.0,
1868 0,
1869 false));
1870 }
1871 default:
1872 return GHOST_kFailure;
1873 break;
1874 }
1875 return GHOST_kSuccess;
1876}
1877
1879{
1880 NSEvent *event = (NSEvent *)eventPtr;
1882 (const void *)event.window);
1883
1884 if (!window) {
1885 // printf("\nW failure for event 0x%x",event.type);
1886 return GHOST_kFailure;
1887 }
1888
1889 switch (event.type) {
1890 case NSEventTypeKeyDown:
1891 case NSEventTypeKeyUp: {
1892 /* Returns an empty string for dead keys. */
1893 GHOST_TKey keyCode;
1894 char utf8_buf[6] = {'\0'};
1895
1896 @autoreleasepool {
1897 NSString *charsIgnoringModifiers = event.charactersIgnoringModifiers;
1898 if (charsIgnoringModifiers.length > 0) {
1899 keyCode = convertKey(event.keyCode, [charsIgnoringModifiers characterAtIndex:0]);
1900 }
1901 else {
1902 keyCode = convertKey(event.keyCode, 0);
1903 }
1904
1905 NSString *characters = event.characters;
1906 if ([characters length] > 0) {
1907 NSData *convertedCharacters = [characters dataUsingEncoding:NSUTF8StringEncoding];
1908
1909 for (int x = 0; x < convertedCharacters.length; x++) {
1910 utf8_buf[x] = ((char *)convertedCharacters.bytes)[x];
1911 }
1912 }
1913 }
1914
1915 /* Arrow keys should not have UTF8. */
1916 if ((keyCode >= GHOST_kKeyLeftArrow) && (keyCode <= GHOST_kKeyDownArrow)) {
1917 utf8_buf[0] = '\0';
1918 }
1919
1920 /* F-keys should not have UTF8. */
1921 if ((keyCode >= GHOST_kKeyF1) && (keyCode <= GHOST_kKeyF20)) {
1922 utf8_buf[0] = '\0';
1923 }
1924
1925 /* no text with command key pressed */
1926 if (modifier_mask_ & NSEventModifierFlagCommand) {
1927 utf8_buf[0] = '\0';
1928 }
1929
1930 if ((keyCode == GHOST_kKeyQ) && (modifier_mask_ & NSEventModifierFlagCommand)) {
1931 break; /* Command-Q is directly handled by Cocoa. */
1932 }
1933
1934 if (event.type == NSEventTypeKeyDown) {
1935 pushEvent(std::make_unique<GHOST_EventKey>(event.timestamp * 1000,
1937 window,
1938 keyCode,
1939 event.isARepeat,
1940 utf8_buf));
1941#if 0
1942 printf("Key down rawCode=0x%x charsIgnoringModifiers=%c keyCode=%u utf8=%s\n",
1943 event.keyCode,
1944 charsIgnoringModifiers.length > 0 ? [charsIgnoringModifiers characterAtIndex:0] :
1945 ' ',
1946 keyCode,
1947 utf8_buf);
1948#endif
1949 }
1950 else {
1951 pushEvent(std::make_unique<GHOST_EventKey>(
1952 event.timestamp * 1000, GHOST_kEventKeyUp, window, keyCode, false, nullptr));
1953#if 0
1954 printf("Key up rawCode=0x%x charsIgnoringModifiers=%c keyCode=%u utf8=%s\n",
1955 event.keyCode,
1956 charsIgnoringModifiers.length > 0 ? [charsIgnoringModifiers characterAtIndex:0] :
1957 ' ',
1958 keyCode,
1959 utf8_buf);
1960#endif
1961 }
1963 break;
1964 }
1965 case NSEventTypeFlagsChanged: {
1966 const unsigned int modifiers = event.modifierFlags;
1967
1968 if ((modifiers & NSEventModifierFlagShift) != (modifier_mask_ & NSEventModifierFlagShift)) {
1969 pushEvent(std::make_unique<GHOST_EventKey>(
1970 event.timestamp * 1000,
1971 (modifiers & NSEventModifierFlagShift) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp,
1972 window,
1974 false));
1975 }
1976 if ((modifiers & NSEventModifierFlagControl) !=
1977 (modifier_mask_ & NSEventModifierFlagControl))
1978 {
1979 pushEvent(std::make_unique<GHOST_EventKey>(
1980 event.timestamp * 1000,
1981 (modifiers & NSEventModifierFlagControl) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp,
1982 window,
1984 false));
1985 }
1986 if ((modifiers & NSEventModifierFlagOption) != (modifier_mask_ & NSEventModifierFlagOption))
1987 {
1988 pushEvent(std::make_unique<GHOST_EventKey>(
1989 event.timestamp * 1000,
1990 (modifiers & NSEventModifierFlagOption) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp,
1991 window,
1993 false));
1994 }
1995 if ((modifiers & NSEventModifierFlagCommand) !=
1996 (modifier_mask_ & NSEventModifierFlagCommand))
1997 {
1998 pushEvent(std::make_unique<GHOST_EventKey>(
1999 event.timestamp * 1000,
2000 (modifiers & NSEventModifierFlagCommand) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp,
2001 window,
2003 false));
2004 }
2005
2006 modifier_mask_ = modifiers;
2008 break;
2009 }
2010
2011 default:
2012 return GHOST_kFailure;
2013 break;
2014 }
2015 return GHOST_kSuccess;
2016}
2017
2018/* --------------------------------------------------------------------
2019 * Clipboard get/set.
2020 */
2021
2022char *GHOST_SystemCocoa::getClipboard(bool /*selection*/) const
2023{
2024 @autoreleasepool {
2025 NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
2026 NSString *textPasted = [pasteBoard stringForType:NSPasteboardTypeString];
2027
2028 if (textPasted == nil) {
2029 return nullptr;
2030 }
2031
2032 const size_t pastedTextSize = [textPasted lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2033
2034 char *temp_buff = (char *)malloc(pastedTextSize + 1);
2035
2036 if (temp_buff == nullptr) {
2037 return nullptr;
2038 }
2039
2040 memcpy(temp_buff, [textPasted cStringUsingEncoding:NSUTF8StringEncoding], pastedTextSize);
2041 temp_buff[pastedTextSize] = '\0';
2042
2043 if (temp_buff) {
2044 return temp_buff;
2045 }
2046 }
2047 return nullptr;
2048}
2049
2050void GHOST_SystemCocoa::putClipboard(const char *buffer, bool selection) const
2051{
2052 if (selection) {
2053 return; /* For copying the selection, used on X11. */
2054 }
2055
2056 @autoreleasepool {
2057 NSPasteboard *pasteBoard = NSPasteboard.generalPasteboard;
2058 [pasteBoard declareTypes:@[ NSPasteboardTypeString ] owner:nil];
2059
2060 NSString *textToCopy = [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
2061 [pasteBoard setString:textToCopy forType:NSPasteboardTypeString];
2062 }
2063}
2064
2066{
2067 NSURL *pasteboardImageFile = nil;
2068
2069 @autoreleasepool {
2070 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
2071 NSDictionary *pasteboardFilteringOptions = @{
2072 NSPasteboardURLReadingFileURLsOnlyKey : @YES,
2073 NSPasteboardURLReadingContentsConformToTypesKey : [NSImage imageTypes]
2074 };
2075
2076 NSArray *pasteboardMatches = [pasteboard readObjectsForClasses:@[ [NSURL class] ]
2077 options:pasteboardFilteringOptions];
2078
2079 if (!pasteboardMatches || !pasteboardMatches.count) {
2080 return nil;
2081 }
2082
2083 pasteboardImageFile = [[pasteboardMatches firstObject] copy];
2084 }
2085
2086 return [pasteboardImageFile autorelease];
2087}
2088
2090{
2091 @autoreleasepool {
2092 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
2093 NSArray *supportedTypes = [NSArray
2094 arrayWithObjects:NSPasteboardTypeFileURL, NSPasteboardTypeTIFF, NSPasteboardTypePNG, nil];
2095
2096 NSPasteboardType availableType = [pasteboard availableTypeFromArray:supportedTypes];
2097
2098 if (!availableType) {
2099 return GHOST_kFailure;
2100 }
2101
2102 /* If we got a file, ensure it's an image file. */
2103 if ([pasteboard availableTypeFromArray:@[ NSPasteboardTypeFileURL ]] &&
2104 NSPasteboardGetImageFile() == nil)
2105 {
2106 return GHOST_kFailure;
2107 }
2108 }
2109
2110 return GHOST_kSuccess;
2111}
2112
2113uint *GHOST_SystemCocoa::getClipboardImage(int *r_width, int *r_height) const
2114{
2115 if (!hasClipboardImage()) {
2116 return nullptr;
2117 }
2118
2119 @autoreleasepool {
2120 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
2121
2122 NSImage *clipboardImage = nil;
2123 if (NSURL *pasteboardImageFile = NSPasteboardGetImageFile(); pasteboardImageFile != nil) {
2124 /* Image file. */
2125 clipboardImage = [[[NSImage alloc] initWithContentsOfURL:pasteboardImageFile] autorelease];
2126 }
2127 else {
2128 /* Raw image data. */
2129 clipboardImage = [[[NSImage alloc] initWithPasteboard:pasteboard] autorelease];
2130 }
2131
2132 if (!clipboardImage) {
2133 return nullptr;
2134 }
2135
2136 blender::ImBuf *ibuf = NSImageToImBuf(clipboardImage);
2137 const NSSize clipboardImageSize = getNSImagePixelSize(clipboardImage);
2138
2139 if (ibuf) {
2140 const size_t byteCount = clipboardImageSize.width * clipboardImageSize.height * 4;
2141 uint *rgba = (uint *)malloc(byteCount);
2142
2143 if (!rgba) {
2145 return nullptr;
2146 }
2147
2148 memcpy(rgba, ibuf->byte_data(), byteCount);
2150
2151 *r_width = clipboardImageSize.width;
2152 *r_height = clipboardImageSize.height;
2153
2154 return rgba;
2155 }
2156 }
2157
2158 return nullptr;
2159}
2160
2161GHOST_TSuccess GHOST_SystemCocoa::putClipboardImage(uint *rgba, int width, int height) const
2162{
2163 @autoreleasepool {
2164 const size_t rowByteCount = width * 4;
2165
2166 NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc]
2167 initWithBitmapDataPlanes:nil
2168 pixelsWide:width
2169 pixelsHigh:height
2170 bitsPerSample:8
2171 samplesPerPixel:4
2172 hasAlpha:YES
2173 isPlanar:NO
2174 colorSpaceName:NSDeviceRGBColorSpace
2175 bytesPerRow:rowByteCount
2176 bitsPerPixel:32];
2177
2178 /* Copy the source image data to imageRep, flipping it vertically. */
2179 uint8_t *srcBuffer = reinterpret_cast<uint8_t *>(rgba);
2180 uint8_t *dstBuffer = static_cast<uint8_t *>([imageRep bitmapData]);
2181
2182 for (int y = 0; y < height; y++) {
2183 const int dstOff = (height - y - 1) * rowByteCount;
2184 const int srcOff = y * rowByteCount;
2185 memcpy(dstBuffer + dstOff, srcBuffer + srcOff, rowByteCount);
2186 }
2187
2188 NSImage *image = [[[NSImage alloc] initWithSize:NSMakeSize(width, height)] autorelease];
2189 [image addRepresentation:imageRep];
2190
2191 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
2192 [pasteboard clearContents];
2193
2194 BOOL pasteSuccess = [pasteboard writeObjects:@[ image ]];
2195
2196 if (!pasteSuccess) {
2197 return GHOST_kFailure;
2198 }
2199 }
2200 return GHOST_kSuccess;
2201}
2202
2204 const char *message,
2205 const char *help_label,
2206 const char *continue_label,
2207 const char *link,
2208 GHOST_DialogOptions dialog_options) const
2209{
2210 @autoreleasepool {
2211 NSAlert *alert = [[[NSAlert alloc] init] autorelease];
2212 alert.accessoryView = [[[NSView alloc] initWithFrame:NSMakeRect(0, 0, 500, 0)] autorelease];
2213
2214 NSString *titleString = [NSString stringWithCString:title];
2215 NSString *messageString = [NSString stringWithCString:message];
2216 NSString *continueString = [NSString stringWithCString:continue_label];
2217 NSString *helpString = [NSString stringWithCString:help_label];
2218
2219 if (dialog_options & GHOST_DialogError) {
2220 alert.alertStyle = NSAlertStyleCritical;
2221 }
2222 else if (dialog_options & GHOST_DialogWarning) {
2223 alert.alertStyle = NSAlertStyleWarning;
2224 }
2225 else {
2226 alert.alertStyle = NSAlertStyleInformational;
2227 }
2228
2229 alert.messageText = titleString;
2230 alert.informativeText = messageString;
2231
2232 [alert addButtonWithTitle:continueString];
2233 if (link && strlen(link)) {
2234 [alert addButtonWithTitle:helpString];
2235 }
2236
2237 const NSModalResponse response = [alert runModal];
2238 if (response == NSAlertSecondButtonReturn) {
2239 NSString *linkString = [NSString stringWithCString:link];
2240 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:linkString]];
2241 }
2242 }
2243 return GHOST_kSuccess;
2244}
#define GHOST_ASSERT(x, info)
#define GHOST_PRINT(x)
CGError CGSGetCursorScale(CGSConnectionID connection, CGFloat *scale)
static GHOST_TKey convertKey(int rawCode, unichar recvChar)
#define FIRSTFILEBUFLG
int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
static char g_firstFileBuf[FIRSTFILEBUFLG]
static NSSize getNSImagePixelSize(NSImage *image)
static bool g_hasFirstFile
int CGSConnectionID
static GHOST_TButton convertButton(int button)
static blender::ImBuf * NSImageToImBuf(NSImage *image)
CGSConnectionID CGSMainConnectionID(void)
static NSURL * NSPasteboardGetImageFile()
GHOST_TEventWheelAxis
@ GHOST_kEventWheelAxisVertical
@ GHOST_kEventWheelAxisHorizontal
const void * GHOST_TEventDataPtr
@ GHOST_kTrackpadEventMagnify
@ GHOST_kTrackpadEventSmartMagnify
@ GHOST_kTrackpadEventRotate
@ GHOST_kTrackpadEventScroll
GHOST_TWindowState
GHOST_TEventType
@ GHOST_kEventWindowClose
@ GHOST_kEventWindowMove
@ GHOST_kEventWindowSize
@ GHOST_kEventDraggingDropDone
@ GHOST_kEventDraggingExited
@ GHOST_kEventNativeResolutionChange
@ GHOST_kEventCursorMove
@ GHOST_kEventDraggingUpdated
@ GHOST_kEventOpenMainFile
@ GHOST_kEventDraggingEntered
@ GHOST_kEventButtonUp
@ GHOST_kEventWindowActivate
@ GHOST_kEventWindowUpdate
@ GHOST_kEventWindowDeactivate
@ GHOST_kEventButtonDown
@ GHOST_kEventKeyDown
@ GHOST_kEventKeyUp
@ GHOST_kEventQuitRequest
@ GHOST_kTabletModeEraser
@ GHOST_kTabletModeStylus
@ GHOST_kTabletModeNone
GHOST_TCapabilityFlag
@ GHOST_kCapabilityClipboardPrimary
@ GHOST_kCapabilityKeyboardHyperKey
@ GHOST_kCapabilityCursorGenerator
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings)
#define GHOST_CAPABILITY_FLAG_ALL
void * GHOST_TDragnDropDataPtr
GHOST_TKey
@ GHOST_kKeyLeftOS
@ GHOST_kKeySemicolon
@ GHOST_kKey5
@ GHOST_kKeyZ
@ GHOST_kKeyQuote
@ GHOST_kKey4
@ GHOST_kKeyT
@ GHOST_kKeyNumpad3
@ GHOST_kKeyAccentGrave
@ GHOST_kKeyNumpad1
@ GHOST_kKeyW
@ GHOST_kKeyLeftAlt
@ GHOST_kKey3
@ GHOST_kKeyG
@ GHOST_kKeyF9
@ GHOST_kKeyC
@ GHOST_kKeyI
@ GHOST_kKeyEnter
@ GHOST_kKeyF20
@ GHOST_kKeyP
@ GHOST_kKeyJ
@ GHOST_kKeyNumpadSlash
@ GHOST_kKeyRightArrow
@ GHOST_kKeyF13
@ GHOST_kKeyF6
@ GHOST_kKeyNumpad4
@ GHOST_kKeyF11
@ GHOST_kKeyR
@ GHOST_kKeyN
@ GHOST_kKeyMinus
@ GHOST_kKeyO
@ GHOST_kKey6
@ GHOST_kKeyBackSpace
@ GHOST_kKey0
@ GHOST_kKeyF5
@ GHOST_kKeyF19
@ GHOST_kKeyDownPage
@ GHOST_kKeyDownArrow
@ GHOST_kKeyQ
@ GHOST_kKeyNumpadPeriod
@ GHOST_kKeyF12
@ GHOST_kKeyF1
@ GHOST_kKeyF
@ GHOST_kKeyU
@ GHOST_kKeyNumpadAsterisk
@ GHOST_kKeyB
@ GHOST_kKeyLeftControl
@ GHOST_kKeyLeftBracket
@ GHOST_kKey1
@ GHOST_kKeyM
@ GHOST_kKeyTab
@ GHOST_kKey8
@ GHOST_kKeyComma
@ GHOST_kKeyRightBracket
@ GHOST_kKeyBackslash
@ GHOST_kKeyNumpad2
@ GHOST_kKeyX
@ GHOST_kKeyL
@ GHOST_kKeyY
@ GHOST_kKeyPeriod
@ GHOST_kKeyNumpadPlus
@ GHOST_kKeyUpPage
@ GHOST_kKey9
@ GHOST_kKeyNumpad5
@ GHOST_kKeyLeftArrow
@ GHOST_kKeyF17
@ GHOST_kKeyD
@ GHOST_kKeyEqual
@ GHOST_kKey7
@ GHOST_kKeyS
@ GHOST_kKeyF8
@ GHOST_kKeyF18
@ GHOST_kKeyHome
@ GHOST_kKeyNumpad6
@ GHOST_kKeyF14
@ GHOST_kKeyNumpad8
@ GHOST_kKeyNumpad9
@ GHOST_kKeyF15
@ GHOST_kKeyEnd
@ GHOST_kKeyUpArrow
@ GHOST_kKeyH
@ GHOST_kKeyDelete
@ GHOST_kKeyF16
@ GHOST_kKeyNumpad0
@ GHOST_kKeyA
@ GHOST_kKey2
@ GHOST_kKeyK
@ GHOST_kKeyNumpad7
@ GHOST_kKeyEsc
@ GHOST_kKeyPlus
@ GHOST_kKeyUnknown
@ GHOST_kKeySlash
@ GHOST_kKeyV
@ GHOST_kKeyF7
@ GHOST_kKeyNumpadEnter
@ GHOST_kKeyNumpadMinus
@ GHOST_kKeyF10
@ GHOST_kKeyLeftShift
@ GHOST_kKeyF3
@ GHOST_kKeyF2
@ GHOST_kKeyF4
@ GHOST_kKeyE
@ GHOST_kKeySpace
@ GHOST_kModifierKeyLeftControl
@ GHOST_kModifierKeyLeftAlt
@ GHOST_kModifierKeyLeftShift
@ GHOST_kModifierKeyLeftOS
GHOST_TSuccess
@ GHOST_kFailure
@ GHOST_kSuccess
@ GHOST_kFireTimeNever
@ GHOST_kGrabHide
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings)
GHOST_TDragnDropTypes
@ GHOST_kDragnDropTypeFilenames
@ GHOST_kDragnDropTypeBitmap
@ GHOST_kDragnDropTypeString
GHOST_TButton
@ GHOST_kButtonMaskRight
@ GHOST_kButtonMaskButton4
@ GHOST_kButtonMaskLeft
@ GHOST_kButtonMaskButton7
@ GHOST_kButtonMaskButton6
@ GHOST_kButtonMaskButton5
@ GHOST_kButtonMaskMiddle
GHOST_DialogOptions
@ GHOST_DialogError
@ GHOST_DialogWarning
#define C
Definition RandGen.cpp:29
unsigned long long int uint64_t
GHOST_ContextMTL(const GHOST_ContextParams &context_params, NSView *metalView, CAMetalLayer *metalLayer)
GHOST_ContextVK(const GHOST_ContextParams &context_params, GHOST_TVulkanPlatformType platform, Window window, Display *display, wl_surface *wayland_surface, wl_display *wayland_display, const GHOST_ContextVK_WindowInfo *wayland_window_info, int contextMajorVersion, int contextMinorVersion, const GHOST_GPUDevice &preferred_device, const GHOST_WindowHDRInfo *hdr_info_=nullptr)
virtual bool getValid() const =0
int32_t t_
virtual bool clip(GHOST_Rect &r) const
Definition GHOST_Rect.cc:92
int32_t r_
virtual void wrapPoint(int32_t &x, int32_t &y, int32_t ofs, GHOST_TAxisFlag axis)
int32_t b_
int32_t l_
bool processEvents(bool waitForEvent) override
uint * getClipboardImage(int *r_width, int *r_height) const override
GHOST_TSuccess disposeContext(GHOST_IContext *context) override
void getAllDisplayDimensions(uint32_t &width, uint32_t &height) const override
GHOST_TSuccess getCursorPosition(int32_t &x, int32_t &y) const override
GHOST_TSuccess handleWindowEvent(GHOST_TEventType eventType, GHOST_WindowCocoa *window)
GHOST_TSuccess handleDraggingEvent(GHOST_TEventType eventType, GHOST_TDragnDropTypes draggedObjectType, GHOST_WindowCocoa *window, int mouseX, int mouseY, void *data)
GHOST_TSuccess handleApplicationBecomeActiveEvent()
GHOST_TSuccess hasClipboardImage() const override
GHOST_TSuccess handleMouseEvent(void *eventPtr)
GHOST_TSuccess getModifierKeys(GHOST_ModifierKeys &keys) const override
GHOST_TSuccess handleKeyEvent(void *eventPtr)
GHOST_TSuccess init() override
GHOST_TSuccess getPixelAtCursor(float r_color[3]) const override
uint64_t getMilliSeconds() const override
GHOST_TCapabilityFlag getCapabilities() const override
GHOST_TSuccess showMessageBox(const char *title, const char *message, const char *help_label, const char *continue_label, const char *link, GHOST_DialogOptions dialog_options) const override
uint8_t getNumDisplays() const override
void getMainDisplayDimensions(uint32_t &width, uint32_t &height) const override
GHOST_TSuccess handleTabletEvent(void *eventPtr, short eventType)
bool handleOpenDocumentRequest(void *filepathStr)
GHOST_TSuccess setCursorPosition(int32_t x, int32_t y) override
char * getClipboard(bool selection) const override
GHOST_TSuccess setMouseCursorPosition(int32_t x, int32_t y)
void putClipboard(const char *buffer, bool selection) const override
GHOST_TSuccess getButtons(GHOST_Buttons &buttons) const override
GHOST_IWindow * getWindowUnderCursor(int32_t x, int32_t y) override
GHOST_IContext * createOffscreenContext(GHOST_GPUSettings gpu_settings) override
uint32_t getCursorPreferredLogicalSize() const override
GHOST_IWindow * createWindow(const char *title, int32_t left, int32_t top, uint32_t width, uint32_t height, GHOST_TWindowState state, GHOST_GPUSettings gpu_settings, const bool exclusive=false, const bool is_dialog=false, const GHOST_IWindow *parent_window=nullptr) override
bool need_delayed_application_become_active_event_processing_
GHOST_TSuccess putClipboardImage(uint *rgba, int width, int height) const override
GHOST_WindowManager * window_manager_
GHOST_TSuccess init() override
GHOST_TimerManager * getTimerManager() const
bool validWindow(GHOST_IWindow *window) override
GHOST_TSuccess pushEvent(std::unique_ptr< const GHOST_IEvent > event)
bool multitouch_gestures_
bool fireTimers(uint64_t time)
bool isDialog() const override
NSScreen * getScreen() const
void clientToScreenIntern(int32_t inX, int32_t inY, int32_t &outX, int32_t &outY) const
void * getOSWindow() const override
GHOST_TabletData & GetCocoaTabletData()
void getClientBounds(GHOST_Rect &bounds) const override
void screenToClient(int32_t inX, int32_t inY, int32_t &outX, int32_t &outY) const override
GHOST_WindowCocoa(GHOST_SystemCocoa *systemCocoa, const char *title, int32_t left, int32_t bottom, uint32_t width, uint32_t height, GHOST_TWindowState state, GHOST_TDrawingContextType type, const GHOST_ContextParams &context_params, bool dialog, GHOST_WindowCocoa *parent_window, const GHOST_GPUDevice &preferred_device)
void loadCursor(bool visible, GHOST_TStandardCursor cursor) const
GHOST_TSuccess addWindow(GHOST_IWindow *window)
GHOST_IWindow * getWindowAssociatedWithOSWindow(const void *osWindow)
const std::vector< GHOST_IWindow * > & getWindows() const
GHOST_IWindow * getActiveWindow() const
GHOST_TSuccess setActiveWindow(GHOST_IWindow *window)
void setWindowInactive(const GHOST_IWindow *window)
virtual GHOST_TSuccess getCursorGrabBounds(GHOST_Rect &bounds) const
void setCursorGrabAccum(int32_t x, int32_t y)
GHOST_TAxisFlag getCursorGrabAxis() const
GHOST_TStandardCursor getCursorShape() const override
bool getCursorVisibility() const override
GHOST_TGrabCursorMode getCursorGrabMode() const
GHOST_TSuccess updateDrawingContext()
bool getCursorGrabModeIsWarp() const
void getCursorGrabAccum(int32_t &x, int32_t &y) const
#define printf
#define image(slot, qualifiers, format)
#define index(i)
#define sampler(slot)
float length(VecOp< float, D >) RET
IMG_TEMPLATE SizeVec imageSize(const T &) RET
float3x3 scale(float3x3 mat, float2 scale)
GHOST_SystemCocoa * systemCocoa
const int state
void IMB_freeImBuf(ImBuf *ibuf)
ImBuf * IMB_allocImBuf(unsigned int x, unsigned int y, ImBufFlags flags)
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
void set(GHOST_TButton mask, bool down)
GHOST_TDrawingContextType context_type
GHOST_GPUDevice preferred_device
void set(GHOST_TModifierKey mask, bool down)
GHOST_TTabletMode Active
const uint8_t * byte_data() const
uint8_t * byte_data_for_write()
Definition allocimbuf.cc:60