1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/views/widget/native_widget_mac.h"
7 #import <Cocoa/Cocoa.h>
9 #include "base/mac/foundation_util.h"
10 #include "base/mac/scoped_nsobject.h"
11 #include "base/strings/sys_string_conversions.h"
12 #include "ui/gfx/font_list.h"
13 #import "ui/gfx/mac/coordinate_conversion.h"
14 #include "ui/native_theme/native_theme.h"
15 #import "ui/views/cocoa/bridged_content_view.h"
16 #import "ui/views/cocoa/bridged_native_widget.h"
17 #import "ui/views/cocoa/views_nswindow_delegate.h"
18 #include "ui/views/window/native_frame_view.h"
20 @interface NativeWidgetMacNSWindow : NSWindow
21 - (ViewsNSWindowDelegate*)viewsNSWindowDelegate;
24 @implementation NativeWidgetMacNSWindow
26 - (ViewsNSWindowDelegate*)viewsNSWindowDelegate {
27 return base::mac::ObjCCastStrict<ViewsNSWindowDelegate>([self delegate]);
30 // Override canBecome{Key,Main}Window to always return YES, otherwise Windows
31 // with a styleMask of NSBorderlessWindowMask default to NO.
32 - (BOOL)canBecomeKeyWindow {
36 - (BOOL)canBecomeMainWindow {
40 // Override orderWindow to intercept visibility changes, since there is no way
41 // to observe these changes via NSWindowDelegate.
42 - (void)orderWindow:(NSWindowOrderingMode)orderingMode
43 relativeTo:(NSInteger)otherWindowNumber {
44 [[self viewsNSWindowDelegate] onWindowOrderWillChange:orderingMode];
45 [super orderWindow:orderingMode relativeTo:otherWindowNumber];
46 [[self viewsNSWindowDelegate] onWindowOrderChanged];
54 NSInteger StyleMaskForParams(const Widget::InitParams& params) {
55 // TODO(tapted): Determine better masks when there are use cases for it.
56 if (params.remove_standard_frame)
57 return NSBorderlessWindowMask;
59 if (params.type == Widget::InitParams::TYPE_WINDOW) {
60 return NSTitledWindowMask | NSClosableWindowMask |
61 NSMiniaturizableWindowMask | NSResizableWindowMask;
63 return NSBorderlessWindowMask;
66 NSRect ValidateContentRect(NSRect content_rect) {
67 // A contentRect with zero width or height is a banned practice in Chrome, due
68 // to unpredictable OSX treatment. For now, silently give a minimum dimension.
69 // TODO(tapted): Add a DCHECK, or add emulation logic (e.g. to auto-hide).
70 if (NSWidth(content_rect) == 0)
71 content_rect.size.width = 1;
73 if (NSHeight(content_rect) == 0)
74 content_rect.size.height = 1;
79 gfx::Size WindowSizeForClientAreaSize(NSWindow* window, const gfx::Size& size) {
80 NSRect content_rect = NSMakeRect(0, 0, size.width(), size.height());
81 NSRect frame_rect = [window frameRectForContentRect:content_rect];
82 return gfx::Size(NSWidth(frame_rect), NSHeight(frame_rect));
87 ////////////////////////////////////////////////////////////////////////////////
88 // NativeWidgetMac, public:
90 NativeWidgetMac::NativeWidgetMac(internal::NativeWidgetDelegate* delegate)
91 : delegate_(delegate),
92 bridge_(new BridgedNativeWidget(this)),
93 ownership_(Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) {
96 NativeWidgetMac::~NativeWidgetMac() {
97 if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
103 void NativeWidgetMac::OnWindowWillClose() {
104 delegate_->OnNativeWidgetDestroying();
105 // Note: If closed via CloseNow(), |bridge_| will already be reset. If closed
106 // by the user, or via Close() and a RunLoop, this will reset it.
108 delegate_->OnNativeWidgetDestroyed();
109 if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
113 ////////////////////////////////////////////////////////////////////////////////
114 // NativeWidgetMac, internal::NativeWidgetPrivate implementation:
116 void NativeWidgetMac::InitNativeWidget(const Widget::InitParams& params) {
117 ownership_ = params.ownership;
119 NSInteger style_mask = StyleMaskForParams(params);
120 NSRect content_rect = ValidateContentRect(
121 [NSWindow contentRectForFrameRect:gfx::ScreenRectToNSRect(params.bounds)
122 styleMask:style_mask]);
124 base::scoped_nsobject<NSWindow> window([[NativeWidgetMacNSWindow alloc]
125 initWithContentRect:content_rect
127 backing:NSBackingStoreBuffered
129 [window setReleasedWhenClosed:NO]; // Owned by scoped_nsobject.
130 bridge_->Init(window, params);
132 delegate_->OnNativeWidgetCreated(true);
134 bridge_->SetFocusManager(GetWidget()->GetFocusManager());
136 DCHECK(GetWidget()->GetRootView());
137 bridge_->SetRootView(GetWidget()->GetRootView());
140 NonClientFrameView* NativeWidgetMac::CreateNonClientFrameView() {
141 return new NativeFrameView(GetWidget());
144 bool NativeWidgetMac::ShouldUseNativeFrame() const {
148 bool NativeWidgetMac::ShouldWindowContentsBeTransparent() const {
153 void NativeWidgetMac::FrameTypeChanged() {
157 Widget* NativeWidgetMac::GetWidget() {
158 return delegate_->AsWidget();
161 const Widget* NativeWidgetMac::GetWidget() const {
162 return delegate_->AsWidget();
165 gfx::NativeView NativeWidgetMac::GetNativeView() const {
166 // Returns a BridgedContentView, unless there is no views::RootView set.
167 return [GetNativeWindow() contentView];
170 gfx::NativeWindow NativeWidgetMac::GetNativeWindow() const {
171 return bridge_ ? bridge_->ns_window() : nil;
174 Widget* NativeWidgetMac::GetTopLevelWidget() {
175 NativeWidgetPrivate* native_widget = GetTopLevelNativeWidget(GetNativeView());
176 return native_widget ? native_widget->GetWidget() : NULL;
179 const ui::Compositor* NativeWidgetMac::GetCompositor() const {
184 ui::Compositor* NativeWidgetMac::GetCompositor() {
189 ui::Layer* NativeWidgetMac::GetLayer() {
194 void NativeWidgetMac::ReorderNativeViews() {
196 bridge_->SetRootView(GetWidget()->GetRootView());
199 void NativeWidgetMac::ViewRemoved(View* view) {
203 void NativeWidgetMac::SetNativeWindowProperty(const char* name, void* value) {
207 void* NativeWidgetMac::GetNativeWindowProperty(const char* name) const {
212 TooltipManager* NativeWidgetMac::GetTooltipManager() const {
217 void NativeWidgetMac::SetCapture() {
221 void NativeWidgetMac::ReleaseCapture() {
225 bool NativeWidgetMac::HasCapture() const {
230 InputMethod* NativeWidgetMac::CreateInputMethod() {
231 return bridge_ ? bridge_->CreateInputMethod() : NULL;
234 internal::InputMethodDelegate* NativeWidgetMac::GetInputMethodDelegate() {
235 return bridge_.get();
238 ui::InputMethod* NativeWidgetMac::GetHostInputMethod() {
239 return bridge_ ? bridge_->GetHostInputMethod() : NULL;
242 void NativeWidgetMac::CenterWindow(const gfx::Size& size) {
243 SetSize(WindowSizeForClientAreaSize(GetNativeWindow(), size));
244 // Note that this is not the precise center of screen, but it is the standard
245 // location for windows like dialogs to appear on screen for Mac.
246 // TODO(tapted): If there is a parent window, center in that instead.
247 [GetNativeWindow() center];
250 void NativeWidgetMac::GetWindowPlacement(gfx::Rect* bounds,
251 ui::WindowShowState* maximized) const {
255 bool NativeWidgetMac::SetWindowTitle(const base::string16& title) {
256 NSWindow* window = GetNativeWindow();
257 NSString* current_title = [window title];
258 NSString* new_title = SysUTF16ToNSString(title);
259 if ([current_title isEqualToString:new_title])
262 [window setTitle:new_title];
266 void NativeWidgetMac::SetWindowIcons(const gfx::ImageSkia& window_icon,
267 const gfx::ImageSkia& app_icon) {
271 void NativeWidgetMac::InitModalType(ui::ModalType modal_type) {
275 gfx::Rect NativeWidgetMac::GetWindowBoundsInScreen() const {
276 return gfx::ScreenRectFromNSRect([GetNativeWindow() frame]);
279 gfx::Rect NativeWidgetMac::GetClientAreaBoundsInScreen() const {
280 NSWindow* window = GetNativeWindow();
281 return gfx::ScreenRectFromNSRect(
282 [window contentRectForFrameRect:[window frame]]);
285 gfx::Rect NativeWidgetMac::GetRestoredBounds() const {
286 return bridge_ ? bridge_->GetRestoredBounds() : gfx::Rect();
289 void NativeWidgetMac::SetBounds(const gfx::Rect& bounds) {
290 [GetNativeWindow() setFrame:gfx::ScreenRectToNSRect(bounds)
295 void NativeWidgetMac::SetSize(const gfx::Size& size) {
296 // Ensure the top-left corner stays in-place (rather than the bottom-left,
297 // which -[NSWindow setContentSize:] would do).
298 SetBounds(gfx::Rect(GetWindowBoundsInScreen().origin(), size));
301 void NativeWidgetMac::StackAbove(gfx::NativeView native_view) {
305 void NativeWidgetMac::StackAtTop() {
309 void NativeWidgetMac::StackBelow(gfx::NativeView native_view) {
313 void NativeWidgetMac::SetShape(gfx::NativeRegion shape) {
317 void NativeWidgetMac::Close() {
321 // Clear the view early to suppress repaints.
322 bridge_->SetRootView(NULL);
324 NSWindow* window = GetNativeWindow();
325 // Calling performClose: will momentarily highlight the close button, but
326 // AppKit will reject it if there is no close button.
327 SEL close_selector = ([window styleMask] & NSClosableWindowMask)
328 ? @selector(performClose:)
330 [window performSelector:close_selector withObject:nil afterDelay:0];
333 void NativeWidgetMac::CloseNow() {
334 // Reset |bridge_| to NULL before destroying it.
335 scoped_ptr<BridgedNativeWidget> bridge(bridge_.Pass());
338 void NativeWidgetMac::Show() {
339 ShowWithWindowState(ui::SHOW_STATE_NORMAL);
342 void NativeWidgetMac::Hide() {
346 void NativeWidgetMac::ShowMaximizedWithBounds(
347 const gfx::Rect& restored_bounds) {
351 void NativeWidgetMac::ShowWithWindowState(ui::WindowShowState state) {
353 case ui::SHOW_STATE_DEFAULT:
354 case ui::SHOW_STATE_NORMAL:
355 case ui::SHOW_STATE_INACTIVE:
357 case ui::SHOW_STATE_MINIMIZED:
358 case ui::SHOW_STATE_MAXIMIZED:
359 case ui::SHOW_STATE_FULLSCREEN:
362 case ui::SHOW_STATE_END:
366 if (state == ui::SHOW_STATE_INACTIVE) {
368 [GetNativeWindow() orderBack:nil];
374 bool NativeWidgetMac::IsVisible() const {
375 return [GetNativeWindow() isVisible];
378 void NativeWidgetMac::Activate() {
379 [GetNativeWindow() makeKeyAndOrderFront:nil];
380 [NSApp activateIgnoringOtherApps:YES];
383 void NativeWidgetMac::Deactivate() {
387 bool NativeWidgetMac::IsActive() const {
388 // To behave like ::GetActiveWindow on Windows, IsActive() must return the
389 // "active" window attached to the calling application. NSWindow provides
390 // -isKeyWindow and -isMainWindow, but these are system-wide and update
391 // asynchronously. A window can not be main or key on Mac without the
392 // application being active.
393 // Here, define the active window as the frontmost visible window in the
395 // Note that this might not be the keyWindow, even when Chrome is active.
396 // Also note that -[NSApplication orderedWindows] excludes panels and other
397 // "unscriptable" windows, but includes invisible windows.
401 NSWindow* window = GetNativeWindow();
402 for (NSWindow* other_window in [NSApp orderedWindows]) {
403 if ([window isEqual:other_window])
406 if ([other_window isVisible])
413 void NativeWidgetMac::SetAlwaysOnTop(bool always_on_top) {
417 bool NativeWidgetMac::IsAlwaysOnTop() const {
422 void NativeWidgetMac::SetVisibleOnAllWorkspaces(bool always_visible) {
426 void NativeWidgetMac::Maximize() {
427 NOTIMPLEMENTED(); // See IsMaximized().
430 void NativeWidgetMac::Minimize() {
434 bool NativeWidgetMac::IsMaximized() const {
435 // The window frame isn't altered on Mac unless going fullscreen. The green
436 // "+" button just makes the window bigger. So, always false.
440 bool NativeWidgetMac::IsMinimized() const {
445 void NativeWidgetMac::Restore() {
449 void NativeWidgetMac::SetFullscreen(bool fullscreen) {
450 if (!bridge_ || fullscreen == IsFullscreen())
453 bridge_->ToggleDesiredFullscreenState();
456 bool NativeWidgetMac::IsFullscreen() const {
457 return bridge_ && bridge_->target_fullscreen_state();
460 void NativeWidgetMac::SetOpacity(unsigned char opacity) {
464 void NativeWidgetMac::SetUseDragFrame(bool use_drag_frame) {
468 void NativeWidgetMac::FlashFrame(bool flash_frame) {
472 void NativeWidgetMac::RunShellDrag(View* view,
473 const ui::OSExchangeData& data,
474 const gfx::Point& location,
476 ui::DragDropTypes::DragEventSource source) {
480 void NativeWidgetMac::SchedulePaintInRect(const gfx::Rect& rect) {
481 // TODO(tapted): This should use setNeedsDisplayInRect:, once the coordinate
482 // system of |rect| has been converted.
483 [GetNativeView() setNeedsDisplay:YES];
486 void NativeWidgetMac::SetCursor(gfx::NativeCursor cursor) {
490 bool NativeWidgetMac::IsMouseEventsEnabled() const {
495 void NativeWidgetMac::ClearNativeFocus() {
499 gfx::Rect NativeWidgetMac::GetWorkAreaBoundsInScreen() const {
504 Widget::MoveLoopResult NativeWidgetMac::RunMoveLoop(
505 const gfx::Vector2d& drag_offset,
506 Widget::MoveLoopSource source,
507 Widget::MoveLoopEscapeBehavior escape_behavior) {
509 return Widget::MOVE_LOOP_CANCELED;
512 void NativeWidgetMac::EndMoveLoop() {
516 void NativeWidgetMac::SetVisibilityChangedAnimationsEnabled(bool value) {
520 ui::NativeTheme* NativeWidgetMac::GetNativeTheme() const {
521 return ui::NativeTheme::instance();
524 void NativeWidgetMac::OnRootViewLayout() {
528 bool NativeWidgetMac::IsTranslucentWindowOpacitySupported() const {
532 void NativeWidgetMac::OnSizeConstraintsChanged() {
536 void NativeWidgetMac::RepostNativeEvent(gfx::NativeEvent native_event) {
540 ////////////////////////////////////////////////////////////////////////////////
543 bool Widget::ConvertRect(const Widget* source,
544 const Widget* target,
551 ////////////////////////////////////////////////////////////////////////////////
552 // internal::NativeWidgetPrivate, public:
555 NativeWidgetPrivate* NativeWidgetPrivate::CreateNativeWidget(
556 internal::NativeWidgetDelegate* delegate) {
557 return new NativeWidgetMac(delegate);
561 NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeView(
562 gfx::NativeView native_view) {
563 return GetNativeWidgetForNativeWindow([native_view window]);
567 NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeWindow(
568 gfx::NativeWindow native_window) {
569 id<NSWindowDelegate> window_delegate = [native_window delegate];
570 if ([window_delegate respondsToSelector:@selector(nativeWidgetMac)]) {
571 ViewsNSWindowDelegate* delegate =
572 base::mac::ObjCCastStrict<ViewsNSWindowDelegate>(window_delegate);
573 return [delegate nativeWidgetMac];
575 return NULL; // Not created by NativeWidgetMac.
579 NativeWidgetPrivate* NativeWidgetPrivate::GetTopLevelNativeWidget(
580 gfx::NativeView native_view) {
581 NativeWidgetPrivate* native_widget =
582 GetNativeWidgetForNativeView(native_view);
586 for (NativeWidgetPrivate* parent;
587 (parent = GetNativeWidgetForNativeWindow(
588 [native_widget->GetNativeWindow() parentWindow]));
589 native_widget = parent) {
591 return native_widget;
595 void NativeWidgetPrivate::GetAllChildWidgets(gfx::NativeView native_view,
596 Widget::Widgets* children) {
597 NativeWidgetPrivate* native_widget =
598 GetNativeWidgetForNativeView(native_view);
602 // Code expects widget for |native_view| to be added to |children|.
603 if (native_widget->GetWidget())
604 children->insert(native_widget->GetWidget());
606 for (NSWindow* child_window : [native_widget->GetNativeWindow() childWindows])
607 GetAllChildWidgets([child_window contentView], children);
611 void NativeWidgetPrivate::GetAllOwnedWidgets(gfx::NativeView native_view,
612 Widget::Widgets* owned) {
617 void NativeWidgetPrivate::ReparentNativeView(gfx::NativeView native_view,
618 gfx::NativeView new_parent) {
623 bool NativeWidgetPrivate::IsMouseButtonDown() {
624 return [NSEvent pressedMouseButtons] != 0;
628 gfx::FontList NativeWidgetPrivate::GetWindowTitleFontList() {
630 return gfx::FontList();
633 } // namespace internal