// // Created by Dan Walmsley on 04/05/2022. // Copyright (c) 2022 Avalonia. All rights reserved. // #import #import #include "common.h" #include "AvnView.h" #include "menu.h" #include "automation.h" #include "cursor.h" #include "ResizeScope.h" #include "AutoFitContentView.h" #import "WindowProtocol.h" #import "WindowInterfaces.h" #include "WindowBaseImpl.h" #include "WindowImpl.h" #include "AvnTextInputMethod.h" #include "AvnView.h" #include @class AutoFitContentView; // Activates the app, but defers until the run loop is running if it isn't yet. // Windows are shown (and the app activated) from OnFrameworkInitializationCompleted, // which runs before -[NSApplication run]. Activating that early yields a "degraded" // activation: the app looks frontmost but the WindowServer never does a real // become-active, which leaves the out-of-process file picker unable to receive // clicks in its file list/sidebar until a manual app switch. Deferring makes the first // activation a clean transition. static void ActivateApplication() { if ([NSApp isRunning]) { [NSApp activateIgnoringOtherApps:YES]; } else { dispatch_async(dispatch_get_main_queue(), ^{ [NSApp activateIgnoringOtherApps:YES]; }); } } WindowBaseImpl::~WindowBaseImpl() { View = nullptr; Window = nullptr; } WindowBaseImpl::WindowBaseImpl(const ComPtr& events, bool usePanel) : TopLevelImpl(events) { _children = std::list>(); _shown = false; _inResize = false; BaseEvents = events; lastPositionSet = { 0, 0 }; hasPosition = false; lastSize = NSSize { 100, 100 }; lastMaxSize = NSSize { CGFLOAT_MAX, CGFLOAT_MAX}; lastMinSize = NSSize { 0, 0 }; lastMenu = nullptr; CreateNSWindow(usePanel); StandardContainer = [[AutoFitContentView new] initWithContent:View]; [Window setContentView:StandardContainer]; [Window setBackingType:NSBackingStoreBuffered]; [Window setContentMinSize:lastMinSize]; [Window setContentMaxSize:lastMaxSize]; [Window setOpaque:false]; } NSWindow *WindowBaseImpl::GetNSWindow() { return Window; } HRESULT WindowBaseImpl::ObtainNSWindowHandleRetained(void **ret) { if (ret == nullptr) { return E_POINTER; } *ret = (__bridge_retained void *) Window; return S_OK; } HRESULT WindowBaseImpl::Show(bool activate, bool isDialog) { @autoreleasepool { [Window setContentSize:lastSize]; if(hasPosition) { SetPosition(lastPositionSet); } else { [Window center]; } // When showing a window, disallow fullscreen because if the window is being // shown while another window is fullscreen, macOS will briefly transition this // new window to fullscreen and then it will be transitioned back. This breaks // input events for a short time as described in this issue: // // https://yt.avaloniaui.net/issue/OUTSYSTEMS-40 // // We restore the collection behavior at the end of this method. auto collectionBehavior = [Window collectionBehavior]; [Window setCollectionBehavior:collectionBehavior & ~NSWindowCollectionBehaviorFullScreenPrimary]; UpdateAppearance(); [Window invalidateShadow]; if (ShouldTakeFocusOnShow() && activate) { [Window orderFront:Window]; [Window makeKeyAndOrderFront:Window]; [Window makeFirstResponder:View]; ActivateApplication(); } else { [Window orderFront:Window]; } _shown = true; [Window setCollectionBehavior:collectionBehavior]; // Ensure that we call needsDisplay = YES so that AvnView.updateLayer is called after the // window is shown: if the client is pumping messages during the window creation/show // process, it's possible that updateLayer gets called after the window is created but // before it's is shown. [View.layer setNeedsDisplay]; return S_OK; } } bool WindowBaseImpl::IsShown () { return _shown; } bool WindowBaseImpl::ShouldTakeFocusOnShow() { return true; } HRESULT WindowBaseImpl::ObtainNSWindowHandle(void **ret) { if (ret == nullptr) { return E_POINTER; } *ret = (__bridge void *) Window; return S_OK; } HRESULT WindowBaseImpl::Hide() { @autoreleasepool { if (Window != nullptr) { // If window is hidden without ending attached sheet first, it will stuck in "order out" state, // and block any new sheets from being attached. // Additionaly, we don't know if user would define any custom panels, so we only end/close file dialog sheets. auto attachedSheet = Window.attachedSheet; if (attachedSheet && ([attachedSheet isKindOfClass: [NSOpenPanel class]] || [attachedSheet isKindOfClass: [NSSavePanel class]])) { [Window endSheet:attachedSheet]; [attachedSheet close]; } auto frame = [Window frame]; AvnPoint point; point.X = frame.origin.x; point.Y = frame.origin.y + frame.size.height; lastPositionSet = ConvertPointY(point); hasPosition = true; [Window orderOut:Window]; } return S_OK; } } HRESULT WindowBaseImpl::Activate() { @autoreleasepool { if (Window != nullptr) { [Window makeKeyAndOrderFront:nil]; ActivateApplication(); } } return S_OK; } HRESULT WindowBaseImpl::SetTopMost(bool value) { @autoreleasepool { _isTopmost = value; UpdateWindowLevel(); return S_OK; } } NSWindowLevel WindowBaseImpl::GetBaseWindowLevel() { return _isTopmost ? NSFloatingWindowLevel : NSNormalWindowLevel; } void WindowBaseImpl::UpdateWindowLevel() { if (Window == nullptr) return; auto level = GetBaseWindowLevel(); // An owned window must be able to come to the front of its owner. // TODO: It shouldn't be necessary if we used `addChildWindow` API. auto parent = Parent.tryGet(); if (parent != nullptr && parent->Window != nullptr) level = std::max(level, [parent->Window level]); [Window setLevel:level]; for (auto iterator = _children.begin(); iterator != _children.end(); iterator++) { auto child = (*iterator).tryGet(); if (child != nullptr) child->UpdateWindowLevel(); } } HRESULT WindowBaseImpl::Close() { @autoreleasepool { if (Window != nullptr) { auto window = Window; Window = nullptr; try { // Seems to throw sometimes on application exit. [window close]; } catch (NSException *) {} } return S_OK; } } HRESULT WindowBaseImpl::GetFrameSize(AvnSize *ret) { @autoreleasepool { if (ret == nullptr) return E_POINTER; if(Window != nullptr && _shown){ auto frame = [Window frame]; ret->Width = frame.size.width; ret->Height = frame.size.height; } return S_OK; } } HRESULT WindowBaseImpl::SetMinMaxSize(AvnSize minSize, AvnSize maxSize) { @autoreleasepool { lastMinSize = ToNSSize(minSize); lastMaxSize = ToNSSize(maxSize); if(Window != nullptr) { [Window setContentMinSize:lastMinSize]; [Window setContentMaxSize:lastMaxSize]; } return S_OK; } } HRESULT WindowBaseImpl::Resize(double x, double y, AvnPlatformResizeReason reason) { if (_inResize) { return S_OK; } _inResize = true; auto resizeBlock = ResizeScope(View, reason); @autoreleasepool { auto maxSize = lastMaxSize; auto minSize = lastMinSize; if (x < minSize.width) { x = minSize.width; } if (y < minSize.height) { y = minSize.height; } if (x > maxSize.width) { x = maxSize.width; } if (y > maxSize.height) { y = maxSize.height; } @try { if(x != lastSize.width || y != lastSize.height) { if (!_shown) { auto screenSize = [Window screen].visibleFrame.size; if (x > screenSize.width) { x = screenSize.width; } if (y > screenSize.height) { y = screenSize.height; } } lastSize = NSSize{x, y}; SetClientSize(lastSize); [Window invalidateShadow]; } } @finally { _inResize = false; } return S_OK; } } HRESULT WindowBaseImpl::SetMainMenu(const ComPtr& menu) { auto nativeMenu = menu.dynamicCast(); lastMenu = nativeMenu ? nativeMenu->GetNative() : nil; if(Window != nullptr) { [GetWindowProtocol() applyMenu:lastMenu]; if ([Window isKeyWindow]) { [GetWindowProtocol() showWindowMenuWithAppMenu]; } } return S_OK; } HRESULT WindowBaseImpl::BeginMoveDrag() { @autoreleasepool { auto lastEvent = [View lastMouseDownEvent]; if (lastEvent == nullptr) { // A press that begins inside an embedded native view (for example a webview hosted // through NativeControlHost) is consumed by that view and never delivered to the // Avalonia view, so no mouse-down is recorded; fall back to the event the // application is tracking right now, provided it is a left-button press or drag // that belongs to this window. auto currentEvent = [NSApp currentEvent]; if (currentEvent != nullptr && [currentEvent window] == Window && ([currentEvent type] == NSEventTypeLeftMouseDown || [currentEvent type] == NSEventTypeLeftMouseDragged)) { lastEvent = currentEvent; } } if (lastEvent == nullptr) { return S_OK; } [Window performWindowDragWithEvent:lastEvent]; return S_OK; } } HRESULT WindowBaseImpl::BeginResizeDrag(__attribute__((unused)) AvnWindowEdge edge) { return S_OK; } HRESULT WindowBaseImpl::GetPosition(AvnPoint *ret) { @autoreleasepool { if (ret == nullptr) { return E_POINTER; } if(Window != nullptr) { auto frame = [Window frame]; ret->X = frame.origin.x; ret->Y = frame.origin.y + frame.size.height; *ret = ConvertPointY(*ret); } else { *ret = lastPositionSet; } return S_OK; } } HRESULT WindowBaseImpl::SetPosition(AvnPoint point) { @autoreleasepool { lastPositionSet = point; hasPosition = true; if(Window != nullptr) { [Window setFrameTopLeftPoint:ToNSPoint(ConvertPointY(point))]; } return S_OK; } } HRESULT WindowBaseImpl::SetTransparencyMode(AvnWindowTransparencyMode mode) { [Window setBackgroundColor: (mode != Transparent ? [NSColor windowBackgroundColor] : [NSColor clearColor])]; [StandardContainer ShowBlur: mode == Blur]; return S_OK; } HRESULT WindowBaseImpl::SetFrameThemeVariant(AvnPlatformThemeVariant variant) { NSAppearanceName appearanceName; if (@available(macOS 10.14, *)) { appearanceName = variant == AvnPlatformThemeVariant::Dark ? NSAppearanceNameDarkAqua : NSAppearanceNameAqua; } else { appearanceName = variant == AvnPlatformThemeVariant::Dark ? NSAppearanceNameVibrantDark : NSAppearanceNameAqua; } [Window setAppearance: [NSAppearance appearanceNamed: appearanceName]]; return S_OK; } bool WindowBaseImpl::IsModal() { return false; } void WindowBaseImpl::UpdateAppearance() { [Window setStyleMask:CalculateStyleMask()]; } void WindowBaseImpl::SetClientSize(NSSize size){ [Window setContentSize:lastSize]; } void WindowBaseImpl::CleanNSWindow() { if(Window != nullptr) { [GetWindowProtocol() disconnectParent]; [Window close]; Window = nullptr; } } void WindowBaseImpl::CreateNSWindow(bool usePanel) { // Anchor the content rect to the primary screen's origin. It's usually at (0,0), but can be offset while the // display server is mid-reconfiguration. This ensures the window is always on a proper screen. // See https://github.com/AvaloniaUI/Avalonia/issues/18895 NSPoint origin = NSZeroPoint; NSArray* screens = [NSScreen screens]; if (screens.count > 0) origin = screens.firstObject.frame.origin; NSRect contentRect = NSRect { origin.x, origin.y, lastSize }; if (usePanel) { Window = [[AvnPanel alloc] initWithParent:comself(this) contentRect:contentRect styleMask:NSWindowStyleMaskBorderless]; [Window setHidesOnDeactivate:false]; } else { Window = [[AvnWindow alloc] initWithParent:comself(this) contentRect:contentRect styleMask:NSWindowStyleMaskBorderless]; } } id WindowBaseImpl::GetWindowProtocol() { if(Window == nullptr) { return nullptr; } return (id ) Window; } void WindowBaseImpl::BringToFront() { // do nothing. } HRESULT WindowBaseImpl::SetParent(const ComPtr& parent) { @autoreleasepool { auto oldParent = Parent.tryGet(); if(oldParent != nullptr) { oldParent->_children.remove(comself(this)); } auto cparent = parent.dynamicCast(); Parent = cparent; if(cparent != nullptr && Window != nullptr){ // If one tries to show a child window with a minimized parent window, then the parent window will be // restored but macOS isn't kind enough to *tell* us that, so the window will be left in a non-interactive // state. Detect this and explicitly restore the parent window ourselves to avoid this situation. if (cparent->WindowState() == Minimized) cparent->SetWindowState(Normal); [Window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary]; cparent->_children.push_back(comself(this)); UpdateAppearance(); } UpdateWindowLevel(); return S_OK; } }