Blender V5.3
GHOST_WindowCocoa.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
8#include "GHOST_Debug.hh"
10
11/* Don't generate OpenGL deprecation warning. This is a known thing, and is not something easily
12 * solvable in a short term. */
13#ifdef __clang__
14# pragma clang diagnostic ignored "-Wdeprecated-declarations"
15#endif
16
17#ifdef WITH_METAL_BACKEND
18# include "GHOST_ContextMTL.hh"
19#endif
20
21#ifdef WITH_VULKAN_BACKEND
22# include "GHOST_ContextVK.hh"
23#endif
24
25#import <Cocoa/Cocoa.h>
26#import <Metal/Metal.h>
27
28/* --------------------------------------------------------------------
29 * Blender window delegate object.
30 */
31
32@interface BlenderWindowDelegate : NSObject <NSWindowDelegate>
33
34@property(nonatomic, readonly, assign) GHOST_SystemCocoa *systemCocoa;
35@property(nonatomic, readonly, assign) GHOST_WindowCocoa *windowCocoa;
36
37- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa
38 windowCocoa:(GHOST_WindowCocoa *)winCocoa;
39- (void)windowDidBecomeKey:(NSNotification *)notification;
40- (void)windowDidResignKey:(NSNotification *)notification;
41- (void)windowDidExpose:(NSNotification *)notification;
42- (void)windowDidResize:(NSNotification *)notification;
43- (void)windowDidMove:(NSNotification *)notification;
44- (void)windowWillMove:(NSNotification *)notification;
45- (BOOL)windowShouldClose:(id)sender;
46- (void)windowDidChangeBackingProperties:(NSNotification *)notification;
47
48@end
49
50@implementation BlenderWindowDelegate : NSObject
51
52@synthesize systemCocoa = system_cocoa_;
53@synthesize windowCocoa = window_cocoa_;
54
55- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa
56 windowCocoa:(GHOST_WindowCocoa *)winCocoa
57{
58 self = [super init];
59
60 if (self) {
61 system_cocoa_ = sysCocoa;
62 window_cocoa_ = winCocoa;
63 }
64
65 return self;
66}
67
68- (void)windowDidBecomeKey:(NSNotification *)notification
69{
70 system_cocoa_->handleWindowEvent(GHOST_kEventWindowActivate, window_cocoa_);
71 /* Workaround for broken app-switching when combining Command-Tab and mission-control. */
72 [(NSWindow *)window_cocoa_->getOSWindow() orderFrontRegardless];
73}
74
75- (void)windowDidResignKey:(NSNotification *)notification
76{
77 system_cocoa_->handleWindowEvent(GHOST_kEventWindowDeactivate, window_cocoa_);
78}
79
80- (void)windowDidExpose:(NSNotification *)notification
81{
82 system_cocoa_->handleWindowEvent(GHOST_kEventWindowUpdate, window_cocoa_);
83}
84
85- (void)windowDidMove:(NSNotification *)notification
86{
87 system_cocoa_->handleWindowEvent(GHOST_kEventWindowMove, window_cocoa_);
88}
89
90- (void)windowWillMove:(NSNotification *)notification
91{
92 system_cocoa_->handleWindowEvent(GHOST_kEventWindowMove, window_cocoa_);
93}
94
95- (void)windowWillEnterFullScreen:(NSNotification *)notification
96{
97 window_cocoa_->setImmediateDraw(true);
98}
99
100- (void)windowDidEnterFullScreen:(NSNotification *)notification
101{
102 /* macOS does not send a window resize event when switching between zoomed
103 * and full-screen, when automatic show/hide of dock and menu bar are enabled.
104 * Send our own to prevent artifacts. */
105 system_cocoa_->handleWindowEvent(GHOST_kEventWindowSize, window_cocoa_);
106
107 window_cocoa_->setImmediateDraw(false);
108}
109
110- (void)windowWillExitFullScreen:(NSNotification *)notification
111{
112 window_cocoa_->setImmediateDraw(true);
113}
114
115- (void)windowDidExitFullScreen:(NSNotification *)notification
116{
117 /* See comment for windowWillEnterFullScreen. */
118 system_cocoa_->handleWindowEvent(GHOST_kEventWindowSize, window_cocoa_);
119 window_cocoa_->setImmediateDraw(false);
120}
121
122- (void)windowDidResize:(NSNotification *)notification
123{
124#if 0
125 if (![[notification object] inLiveResize])
126#endif
127 {
128 /* Send event only once, at end of resize operation (when user has released mouse button). */
129 system_cocoa_->handleWindowEvent(GHOST_kEventWindowSize, window_cocoa_);
130 }
131 /* Live resize, send event, gets handled in wm_window.c.
132 * Needed because live resize runs in a modal loop, not letting main loop run */
133 if ([[notification object] inLiveResize]) {
134 system_cocoa_->dispatchEvents();
135 }
136}
137
138- (void)windowDidChangeBackingProperties:(NSNotification *)notification
139{
140 system_cocoa_->handleWindowEvent(GHOST_kEventNativeResolutionChange, window_cocoa_);
141 system_cocoa_->handleWindowEvent(GHOST_kEventWindowSize, window_cocoa_);
142}
143
144- (BOOL)windowShouldClose:(id)sender;
145{
146 /* Let Blender close the window rather than closing immediately. */
147 system_cocoa_->handleWindowEvent(GHOST_kEventWindowClose, window_cocoa_);
148 return false;
149}
150
151@end
152
153@interface BlenderWindow : NSWindow
154
155@property(nonatomic, readonly, assign) GHOST_SystemCocoa *systemCocoa;
156@property(nonatomic, readonly, assign) GHOST_WindowCocoa *windowCocoa;
157@property(nonatomic, readonly, assign) GHOST_TDragnDropTypes draggedObjectType;
158
159- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa
160 windowCocoa:(GHOST_WindowCocoa *)winCocoa
161 contentRect:(NSRect)contentRect
162 styleMask:(NSWindowStyleMask)style
163 backing:(NSBackingStoreType)backingStoreType
164 defer:(BOOL)flag;
165
166@end
167
168@implementation BlenderWindow
169
170@synthesize systemCocoa = system_cocoa_;
171@synthesize windowCocoa = window_cocoa_;
172@synthesize draggedObjectType = dragged_object_type_;
173
174- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa
175 windowCocoa:(GHOST_WindowCocoa *)winCocoa
176 contentRect:(NSRect)contentRect
177 styleMask:(NSWindowStyleMask)style
178 backing:(NSBackingStoreType)backingStoreType
179 defer:(BOOL)flag
180{
181 self = [super initWithContentRect:contentRect
182 styleMask:style
183 backing:backingStoreType
184 defer:flag];
185
186 if (self) {
187 system_cocoa_ = sysCocoa;
188 window_cocoa_ = winCocoa;
189 }
190
191 return self;
192}
193
194- (BOOL)canBecomeKeyWindow
195{
196 /* Don't make other windows active when a dialog window is open. */
197 return (window_cocoa_->isDialog() || !system_cocoa_->hasDialogWindow());
198}
199
200/* The drag & drop dragging destination methods. */
201- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender
202{
203 @autoreleasepool {
204 NSPasteboard *draggingPBoard = sender.draggingPasteboard;
205 if ([[draggingPBoard types] containsObject:NSPasteboardTypeTIFF]) {
206 dragged_object_type_ = GHOST_kDragnDropTypeBitmap;
207 }
208 else if ([[draggingPBoard types] containsObject:NSFilenamesPboardType]) {
209 dragged_object_type_ = GHOST_kDragnDropTypeFilenames;
210 }
211 else if ([[draggingPBoard types] containsObject:NSPasteboardTypeString]) {
212 dragged_object_type_ = GHOST_kDragnDropTypeString;
213 }
214 else {
215 return NSDragOperationNone;
216 }
217
218 const NSPoint mouseLocation = sender.draggingLocation;
219 window_cocoa_->setAcceptDragOperation(TRUE); /* Drag operation is accepted by default. */
220 system_cocoa_->handleDraggingEvent(GHOST_kEventDraggingEntered,
221 dragged_object_type_,
222 window_cocoa_,
223 mouseLocation.x,
224 mouseLocation.y,
225 nil);
226 }
227 return NSDragOperationCopy;
228}
229
230- (BOOL)wantsPeriodicDraggingUpdates
231{
232 return NO; /* No need to overflow blender event queue. Events shall be sent only on changes. */
233}
234
235- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender
236{
237 const NSPoint mouseLocation = [sender draggingLocation];
238
239 system_cocoa_->handleDraggingEvent(GHOST_kEventDraggingUpdated,
240 dragged_object_type_,
241 window_cocoa_,
242 mouseLocation.x,
243 mouseLocation.y,
244 nil);
245 return window_cocoa_->canAcceptDragOperation() ? NSDragOperationCopy : NSDragOperationNone;
246}
247
248- (void)draggingExited:(id<NSDraggingInfo>)sender
249{
250 system_cocoa_->handleDraggingEvent(
251 GHOST_kEventDraggingExited, dragged_object_type_, window_cocoa_, 0, 0, nil);
252 dragged_object_type_ = GHOST_kDragnDropTypeUnknown;
253}
254
255- (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender
256{
257 if (window_cocoa_->canAcceptDragOperation()) {
258 return YES;
259 }
260 return NO;
261}
262
263- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender
264{
265 @autoreleasepool {
266 NSPasteboard *draggingPBoard = sender.draggingPasteboard;
267 id data;
268
269 switch (dragged_object_type_) {
271 if (![NSImage canInitWithPasteboard:draggingPBoard]) {
272 return NO;
273 }
274 /* Caller must [release] the returned data in this case. */
275 NSImage *droppedImg = [[NSImage alloc] initWithPasteboard:draggingPBoard];
276 data = droppedImg;
277 break;
278 }
280 data = [draggingPBoard propertyListForType:NSFilenamesPboardType];
281 break;
283 data = [draggingPBoard stringForType:NSPasteboardTypeString];
284 break;
285 default:
286 return NO;
287 break;
288 }
289
290 const NSPoint mouseLocation = sender.draggingLocation;
291 system_cocoa_->handleDraggingEvent(GHOST_kEventDraggingDropDone,
292 dragged_object_type_,
293 window_cocoa_,
294 mouseLocation.x,
295 mouseLocation.y,
296 (void *)data);
297 }
298 return YES;
299}
300
301@end
302
303/* NSView for handling input and drawing. */
304#define COCOA_VIEW_CLASS CocoaOpenGLView
305#define COCOA_VIEW_BASE_CLASS NSOpenGLView
307#undef COCOA_VIEW_CLASS
308#undef COCOA_VIEW_BASE_CLASS
309
310#define COCOA_VIEW_CLASS CocoaMetalView
311#define COCOA_VIEW_BASE_CLASS NSView
313#undef COCOA_VIEW_CLASS
314#undef COCOA_VIEW_BASE_CLASS
315
316/* --------------------------------------------------------------------
317 * Initialization / Finalization.
318 */
319
321 const char *title,
322 int32_t left,
323 int32_t bottom,
324 uint32_t width,
325 uint32_t height,
328 const GHOST_ContextParams &context_params,
329 bool is_dialog,
330 GHOST_WindowCocoa *parent_window,
331 const GHOST_GPUDevice &preferred_device)
332 : GHOST_Window(width, height, state, context_params, false),
333 opengl_view_(nil),
334 metal_view_(nil),
335 metal_layer_(nil),
337 custom_cursor_(nullptr),
338 immediate_draw_(false),
339 is_dialog_(is_dialog),
340 preferred_device_(preferred_device)
341{
342 full_screen_ = false;
343
344 @autoreleasepool {
345 /* Create the window. */
346 NSRect rect;
347 rect.origin.x = left;
348 rect.origin.y = bottom;
349 rect.size.width = width;
350 rect.size.height = height;
351
352 NSWindowStyleMask styleMask = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
353 NSWindowStyleMaskResizable;
354 if (!is_dialog) {
355 styleMask |= NSWindowStyleMaskMiniaturizable;
356 }
357
358 window_ = [[BlenderWindow alloc] initWithSystemCocoa:systemCocoa
359 windowCocoa:this
360 contentRect:rect
361 styleMask:styleMask
362 backing:NSBackingStoreBuffered
363 defer:NO];
364 /* By default, AppKit repositions the window in the context of the current "mainMonitor"
365 * (the monitor which has focus), bypass this by forcing the window back into its correct
366 * position. Since we use global screen coordinate indexed on the first, primary screen.
367 */
368 [window_ setFrameOrigin:NSMakePoint(left, bottom)];
369
370 /* Forbid to resize the window below the blender defined minimum one. */
371 const NSSize minSize = {320, 240};
372 window_.contentMinSize = minSize;
373
374 /* Create NSView inside the window. */
375 id<MTLDevice> metalDevice = MTLCreateSystemDefaultDevice();
376 NSView *view;
377
378 if (metalDevice) {
379 /* Create metal layer and view if supported. */
380 metal_layer_ = [[CAMetalLayer alloc] init];
381 metal_layer_.edgeAntialiasingMask = 0;
382 metal_layer_.masksToBounds = NO;
383 metal_layer_.opaque = YES;
384 metal_layer_.framebufferOnly = YES;
385 metal_layer_.presentsWithTransaction = NO;
386 [metal_layer_ removeAllAnimations];
387 metal_layer_.device = metalDevice;
388
389 if (context_params.vsync != GHOST_kVSyncModeUnset) {
390 metal_layer_.displaySyncEnabled = (context_params.vsync == GHOST_kVSyncModeOff) ? NO : YES;
391 }
392
393 if (type == GHOST_kDrawingContextTypeMetal) {
394 /* Enable EDR support. This is done by:
395 * 1. Using a floating point render target, so that values outside 0..1 can be used
396 * 2. Informing the OS that we are EDR aware, and intend to use values outside 0..1
397 * 3. Setting the extended sRGB color space so that the OS knows how to interpret the
398 * values.
399 */
400 metal_layer_.wantsExtendedDynamicRangeContent = YES;
401 metal_layer_.pixelFormat = MTLPixelFormatRGBA16Float;
402 const CFStringRef name = kCGColorSpaceExtendedSRGB;
403 CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(name);
404 metal_layer_.colorspace = colorspace;
405 CGColorSpaceRelease(colorspace);
406
407 /* For Blender to know if this window supports HDR. */
408 hdr_info_.hdr_enabled = true;
411 }
412
413 metal_view_ = [[CocoaMetalView alloc] initWithSystemCocoa:systemCocoa
414 windowCocoa:this
415 frame:rect];
416 metal_view_.wantsLayer = YES;
418 view = metal_view_;
419 }
420 else {
421 /* Fall back to OpenGL view if there is no Metal support. */
422 opengl_view_ = [[CocoaOpenGLView alloc] initWithSystemCocoa:systemCocoa
423 windowCocoa:this
424 frame:rect];
425 view = opengl_view_;
426 }
427
428 window_.contentView = view;
429 window_.initialFirstResponder = view;
430
433 }
434
435 [window_ makeKeyAndOrderFront:nil];
436
438
442
443 setTitle(title);
444
445 tablet_ = GHOST_TABLET_DATA_NONE;
446
447 BlenderWindowDelegate *windowDelegate = [[BlenderWindowDelegate alloc]
448 initWithSystemCocoa:systemCocoa
449 windowCocoa:this];
450 window_.delegate = windowDelegate;
451
452 window_.acceptsMouseMovedEvents = YES;
453
454 NSView *contentview = window_.contentView;
455 contentview.allowedTouchTypes = (NSTouchTypeMaskDirect | NSTouchTypeMaskIndirect);
456
457 [window_ registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType,
458 NSPasteboardTypeString,
459 NSPasteboardTypeTIFF,
460 nil]];
461
462 if (is_dialog && parent_window) {
463 [parent_window->getViewWindow() addChildWindow:window_ ordered:NSWindowAbove];
464 window_.collectionBehavior = NSWindowCollectionBehaviorFullScreenAuxiliary;
465 }
466 else {
467 window_.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary;
468 }
469
471 }
472}
473
475{
476 @autoreleasepool {
477 if (custom_cursor_) {
478 [custom_cursor_ release];
479 custom_cursor_ = nil;
480 }
481
483
484 if (opengl_view_) {
485 [opengl_view_ release];
486 opengl_view_ = nil;
487 }
488 if (metal_view_) {
489 [metal_view_ release];
490 metal_view_ = nil;
491 }
492 if (metal_layer_) {
493 [metal_layer_ release];
494 metal_layer_ = nil;
495 }
496
497 if (window_) {
498 [window_ close];
499 }
500
501 /* Check for other blender opened windows and make the front-most key
502 * NOTE: for some reason the closed window is still in the list. */
503 NSArray *windowsList = [NSApp orderedWindows];
504 for (int a = 0; a < [windowsList count]; a++) {
505 if (window_ != (BlenderWindow *)[windowsList objectAtIndex:a]) {
506 [[windowsList objectAtIndex:a] makeKeyWindow];
507 break;
508 }
509 }
510 window_ = nil;
511 }
512}
513
514/* --------------------------------------------------------------------
515 * Accessors.
516 */
517
519{
520 NSView *view = (opengl_view_) ? opengl_view_ : metal_view_;
521 return GHOST_Window::getValid() && window_ != nullptr && view != nullptr;
522}
523
525{
526 return (void *)window_;
527}
528
529void GHOST_WindowCocoa::setTitle(const char *title)
530{
531 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setTitle(): window invalid");
532
533 @autoreleasepool {
534 NSString *windowTitle = [[NSString alloc] initWithCString:title encoding:NSUTF8StringEncoding];
535 window_.title = windowTitle;
536
537 [windowTitle release];
538 }
539}
540
542{
543 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getTitle(): window invalid");
544
545 std::string title;
546 @autoreleasepool {
547 NSString *windowTitle = window_.title;
548 if (windowTitle != nil) {
549 title = windowTitle.UTF8String;
550 }
551 }
552 return title;
553}
554
555void GHOST_WindowCocoa::setPath(const char *filepath)
556{
557 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setAssociatedFile(): window invalid");
558
559 @autoreleasepool {
560 NSString *associatedFileName = [[[NSString alloc] initWithCString:filepath
561 encoding:NSUTF8StringEncoding]
562 autorelease];
563
564 window_.representedFilename = associatedFileName;
565 }
566}
567
569{
570 @autoreleasepool {
572 const float *background_color = window_decoration_style_settings_.colored_titlebar_bg_color;
573
574 /* Title-bar background color. */
575 window_.backgroundColor = [NSColor colorWithRed:background_color[0]
576 green:background_color[1]
577 blue:background_color[2]
578 alpha:1.0];
579
580 /* Title-bar foreground color.
581 * Use the value component of the title-bar background's HSV representation to determine
582 * whether we should use the macOS dark or light title-bar text appearance. With values below
583 * 0.5 considered as dark themes, and values above 0.5 considered as light themes.
584 */
585 const float hsv_v = MAX(background_color[0], MAX(background_color[1], background_color[2]));
586
587 const NSAppearanceName win_appearance = hsv_v > 0.5 ? NSAppearanceNameVibrantLight :
588 NSAppearanceNameVibrantDark;
589
590 window_.appearance = [NSAppearance appearanceNamed:win_appearance];
591 window_.titlebarAppearsTransparent = YES;
592 }
593 else {
594 window_.titlebarAppearsTransparent = NO;
595 }
596 }
597 return GHOST_kSuccess;
598}
599
601{
602 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getWindowBounds(): window invalid");
603
604 @autoreleasepool {
605 /* All coordinates are based off the primary screen. */
606 const NSRect screenFrame = [getPrimaryScreen() visibleFrame];
607 const NSRect windowFrame = window_.frame;
608
609 /* Flip the Y axis, from bottom left coordinate to top left, which is the expected coordinate
610 * return format for GHOST, even though the Window Manager later reflips it to bottom-left
611 * this is the expected coordinate system for all GHOST backends
612 */
613
614 const int32_t screenMaxY = screenFrame.origin.y + screenFrame.size.height;
615
616 /* Flip the coordinates vertically from a bottom-left origin to a top-left origin,
617 * as expected by GHOST. */
618 bounds.b_ = screenMaxY - windowFrame.origin.y;
619 bounds.t_ = screenMaxY - windowFrame.origin.y - windowFrame.size.height;
620
621 bounds.l_ = windowFrame.origin.x;
622 bounds.r_ = windowFrame.origin.x + windowFrame.size.width;
623 }
624}
625
627{
628 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getClientBounds(): window invalid");
629
630 @autoreleasepool {
631 /* All coordinates are based off the primary screen. */
632 const NSRect screenFrame = [getPrimaryScreen() visibleFrame];
633 /* Screen Content Rectangle (excluding Menu Bar and Dock). */
634 const NSRect screenContentRect = [NSWindow contentRectForFrameRect:screenFrame
635 styleMask:[window_ styleMask]];
636
637 const NSRect windowFrame = window_.frame;
638 /* Window Content Rectangle (excluding Titlebar and borders) */
639 const NSRect windowContentRect = [window_ contentRectForFrameRect:windowFrame];
640
641 const int32_t screenMaxY = screenContentRect.origin.y + screenContentRect.size.height;
642
643 /* Flip the coordinates vertically from a bottom-left origin to a top-left origin,
644 * as expected by GHOST. */
645 bounds.b_ = screenMaxY - windowContentRect.origin.y;
646 bounds.t_ = screenMaxY - windowContentRect.origin.y - windowContentRect.size.height;
647
648 bounds.l_ = windowContentRect.origin.x;
649 bounds.r_ = windowContentRect.origin.x + windowContentRect.size.width;
650 }
651}
652
654{
655 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientWidth(): window invalid");
656
657 @autoreleasepool {
658 GHOST_Rect cBnds;
659 getClientBounds(cBnds);
660
661 if ((uint32_t(cBnds.getWidth())) != width) {
662 const NSSize size = {(CGFloat)width, (CGFloat)cBnds.getHeight()};
663 [window_ setContentSize:size];
664 }
665 }
666 return GHOST_kSuccess;
667}
668
670{
671 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientHeight(): window invalid");
672
673 @autoreleasepool {
674 GHOST_Rect cBnds;
675 getClientBounds(cBnds);
676
677 if ((uint32_t(cBnds.getHeight())) != height) {
678 const NSSize size = {(CGFloat)cBnds.getWidth(), (CGFloat)height};
679 [window_ setContentSize:size];
680 }
681 }
682 return GHOST_kSuccess;
683}
684
685GHOST_TSuccess GHOST_WindowCocoa::setClientSize(uint32_t width, uint32_t height)
686{
687 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setClientSize(): window invalid");
688
689 @autoreleasepool {
690 GHOST_Rect cBnds;
691 getClientBounds(cBnds);
692 if (((uint32_t(cBnds.getWidth())) != width) || ((uint32_t(cBnds.getHeight())) != height)) {
693 const NSSize size = {(CGFloat)width, (CGFloat)height};
694 [window_ setContentSize:size];
695 }
696 }
697 return GHOST_kSuccess;
698}
699
701{
702 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getState(): window invalid");
703
704 @autoreleasepool {
705 NSUInteger masks = window_.styleMask;
706
707 if (masks & NSWindowStyleMaskFullScreen) {
708 /* Lion style full-screen. */
709 if (!immediate_draw_) {
711 }
713 }
714 if (window_.isMiniaturized) {
716 }
717 if (window_.isZoomed) {
719 }
720 if (immediate_draw_) {
722 }
724 }
725}
726
728 int32_t inY,
729 int32_t &outX,
730 int32_t &outY) const
731{
732 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::screenToClient(): window invalid");
733
734 screenToClientIntern(inX, inY, outX, outY);
735
736 /* switch y to match ghost convention */
737 GHOST_Rect cBnds;
738 getClientBounds(cBnds);
739 outY = (cBnds.getHeight() - 1) - outY;
740}
741
743 int32_t inY,
744 int32_t &outX,
745 int32_t &outY) const
746{
747 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::clientToScreen(): window invalid");
748
749 /* switch y to match ghost convention */
750 GHOST_Rect cBnds;
751 getClientBounds(cBnds);
752 inY = (cBnds.getHeight() - 1) - inY;
753
754 clientToScreenIntern(inX, inY, outX, outY);
755}
756
758 int32_t inY,
759 int32_t &outX,
760 int32_t &outY) const
761{
762 NSRect screenCoord;
763 screenCoord.origin = {(CGFloat)inX, (CGFloat)inY};
764
765 const NSRect baseCoord = [window_ convertRectFromScreen:screenCoord];
766
767 outX = baseCoord.origin.x;
768 outY = baseCoord.origin.y;
769}
770
772 int32_t inY,
773 int32_t &outX,
774 int32_t &outY) const
775{
776 NSRect baseCoord;
777 baseCoord.origin = {(CGFloat)inX, (CGFloat)inY};
778
779 const NSRect screenCoord = [window_ convertRectToScreen:baseCoord];
780
781 outX = screenCoord.origin.x;
782 outY = screenCoord.origin.y;
783}
784
786{
787 return window_.screen;
788}
789
791{
792 /* The first element of the screens array is guaranteed to be the primary screen by AppKit. */
793 return [[NSScreen screens] firstObject];
794}
795
796/* called for event, when window leaves monitor to another */
798{
799 GHOST_Rect rect;
800 getClientBounds(rect);
801
802 CAMetalLayer *metalLayer = (CAMetalLayer *)metal_view_.layer;
803 native_pixel_size_ = float(metalLayer.drawableSize.width) / float(rect.getWidth());
804}
805
814{
815 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setState(): window invalid");
816
817 @autoreleasepool {
818 switch (state) {
820 [window_ miniaturize:nil];
821 break;
823 [window_ zoom:nil];
824 break;
825
827 const NSUInteger masks = window_.styleMask;
828
829 if (!(masks & NSWindowStyleMaskFullScreen)) {
830 [window_ toggleFullScreen:nil];
831 }
832 break;
833 }
835 default:
836 @autoreleasepool {
837 const NSUInteger masks = window_.styleMask;
838
839 if (masks & NSWindowStyleMaskFullScreen) {
840 /* Lion style full-screen. */
841 [window_ toggleFullScreen:nil];
842 }
843 else if (window_.isMiniaturized) {
844 [window_ deminiaturize:nil];
845 }
846 else if (window_.isZoomed) {
847 [window_ zoom:nil];
848 }
849 }
850 break;
851 }
852 }
853 return GHOST_kSuccess;
854}
855
857{
858 @autoreleasepool {
859 window_.documentEdited = is_unsaved_changes;
860 }
861 return GHOST_Window::setModifiedState(is_unsaved_changes);
862}
863
865{
866 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::setOrder(): window invalid");
867
868 @autoreleasepool {
869 if (order == GHOST_kWindowOrderTop) {
870 [NSApp activateIgnoringOtherApps:YES];
871 [window_ makeKeyAndOrderFront:nil];
872 }
873 else {
874 NSArray *windowsList;
875
876 [window_ orderBack:nil];
877
878 /* Check for other blender opened windows and make the front-most key. */
879 windowsList = [NSApp orderedWindows];
880 if (windowsList.count) {
881 [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
882 }
883 }
884 }
885 return GHOST_kSuccess;
886}
887
888/* --------------------------------------------------------------------
889 * Drawing context.
890 */
891
893{
894 NSSize viewSize = metal_view_.bounds.size;
895 NSSize backingSize = viewSize;
896
898 backingSize = [metal_view_ convertSizeToBacking:viewSize];
899 }
900
901 CAMetalLayer *metalLayer = (CAMetalLayer *)metal_view_.layer;
902
903 metalLayer.contentsScale = backingSize.height / viewSize.height;
904 metalLayer.drawableSize = NSSizeToCGSize(backingSize);
905}
906
908{
909 switch (type) {
910#ifdef WITH_VULKAN_BACKEND
911 case GHOST_kDrawingContextTypeVulkan: {
912 GHOST_Context *context = new GHOST_ContextVK(
914 if (context->initializeDrawingContext()) {
915 return context;
916 }
917 delete context;
918 return nullptr;
919 }
920#endif
921
922#ifdef WITH_METAL_BACKEND
923 case GHOST_kDrawingContextTypeMetal: {
924 GHOST_Context *context = new GHOST_ContextMTL(
926 if (context->initializeDrawingContext()) {
927 return context;
928 }
929 delete context;
930 return nullptr;
931 }
932#endif
933
934 default:
935 /* Unsupported backend. */
936 return nullptr;
937 }
938}
939
940/* --------------------------------------------------------------------
941 * Invalidate.
942 */
943
945{
946 GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::invalidate(): window invalid");
947
948 @autoreleasepool {
949 NSView *view = (opengl_view_) ? opengl_view_ : metal_view_;
950 view.needsDisplay = YES;
951 }
952 return GHOST_kSuccess;
953}
954
955/* --------------------------------------------------------------------
956 * Progress bar.
957 */
958
960{
961 @autoreleasepool {
962 if ((progress >= 0.0) && (progress <= 1.0)) {
963 NSImage *dockIcon = [[NSImage alloc] initWithSize:NSMakeSize(128, 128)];
964
965 [dockIcon lockFocus];
966
967 [[NSImage imageNamed:@"NSApplicationIcon"] drawAtPoint:NSZeroPoint
968 fromRect:NSZeroRect
969 operation:NSCompositingOperationSourceOver
970 fraction:1.0];
971
972 NSRect progressRect = {{8, 8}, {112, 14}};
973 NSBezierPath *progressPath;
974
975 /* Draw white track. */
976 [[[NSColor whiteColor] colorWithAlphaComponent:0.6] setFill];
977 progressPath = [NSBezierPath bezierPathWithRoundedRect:progressRect xRadius:7 yRadius:7];
978 [progressPath fill];
979
980 /* Black progress fill. */
981 [[[NSColor blackColor] colorWithAlphaComponent:0.7] setFill];
982 progressRect = NSInsetRect(progressRect, 2, 2);
983 progressRect.size.width *= progress;
984 progressPath = [NSBezierPath bezierPathWithRoundedRect:progressRect xRadius:5 yRadius:5];
985 [progressPath fill];
986
987 [dockIcon unlockFocus];
988 [NSApp setApplicationIconImage:dockIcon];
989 [dockIcon release];
990
992 }
993 }
994 return GHOST_kSuccess;
995}
996
998{
1000 return GHOST_kFailure;
1001 }
1002 progress_bar_visible_ = false;
1003
1004 /* Reset application icon to remove the progress bar. */
1005 @autoreleasepool {
1006 NSImage *dockIcon = [[NSImage alloc] initWithSize:NSMakeSize(128, 128)];
1007 [dockIcon lockFocus];
1008 [[NSImage imageNamed:@"NSApplicationIcon"] drawAtPoint:NSZeroPoint
1009 fromRect:NSZeroRect
1010 operation:NSCompositingOperationSourceOver
1011 fraction:1.0];
1012 [dockIcon unlockFocus];
1013 [NSApp setApplicationIconImage:dockIcon];
1014 [dockIcon release];
1015 }
1016 return GHOST_kSuccess;
1017}
1018
1019/* --------------------------------------------------------------------
1020 * Cursor handling.
1021 */
1022
1023/* busyButClickableCursor is an undocumented NSCursor API, but
1024 * has been in use since at least OS X 10.4 and through 10.9. */
1025@interface NSCursor (Undocumented)
1027@end
1028
1030{
1031 @autoreleasepool {
1032 switch (shape) {
1034 if (custom_cursor_) {
1035 return custom_cursor_;
1036 }
1037 else {
1038 return nullptr;
1039 }
1041 return [NSCursor disappearingItemCursor];
1043 return [NSCursor IBeamCursor];
1045 return [NSCursor crosshairCursor];
1047 return [NSCursor resizeUpDownCursor];
1049 return [NSCursor resizeLeftRightCursor];
1051 return [NSCursor resizeUpCursor];
1053 return [NSCursor resizeDownCursor];
1055 return [NSCursor resizeLeftCursor];
1057 return [NSCursor resizeRightCursor];
1059 return [NSCursor dragCopyCursor];
1061 return [NSCursor operationNotAllowedCursor];
1063 return [NSCursor openHandCursor];
1065 return [NSCursor openHandCursor];
1067 return [NSCursor closedHandCursor];
1069 return [NSCursor pointingHandCursor];
1071 return [NSCursor arrowCursor];
1073 if ([NSCursor respondsToSelector:@selector(busyButClickableCursor)]) {
1074 return [NSCursor busyButClickableCursor];
1075 }
1076 return nullptr;
1077 default:
1078 return nullptr;
1079 }
1080 }
1081}
1082
1084{
1085 static bool systemCursorVisible = true;
1086
1087 @autoreleasepool {
1088 if (visible != systemCursorVisible) {
1089 if (visible) {
1090 [NSCursor unhide];
1091 systemCursorVisible = true;
1092 }
1093 else {
1094 [NSCursor hide];
1095 systemCursorVisible = false;
1096 }
1097 }
1098
1099 NSCursor *cursor = getStandardCursor(shape);
1100 if (cursor == nullptr) {
1102 }
1103
1104 [cursor set];
1105 }
1106}
1107
1109{
1110 return is_dialog_;
1111}
1112
1114{
1115 @autoreleasepool {
1116 if (window_.isVisible) {
1117 loadCursor(visible, getCursorShape());
1118 }
1119 }
1120 return GHOST_kSuccess;
1121}
1122
1124{
1125 @autoreleasepool {
1126 if (mode != GHOST_kGrabDisable) {
1127 /* No need to perform grab without warp as it is always enabled in OS X. */
1128 if (mode != GHOST_kGrabNormal) {
1129 @autoreleasepool {
1131 setCursorGrabAccum(0, 0);
1132
1133 if (mode == GHOST_kGrabHide) {
1135 }
1136
1137 /* Make window key if it wasn't to get the mouse move events. */
1138 [window_ makeKeyWindow];
1139 }
1140 }
1141 }
1142 else {
1146 }
1147
1148 /* Almost works without but important otherwise the mouse GHOST location
1149 * can be incorrect on exit. */
1150 setCursorGrabAccum(0, 0);
1151 cursor_grab_bounds_.l_ = cursor_grab_bounds_.r_ = -1; /* disable */
1152 }
1153 }
1154 return GHOST_kSuccess;
1155}
1156
1158{
1159 @autoreleasepool {
1160 if (window_.isVisible) {
1162 }
1163 }
1164 return GHOST_kSuccess;
1165}
1166
1168{
1169 @autoreleasepool {
1171 return success;
1172 }
1173}
1174
1178static void cursor_bitmap_rgba_invert(uint32_t *buffer, const int size[2])
1179{
1180 for (int i = 0; i < size[1]; ++i) {
1181 for (int j = 0; j < size[0]; ++j) {
1182 buffer[(i * size[0]) + j] = buffer[(i * size[0]) + j] ^ 0x00FFFFFF;
1183 }
1184 }
1185}
1186
1188 const uint8_t * /*mask*/,
1189 const int size[2],
1190 const int hot_spot[2],
1191 const bool can_invert_color)
1192{
1193 @autoreleasepool {
1194 if (custom_cursor_) {
1195 [custom_cursor_ release];
1196 custom_cursor_ = nil;
1197 }
1198
1199 if (can_invert_color) {
1200 /* Flip white cursor with black outline to black cursor with
1201 * white outline to match macOS platform conventions. */
1202 cursor_bitmap_rgba_invert((uint32_t *)bitmap, size);
1203 }
1204
1205 NSBitmapImageRep *cursorImageRep = [[NSBitmapImageRep alloc]
1206 initWithBitmapDataPlanes:(unsigned char **)&bitmap
1207 pixelsWide:size[0]
1208 pixelsHigh:size[1]
1209 bitsPerSample:8
1210 samplesPerPixel:4
1211 hasAlpha:YES
1212 isPlanar:NO
1213 colorSpaceName:NSDeviceRGBColorSpace
1214 bytesPerRow:(size[0] * 4)
1215 bitsPerPixel:32];
1216
1217 /* The bitmap is already at HiDPI pixel resolution. NSImage/NSCursor work in points,
1218 * so set the NSImage's logical size to `pixels / backingScaleFactor` to prevent
1219 * AppKit from upscaling the cursor on Hi-DPI displays.
1220 *
1221 * Build the NSImage from a CGImage with size NSZeroSize so it initially adopts the
1222 * pixel dimensions, then shrink with `setSize:` to declare the logical point size. */
1223 const CGFloat scale = [window_ backingScaleFactor];
1224 const NSSize imSize = {(CGFloat)size[0] / scale, (CGFloat)size[1] / scale};
1225 CGImageRef cgImage = [cursorImageRep CGImage];
1226 NSImage *cursorImage = [[NSImage alloc] initWithCGImage:cgImage size:NSZeroSize];
1227 [cursorImage setSize:imSize];
1228
1229 const NSPoint hotSpotPoint = {(CGFloat)hot_spot[0] / scale, (CGFloat)hot_spot[1] / scale};
1230
1231 /* Foreground and background color parameter is not handled for now (10.6). */
1232 custom_cursor_ = [[NSCursor alloc] initWithImage:cursorImage hotSpot:hotSpotPoint];
1233
1234 [cursorImageRep release];
1235 [cursorImage release];
1236
1237 if (window_.isVisible) {
1239 }
1240 }
1241 return GHOST_kSuccess;
1242}
1243
1244#ifdef WITH_INPUT_IME
1245void GHOST_WindowCocoa::beginIME(int32_t x, int32_t y, int32_t w, int32_t h, bool completed)
1246{
1247 if (opengl_view_) {
1248 [opengl_view_ beginIME:x y:y w:w h:h completed:completed];
1249 }
1250 else {
1251 [metal_view_ beginIME:x y:y w:w h:h completed:completed];
1252 }
1253}
1254
1255void GHOST_WindowCocoa::endIME()
1256{
1257 if (opengl_view_) {
1258 [opengl_view_ endIME];
1259 }
1260 else {
1261 [metal_view_ endIME];
1262 }
1263}
1264#endif /* WITH_INPUT_IME */
#define GHOST_ASSERT(x, info)
GHOST_TWindowState
@ GHOST_kWindowStateMinimized
@ GHOST_kWindowStateMaximized
@ GHOST_kWindowStateNormal
@ GHOST_kWindowStateFullScreen
GHOST_TStandardCursor
@ GHOST_kStandardCursorHandClosed
@ GHOST_kStandardCursorHandOpen
@ GHOST_kStandardCursorCopy
@ GHOST_kStandardCursorWait
@ GHOST_kStandardCursorTopSide
@ GHOST_kStandardCursorStop
@ GHOST_kStandardCursorCrosshair
@ GHOST_kStandardCursorCustom
@ GHOST_kStandardCursorLeftRight
@ GHOST_kStandardCursorUpDown
@ GHOST_kStandardCursorHandPoint
@ GHOST_kStandardCursorBottomSide
@ GHOST_kStandardCursorMove
@ GHOST_kStandardCursorDefault
@ GHOST_kStandardCursorRightSide
@ GHOST_kStandardCursorDestroy
@ GHOST_kStandardCursorLeftSide
@ GHOST_kStandardCursorText
@ GHOST_kEventWindowClose
@ GHOST_kEventWindowMove
@ GHOST_kEventWindowSize
@ GHOST_kEventDraggingDropDone
@ GHOST_kEventDraggingExited
@ GHOST_kEventNativeResolutionChange
@ GHOST_kEventDraggingUpdated
@ GHOST_kEventDraggingEntered
@ GHOST_kEventWindowActivate
@ GHOST_kEventWindowUpdate
@ GHOST_kEventWindowDeactivate
GHOST_TDrawingContextType
GHOST_TWindowOrder
@ GHOST_kWindowOrderTop
GHOST_TSuccess
@ GHOST_kFailure
@ GHOST_kSuccess
GHOST_TGrabCursorMode
@ GHOST_kGrabDisable
@ GHOST_kGrabHide
@ GHOST_kGrabNormal
GHOST_TDragnDropTypes
@ GHOST_kDragnDropTypeUnknown
@ GHOST_kDragnDropTypeFilenames
@ GHOST_kDragnDropTypeBitmap
@ GHOST_kDragnDropTypeString
@ GHOST_kVSyncModeUnset
@ GHOST_kVSyncModeOff
@ GHOST_kDecorationColoredTitleBar
static void cursor_bitmap_rgba_invert(uint32_t *buffer, const int size[2])
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
Definition btDbvt.cpp:52
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
NSCursor * busyButClickableCursor()
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)
int32_t t_
int32_t r_
virtual int32_t getHeight() const
int32_t b_
int32_t l_
virtual int32_t getWidth() const
BlenderWindow * window_
bool isDialog() const override
GHOST_TSuccess setProgressBar(float progress) override
GHOST_TSuccess setWindowCursorShape(GHOST_TStandardCursor shape) override
GHOST_TSuccess setState(GHOST_TWindowState state) override
std::string getTitle() const override
GHOST_SystemCocoa * system_cocoa_
void setImmediateDraw(bool value)
GHOST_TSuccess setClientHeight(uint32_t height) override
void clientToScreen(int32_t inX, int32_t inY, int32_t &outX, int32_t &outY) const override
CAMetalLayer * metal_layer_
NSScreen * getScreen() const
void setTitle(const char *title) override
GHOST_TSuccess invalidate() override
GHOST_TSuccess endProgressBar() override
NSCursor * getStandardCursor(GHOST_TStandardCursor cursor) const
GHOST_TWindowState getState() const override
GHOST_TSuccess setClientWidth(uint32_t width) override
GHOST_TSuccess applyWindowDecorationStyle() override
GHOST_TSuccess hasCursorShape(GHOST_TStandardCursor shape) override
void clientToScreenIntern(int32_t inX, int32_t inY, int32_t &outX, int32_t &outY) const
void * getOSWindow() const override
CocoaOpenGLView * opengl_view_
void getClientBounds(GHOST_Rect &bounds) const override
GHOST_TSuccess setModifiedState(bool is_unsaved_changes) override
void screenToClient(int32_t inX, int32_t inY, int32_t &outX, int32_t &outY) const override
void getWindowBounds(GHOST_Rect &bounds) const override
GHOST_Context * newDrawingContext(GHOST_TDrawingContextType type) override
GHOST_TSuccess setWindowCursorGrab(GHOST_TGrabCursorMode mode) override
GHOST_TSuccess setWindowCustomCursorShape(const uint8_t *bitmap, const uint8_t *mask, const int size[2], const int hot_spot[2], bool can_invert_color) override
static NSScreen * getPrimaryScreen()
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)
GHOST_TSuccess setOrder(GHOST_TWindowOrder order) override
CocoaMetalView * metal_view_
void screenToClientIntern(int32_t inX, int32_t inY, int32_t &outX, int32_t &outY) const
GHOST_GPUDevice preferred_device_
void setPath(const char *filepath) override
bool getValid() const override
GHOST_TSuccess setWindowCursorVisibility(bool visible) override
GHOST_TabletData tablet_
void loadCursor(bool visible, GHOST_TStandardCursor cursor) const
GHOST_TSuccess setClientSize(uint32_t width, uint32_t height) override
GHOST_ContextParams want_context_params_
float native_pixel_size_
GHOST_TSuccess setModifiedState(bool is_unsaved_changes) override
void setCursorGrabAccum(int32_t x, int32_t y)
GHOST_WindowDecorationStyleSettings window_decoration_style_settings_
GHOST_TStandardCursor getCursorShape() const override
GHOST_TSuccess setDrawingContextType(GHOST_TDrawingContextType type) override
int32_t cursor_grab_init_pos_[2]
GHOST_TSuccess releaseNativeHandles()
GHOST_TWindowDecorationStyleFlags window_decoration_style_flags_
virtual bool canAcceptDragOperation() const
bool getValid() const override
bool getCursorVisibility() const override
GHOST_TSuccess activateDrawingContext() override
GHOST_TSuccess updateDrawingContext()
GHOST_Window(uint32_t width, uint32_t height, GHOST_TWindowState state, const GHOST_ContextParams &context_params, const bool exclusive=false)
GHOST_Rect cursor_grab_bounds_
bool progress_bar_visible_
GHOST_WindowHDRInfo hdr_info_
GHOST_TGrabCursorMode cursor_grab_
float3x3 scale(float3x3 mat, float2 scale)
GHOST_SystemCocoa * systemCocoa
GHOST_WindowCocoa * windowCocoa
GHOST_TDragnDropTypes draggedObjectType
GHOST_SystemCocoa * systemCocoa
GHOST_WindowCocoa * windowCocoa
const int state
BMesh const char void * data
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
GHOST_TVSyncModes vsync