Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / browser / ui / cocoa / apps / native_app_window_cocoa.mm
blobecd390eff3b41b9a1d54f83c8de52b362bc64993
1 // Copyright 2013 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 "chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h"
7 #include "apps/app_shim/extension_app_shim_handler_mac.h"
8 #include "base/command_line.h"
9 #include "base/mac/mac_util.h"
10 #include "base/strings/sys_string_conversions.h"
11 #include "chrome/browser/profiles/profile.h"
12 #include "chrome/browser/ui/cocoa/browser_window_utils.h"
13 #import "chrome/browser/ui/cocoa/chrome_event_processing_window.h"
14 #include "chrome/browser/ui/cocoa/extensions/extension_keybinding_registry_cocoa.h"
15 #include "chrome/browser/ui/cocoa/extensions/extension_view_mac.h"
16 #import "chrome/browser/ui/cocoa/nsview_additions.h"
17 #include "chrome/common/chrome_switches.h"
18 #include "content/public/browser/native_web_keyboard_event.h"
19 #include "content/public/browser/render_widget_host_view.h"
20 #include "content/public/browser/web_contents.h"
21 #include "extensions/common/extension.h"
22 #include "third_party/skia/include/core/SkRegion.h"
23 #include "ui/gfx/skia_util.h"
25 // NOTE: State Before Update.
27 // Internal state, such as |is_maximized_|, must be set before the window
28 // state is changed so that it is accurate when e.g. a resize results in a call
29 // to |OnNativeWindowChanged|.
31 // NOTE: Maximize and Zoom.
33 // Zooming is implemented manually in order to implement maximize functionality
34 // and to support non resizable windows. The window will be resized explicitly
35 // in the |WindowWillZoom| call.
37 // Attempting maximize and restore functionality with non resizable windows
38 // using the native zoom method did not work, even with
39 // windowWillUseStandardFrame, as the window would not restore back to the
40 // desired size.
42 using apps::AppWindow;
44 @interface NSWindow (NSPrivateApis)
45 - (void)setBottomCornerRounded:(BOOL)rounded;
46 @end
48 // Replicate specific 10.7 SDK declarations for building with prior SDKs.
49 #if !defined(MAC_OS_X_VERSION_10_7) || \
50     MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
52 @interface NSWindow (LionSDKDeclarations)
53 - (void)toggleFullScreen:(id)sender;
54 @end
56 enum {
57   NSWindowCollectionBehaviorFullScreenPrimary = 1 << 7,
58   NSFullScreenWindowMask = 1 << 14
61 #endif  // MAC_OS_X_VERSION_10_7
63 namespace {
65 void SetFullScreenCollectionBehavior(NSWindow* window, bool allow_fullscreen) {
66   NSWindowCollectionBehavior behavior = [window collectionBehavior];
67   if (allow_fullscreen)
68     behavior |= NSWindowCollectionBehaviorFullScreenPrimary;
69   else
70     behavior &= ~NSWindowCollectionBehaviorFullScreenPrimary;
71   [window setCollectionBehavior:behavior];
74 void InitCollectionBehavior(NSWindow* window) {
75   // Since always-on-top windows have a higher window level
76   // than NSNormalWindowLevel, they will default to
77   // NSWindowCollectionBehaviorTransient. Set the value
78   // explicitly here to match normal windows.
79   NSWindowCollectionBehavior behavior = [window collectionBehavior];
80   behavior |= NSWindowCollectionBehaviorManaged;
81   [window setCollectionBehavior:behavior];
84 // Returns the level for windows that are configured to be always on top.
85 // This is not a constant because NSFloatingWindowLevel is a macro defined
86 // as a function call.
87 NSInteger AlwaysOnTopWindowLevel() {
88   return NSFloatingWindowLevel;
91 NSRect GfxToCocoaBounds(gfx::Rect bounds) {
92   typedef apps::AppWindow::BoundsSpecification BoundsSpecification;
94   NSRect main_screen_rect = [[[NSScreen screens] objectAtIndex:0] frame];
96   // If coordinates are unspecified, center window on primary screen.
97   if (bounds.x() == BoundsSpecification::kUnspecifiedPosition)
98     bounds.set_x(floor((NSWidth(main_screen_rect) - bounds.width()) / 2));
99   if (bounds.y() == BoundsSpecification::kUnspecifiedPosition)
100     bounds.set_y(floor((NSHeight(main_screen_rect) - bounds.height()) / 2));
102   // Convert to Mac coordinates.
103   NSRect cocoa_bounds = NSRectFromCGRect(bounds.ToCGRect());
104   cocoa_bounds.origin.y = NSHeight(main_screen_rect) - NSMaxY(cocoa_bounds);
105   return cocoa_bounds;
108 // Return a vector of non-draggable regions that fill a window of size
109 // |width| by |height|, but leave gaps where the window should be draggable.
110 std::vector<gfx::Rect> CalculateNonDraggableRegions(
111     const std::vector<extensions::DraggableRegion>& regions,
112     int width,
113     int height) {
114   std::vector<gfx::Rect> result;
115   if (regions.empty()) {
116     result.push_back(gfx::Rect(0, 0, width, height));
117   } else {
118     scoped_ptr<SkRegion> draggable(
119         AppWindow::RawDraggableRegionsToSkRegion(regions));
120     scoped_ptr<SkRegion> non_draggable(new SkRegion);
121     non_draggable->op(0, 0, width, height, SkRegion::kUnion_Op);
122     non_draggable->op(*draggable, SkRegion::kDifference_Op);
123     for (SkRegion::Iterator it(*non_draggable); !it.done(); it.next()) {
124       result.push_back(gfx::SkIRectToRect(it.rect()));
125     }
126   }
127   return result;
130 }  // namespace
132 @implementation NativeAppWindowController
134 @synthesize appWindow = appWindow_;
136 - (void)windowWillClose:(NSNotification*)notification {
137   if (appWindow_)
138     appWindow_->WindowWillClose();
141 - (void)windowDidBecomeKey:(NSNotification*)notification {
142   if (appWindow_)
143     appWindow_->WindowDidBecomeKey();
146 - (void)windowDidResignKey:(NSNotification*)notification {
147   if (appWindow_)
148     appWindow_->WindowDidResignKey();
151 - (void)windowDidResize:(NSNotification*)notification {
152   if (appWindow_)
153     appWindow_->WindowDidResize();
156 - (void)windowDidEndLiveResize:(NSNotification*)notification {
157   if (appWindow_)
158     appWindow_->WindowDidFinishResize();
161 - (void)windowDidEnterFullScreen:(NSNotification*)notification {
162   if (appWindow_)
163     appWindow_->WindowDidFinishResize();
166 - (void)windowDidExitFullScreen:(NSNotification*)notification {
167   if (appWindow_)
168     appWindow_->WindowDidFinishResize();
171 - (void)windowDidMove:(NSNotification*)notification {
172   if (appWindow_)
173     appWindow_->WindowDidMove();
176 - (void)windowDidMiniaturize:(NSNotification*)notification {
177   if (appWindow_)
178     appWindow_->WindowDidMiniaturize();
181 - (void)windowDidDeminiaturize:(NSNotification*)notification {
182   if (appWindow_)
183     appWindow_->WindowDidDeminiaturize();
186 - (BOOL)windowShouldZoom:(NSWindow*)window
187                  toFrame:(NSRect)newFrame {
188   if (appWindow_)
189     appWindow_->WindowWillZoom();
190   return NO;  // See top of file NOTE: Maximize and Zoom.
193 // Allow non resizable windows (without NSResizableWindowMask) to enter
194 // fullscreen by passing through the full size in willUseFullScreenContentSize.
195 - (NSSize)window:(NSWindow *)window
196     willUseFullScreenContentSize:(NSSize)proposedSize {
197   return proposedSize;
200 - (void)executeCommand:(int)command {
201   // No-op, swallow the event.
204 - (BOOL)handledByExtensionCommand:(NSEvent*)event {
205   if (appWindow_)
206     return appWindow_->HandledByExtensionCommand(event);
207   return NO;
210 @end
212 // This is really a method on NSGrayFrame, so it should only be called on the
213 // view passed into -[NSWindow drawCustomFrameRect:forView:].
214 @interface NSView (PrivateMethods)
215 - (CGFloat)roundedCornerRadius;
216 @end
218 // TODO(jamescook): Should these be AppNSWindow to match apps::AppWindow?
219 // http://crbug.com/344082
220 @interface ShellNSWindow : ChromeEventProcessingWindow
221 @end
222 @implementation ShellNSWindow
223 @end
225 @interface ShellCustomFrameNSWindow : ShellNSWindow
227 - (void)drawCustomFrameRect:(NSRect)rect forView:(NSView*)view;
229 @end
231 @implementation ShellCustomFrameNSWindow
233 - (void)drawCustomFrameRect:(NSRect)rect forView:(NSView*)view {
234   [[NSBezierPath bezierPathWithRect:rect] addClip];
235   [[NSColor clearColor] set];
236   NSRectFill(rect);
238   // Set up our clip.
239   CGFloat cornerRadius = 4.0;
240   if ([view respondsToSelector:@selector(roundedCornerRadius)])
241     cornerRadius = [view roundedCornerRadius];
242   [[NSBezierPath bezierPathWithRoundedRect:[view bounds]
243                                    xRadius:cornerRadius
244                                    yRadius:cornerRadius] addClip];
245   [[NSColor whiteColor] set];
246   NSRectFill(rect);
249 @end
251 @interface ShellFramelessNSWindow : ShellCustomFrameNSWindow
253 @end
255 @implementation ShellFramelessNSWindow
257 + (NSRect)frameRectForContentRect:(NSRect)contentRect
258                         styleMask:(NSUInteger)mask {
259   return contentRect;
262 + (NSRect)contentRectForFrameRect:(NSRect)frameRect
263                         styleMask:(NSUInteger)mask {
264   return frameRect;
267 - (NSRect)frameRectForContentRect:(NSRect)contentRect {
268   return contentRect;
271 - (NSRect)contentRectForFrameRect:(NSRect)frameRect {
272   return frameRect;
275 @end
277 @interface ControlRegionView : NSView
278 @end
280 @implementation ControlRegionView
282 - (BOOL)mouseDownCanMoveWindow {
283   return NO;
286 - (NSView*)hitTest:(NSPoint)aPoint {
287   return nil;
290 @end
292 @interface NSView (WebContentsView)
293 - (void)setMouseDownCanMoveWindow:(BOOL)can_move;
294 @end
296 NativeAppWindowCocoa::NativeAppWindowCocoa(
297     AppWindow* app_window,
298     const AppWindow::CreateParams& params)
299     : app_window_(app_window),
300       has_frame_(params.frame == AppWindow::FRAME_CHROME),
301       is_hidden_(false),
302       is_hidden_with_app_(false),
303       is_maximized_(false),
304       is_fullscreen_(false),
305       is_resizable_(params.resizable),
306       shows_resize_controls_(true),
307       shows_fullscreen_controls_(true),
308       attention_request_id_(0) {
309   Observe(WebContents());
311   base::scoped_nsobject<NSWindow> window;
312   Class window_class;
313   if (has_frame_) {
314     bool should_use_native_frame =
315         CommandLine::ForCurrentProcess()->HasSwitch(
316             switches::kAppsUseNativeFrame);
317     window_class = should_use_native_frame ?
318         [ShellNSWindow class] : [ShellCustomFrameNSWindow class];
319   } else {
320     window_class = [ShellFramelessNSWindow class];
321   }
323   // Estimate the initial bounds of the window. Once the frame insets are known,
324   // the window bounds and constraints can be set precisely.
325   NSRect cocoa_bounds = GfxToCocoaBounds(
326       params.GetInitialWindowBounds(gfx::Insets()));
327   window.reset([[window_class alloc]
328       initWithContentRect:cocoa_bounds
329                 styleMask:GetWindowStyleMask()
330                   backing:NSBackingStoreBuffered
331                     defer:NO]);
333   std::string name;
334   const extensions::Extension* extension = app_window_->GetExtension();
335   if (extension)
336     name = extension->name();
337   [window setTitle:base::SysUTF8ToNSString(name)];
338   [[window contentView] cr_setWantsLayer:YES];
340   if (base::mac::IsOSSnowLeopard() &&
341       [window respondsToSelector:@selector(setBottomCornerRounded:)])
342     [window setBottomCornerRounded:NO];
344   if (params.always_on_top)
345     [window setLevel:AlwaysOnTopWindowLevel()];
346   InitCollectionBehavior(window);
348   window_controller_.reset(
349       [[NativeAppWindowController alloc] initWithWindow:window.release()]);
351   NSView* view = WebContents()->GetNativeView();
352   [view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
354   InstallView();
356   [[window_controller_ window] setDelegate:window_controller_];
357   [window_controller_ setAppWindow:this];
359   // We can now compute the precise window bounds and constraints.
360   gfx::Insets insets = GetFrameInsets();
361   SetBounds(params.GetInitialWindowBounds(insets));
362   SetContentSizeConstraints(params.GetContentMinimumSize(insets),
363                             params.GetContentMaximumSize(insets));
365   // Initialize |restored_bounds_|.
366   restored_bounds_ = [this->window() frame];
368   extension_keybinding_registry_.reset(new ExtensionKeybindingRegistryCocoa(
369       Profile::FromBrowserContext(app_window_->browser_context()),
370       window,
371       extensions::ExtensionKeybindingRegistry::PLATFORM_APPS_ONLY,
372       NULL));
375 NSUInteger NativeAppWindowCocoa::GetWindowStyleMask() const {
376   NSUInteger style_mask = NSTitledWindowMask | NSClosableWindowMask |
377                           NSMiniaturizableWindowMask;
378   if (shows_resize_controls_)
379     style_mask |= NSResizableWindowMask;
380   if (!has_frame_ ||
381       !CommandLine::ForCurrentProcess()->HasSwitch(
382           switches::kAppsUseNativeFrame)) {
383     style_mask |= NSTexturedBackgroundWindowMask;
384   }
385   return style_mask;
388 void NativeAppWindowCocoa::InstallView() {
389   NSView* view = WebContents()->GetNativeView();
390   if (has_frame_) {
391     [view setFrame:[[window() contentView] bounds]];
392     [[window() contentView] addSubview:view];
393     if (!shows_fullscreen_controls_)
394       [[window() standardWindowButton:NSWindowZoomButton] setEnabled:NO];
395     if (!shows_resize_controls_)
396       [window() setShowsResizeIndicator:NO];
397   } else {
398     // TODO(jeremya): find a cleaner way to send this information to the
399     // WebContentsViewCocoa view.
400     DCHECK([view
401         respondsToSelector:@selector(setMouseDownCanMoveWindow:)]);
402     [view setMouseDownCanMoveWindow:YES];
404     NSView* frameView = [[window() contentView] superview];
405     [view setFrame:[frameView bounds]];
406     [frameView addSubview:view];
408     [[window() standardWindowButton:NSWindowZoomButton] setHidden:YES];
409     [[window() standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
410     [[window() standardWindowButton:NSWindowCloseButton] setHidden:YES];
412     // Some third-party OS X utilities check the zoom button's enabled state to
413     // determine whether to show custom UI on hover, so we disable it here to
414     // prevent them from doing so in a frameless app window.
415     [[window() standardWindowButton:NSWindowZoomButton] setEnabled:NO];
417     UpdateDraggableRegionViews();
418   }
421 void NativeAppWindowCocoa::UninstallView() {
422   NSView* view = WebContents()->GetNativeView();
423   [view removeFromSuperview];
426 bool NativeAppWindowCocoa::IsActive() const {
427   return [window() isKeyWindow];
430 bool NativeAppWindowCocoa::IsMaximized() const {
431   return is_maximized_;
434 bool NativeAppWindowCocoa::IsMinimized() const {
435   return [window() isMiniaturized];
438 bool NativeAppWindowCocoa::IsFullscreen() const {
439   return is_fullscreen_;
442 void NativeAppWindowCocoa::SetFullscreen(int fullscreen_types) {
443   bool fullscreen = (fullscreen_types != AppWindow::FULLSCREEN_TYPE_NONE);
444   if (fullscreen == is_fullscreen_)
445     return;
446   is_fullscreen_ = fullscreen;
448   if (base::mac::IsOSLionOrLater()) {
449     // If going fullscreen, but the window is constrained (fullscreen UI control
450     // is disabled), temporarily enable it. It will be disabled again on leaving
451     // fullscreen.
452     if (fullscreen && !shows_fullscreen_controls_)
453       SetFullScreenCollectionBehavior(window(), true);
454     [window() toggleFullScreen:nil];
455     return;
456   }
458   DCHECK(base::mac::IsOSSnowLeopard());
460   // Fade to black.
461   const CGDisplayReservationInterval kFadeDurationSeconds = 0.6;
462   bool did_fade_out = false;
463   CGDisplayFadeReservationToken token;
464   if (CGAcquireDisplayFadeReservation(kFadeDurationSeconds, &token) ==
465       kCGErrorSuccess) {
466     did_fade_out = true;
467     CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendNormal,
468         kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, /*synchronous=*/true);
469   }
471   // Since frameless windows insert the WebContentsView into the NSThemeFrame
472   // ([[window contentView] superview]), and since that NSThemeFrame is
473   // destroyed and recreated when we change the styleMask of the window, we
474   // need to remove the view from the window when we change the style, and
475   // add it back afterwards.
476   UninstallView();
477   if (fullscreen) {
478     UpdateRestoredBounds();
479     [window() setStyleMask:NSBorderlessWindowMask];
480     [window() setFrame:[window()
481         frameRectForContentRect:[[window() screen] frame]]
482                display:YES];
483     base::mac::RequestFullScreen(base::mac::kFullScreenModeAutoHideAll);
484   } else {
485     base::mac::ReleaseFullScreen(base::mac::kFullScreenModeAutoHideAll);
486     [window() setStyleMask:GetWindowStyleMask()];
487     [window() setFrame:restored_bounds_ display:YES];
488   }
489   InstallView();
491   // Fade back in.
492   if (did_fade_out) {
493     CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendSolidColor,
494         kCGDisplayBlendNormal, 0.0, 0.0, 0.0, /*synchronous=*/false);
495     CGReleaseDisplayFadeReservation(token);
496   }
499 bool NativeAppWindowCocoa::IsFullscreenOrPending() const {
500   return is_fullscreen_;
503 bool NativeAppWindowCocoa::IsDetached() const {
504   return false;
507 gfx::NativeWindow NativeAppWindowCocoa::GetNativeWindow() {
508   return window();
511 gfx::Rect NativeAppWindowCocoa::GetRestoredBounds() const {
512   // Flip coordinates based on the primary screen.
513   NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
514   NSRect frame = restored_bounds_;
515   gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
516   bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
517   return bounds;
520 ui::WindowShowState NativeAppWindowCocoa::GetRestoredState() const {
521   if (IsMaximized())
522     return ui::SHOW_STATE_MAXIMIZED;
523   if (IsFullscreen())
524     return ui::SHOW_STATE_FULLSCREEN;
525   return ui::SHOW_STATE_NORMAL;
528 gfx::Rect NativeAppWindowCocoa::GetBounds() const {
529   // Flip coordinates based on the primary screen.
530   NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
531   NSRect frame = [window() frame];
532   gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
533   bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
534   return bounds;
537 void NativeAppWindowCocoa::Show() {
538   is_hidden_ = false;
540   if (is_hidden_with_app_) {
541     // If there is a shim to gently request attention, return here. Otherwise
542     // show the window as usual.
543     if (apps::ExtensionAppShimHandler::RequestUserAttentionForWindow(
544             app_window_)) {
545       return;
546     }
547   }
549   [window_controller_ showWindow:nil];
550   Activate();
553 void NativeAppWindowCocoa::ShowInactive() {
554   is_hidden_ = false;
555   [window() orderFront:window_controller_];
558 void NativeAppWindowCocoa::Hide() {
559   is_hidden_ = true;
560   HideWithoutMarkingHidden();
563 void NativeAppWindowCocoa::Close() {
564   [window() performClose:nil];
567 void NativeAppWindowCocoa::Activate() {
568   [BrowserWindowUtils activateWindowForController:window_controller_];
571 void NativeAppWindowCocoa::Deactivate() {
572   // TODO(jcivelli): http://crbug.com/51364 Implement me.
573   NOTIMPLEMENTED();
576 void NativeAppWindowCocoa::Maximize() {
577   UpdateRestoredBounds();
578   is_maximized_ = true;  // See top of file NOTE: State Before Update.
579   [window() setFrame:[[window() screen] visibleFrame] display:YES animate:YES];
582 void NativeAppWindowCocoa::Minimize() {
583   [window() miniaturize:window_controller_];
586 void NativeAppWindowCocoa::Restore() {
587   DCHECK(!IsFullscreenOrPending());   // SetFullscreen, not Restore, expected.
589   if (IsMaximized()) {
590     is_maximized_ = false;  // See top of file NOTE: State Before Update.
591     [window() setFrame:restored_bounds() display:YES animate:YES];
592   } else if (IsMinimized()) {
593     is_maximized_ = false;  // See top of file NOTE: State Before Update.
594     [window() deminiaturize:window_controller_];
595   }
598 void NativeAppWindowCocoa::SetBounds(const gfx::Rect& bounds) {
599   // Enforce minimum/maximum bounds.
600   gfx::Rect checked_bounds = bounds;
602   NSSize min_size = [window() minSize];
603   if (bounds.width() < min_size.width)
604     checked_bounds.set_width(min_size.width);
605   if (bounds.height() < min_size.height)
606     checked_bounds.set_height(min_size.height);
607   NSSize max_size = [window() maxSize];
608   if (checked_bounds.width() > max_size.width)
609     checked_bounds.set_width(max_size.width);
610   if (checked_bounds.height() > max_size.height)
611     checked_bounds.set_height(max_size.height);
613   NSRect cocoa_bounds = GfxToCocoaBounds(checked_bounds);
614   [window() setFrame:cocoa_bounds display:YES];
615   // setFrame: without animate: does not trigger a windowDidEndLiveResize: so
616   // call it here.
617   WindowDidFinishResize();
620 void NativeAppWindowCocoa::UpdateWindowIcon() {
621   // TODO(junmin): implement.
624 void NativeAppWindowCocoa::UpdateWindowTitle() {
625   base::string16 title = app_window_->GetTitle();
626   [window() setTitle:base::SysUTF16ToNSString(title)];
629 void NativeAppWindowCocoa::UpdateBadgeIcon() {
630   // TODO(benwells): implement.
631   NOTIMPLEMENTED();
634 void NativeAppWindowCocoa::UpdateShape(scoped_ptr<SkRegion> region) {
635   NOTIMPLEMENTED();
638 void NativeAppWindowCocoa::UpdateDraggableRegions(
639     const std::vector<extensions::DraggableRegion>& regions) {
640   // Draggable region is not supported for non-frameless window.
641   if (has_frame_)
642     return;
644   draggable_regions_ = regions;
645   UpdateDraggableRegionViews();
648 SkRegion* NativeAppWindowCocoa::GetDraggableRegion() {
649   return NULL;
652 void NativeAppWindowCocoa::HandleKeyboardEvent(
653     const content::NativeWebKeyboardEvent& event) {
654   if (event.skip_in_browser ||
655       event.type == content::NativeWebKeyboardEvent::Char) {
656     return;
657   }
658   [window() redispatchKeyEvent:event.os_event];
661 void NativeAppWindowCocoa::UpdateDraggableRegionViews() {
662   if (has_frame_)
663     return;
665   // All ControlRegionViews should be added as children of the WebContentsView,
666   // because WebContentsView will be removed and re-added when entering and
667   // leaving fullscreen mode.
668   NSView* webView = WebContents()->GetNativeView();
669   NSInteger webViewWidth = NSWidth([webView bounds]);
670   NSInteger webViewHeight = NSHeight([webView bounds]);
672   // Remove all ControlRegionViews that are added last time.
673   // Note that [webView subviews] returns the view's mutable internal array and
674   // it should be copied to avoid mutating the original array while enumerating
675   // it.
676   base::scoped_nsobject<NSArray> subviews([[webView subviews] copy]);
677   for (NSView* subview in subviews.get())
678     if ([subview isKindOfClass:[ControlRegionView class]])
679       [subview removeFromSuperview];
681   // Draggable regions is implemented by having the whole web view draggable
682   // (mouseDownCanMoveWindow) and overlaying regions that are not draggable.
683   std::vector<gfx::Rect> system_drag_exclude_areas =
684       CalculateNonDraggableRegions(
685           draggable_regions_, webViewWidth, webViewHeight);
687   // Create and add a ControlRegionView for each region that needs to be
688   // excluded from the dragging.
689   for (std::vector<gfx::Rect>::const_iterator iter =
690            system_drag_exclude_areas.begin();
691        iter != system_drag_exclude_areas.end();
692        ++iter) {
693     base::scoped_nsobject<NSView> controlRegion(
694         [[ControlRegionView alloc] initWithFrame:NSZeroRect]);
695     [controlRegion setFrame:NSMakeRect(iter->x(),
696                                        webViewHeight - iter->bottom(),
697                                        iter->width(),
698                                        iter->height())];
699     [webView addSubview:controlRegion];
700   }
703 void NativeAppWindowCocoa::FlashFrame(bool flash) {
704   if (flash) {
705     attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
706   } else {
707     [NSApp cancelUserAttentionRequest:attention_request_id_];
708     attention_request_id_ = 0;
709   }
712 bool NativeAppWindowCocoa::IsAlwaysOnTop() const {
713   return [window() level] == AlwaysOnTopWindowLevel();
716 void NativeAppWindowCocoa::RenderViewCreated(content::RenderViewHost* rvh) {
717   if (IsActive())
718     WebContents()->RestoreFocus();
721 bool NativeAppWindowCocoa::IsFrameless() const {
722   return !has_frame_;
725 bool NativeAppWindowCocoa::HasFrameColor() const {
726   // TODO(benwells): Implement this.
727   return false;
730 SkColor NativeAppWindowCocoa::ActiveFrameColor() const {
731   // TODO(benwells): Implement this.
732   return SkColor();
735 SkColor NativeAppWindowCocoa::InactiveFrameColor() const {
736   // TODO(benwells): Implement this.
737   return SkColor();
740 gfx::Insets NativeAppWindowCocoa::GetFrameInsets() const {
741   if (!has_frame_)
742     return gfx::Insets();
744   // Flip the coordinates based on the main screen.
745   NSInteger screen_height =
746       NSHeight([[[NSScreen screens] objectAtIndex:0] frame]);
748   NSRect frame_nsrect = [window() frame];
749   gfx::Rect frame_rect(NSRectToCGRect(frame_nsrect));
750   frame_rect.set_y(screen_height - NSMaxY(frame_nsrect));
752   NSRect content_nsrect = [window() contentRectForFrameRect:frame_nsrect];
753   gfx::Rect content_rect(NSRectToCGRect(content_nsrect));
754   content_rect.set_y(screen_height - NSMaxY(content_nsrect));
756   return frame_rect.InsetsFrom(content_rect);
759 gfx::NativeView NativeAppWindowCocoa::GetHostView() const {
760   NOTIMPLEMENTED();
761   return NULL;
764 gfx::Point NativeAppWindowCocoa::GetDialogPosition(const gfx::Size& size) {
765   NOTIMPLEMENTED();
766   return gfx::Point();
769 gfx::Size NativeAppWindowCocoa::GetMaximumDialogSize() {
770   NOTIMPLEMENTED();
771   return gfx::Size();
774 void NativeAppWindowCocoa::AddObserver(
775     web_modal::ModalDialogHostObserver* observer) {
776   NOTIMPLEMENTED();
779 void NativeAppWindowCocoa::RemoveObserver(
780     web_modal::ModalDialogHostObserver* observer) {
781   NOTIMPLEMENTED();
784 void NativeAppWindowCocoa::WindowWillClose() {
785   [window_controller_ setAppWindow:NULL];
786   app_window_->OnNativeWindowChanged();
787   app_window_->OnNativeClose();
790 void NativeAppWindowCocoa::WindowDidBecomeKey() {
791   content::RenderWidgetHostView* rwhv =
792       WebContents()->GetRenderWidgetHostView();
793   if (rwhv)
794     rwhv->SetActive(true);
795   app_window_->OnNativeWindowActivated();
797   WebContents()->RestoreFocus();
800 void NativeAppWindowCocoa::WindowDidResignKey() {
801   // If our app is still active and we're still the key window, ignore this
802   // message, since it just means that a menu extra (on the "system status bar")
803   // was activated; we'll get another |-windowDidResignKey| if we ever really
804   // lose key window status.
805   if ([NSApp isActive] && ([NSApp keyWindow] == window()))
806     return;
808   WebContents()->StoreFocus();
810   content::RenderWidgetHostView* rwhv =
811       WebContents()->GetRenderWidgetHostView();
812   if (rwhv)
813     rwhv->SetActive(false);
816 void NativeAppWindowCocoa::WindowDidFinishResize() {
817   // Update |is_maximized_| if needed:
818   // - Exit maximized state if resized.
819   // - Consider us maximized if resize places us back to maximized location.
820   //   This happens when returning from fullscreen.
821   NSRect frame = [window() frame];
822   NSRect screen = [[window() screen] visibleFrame];
823   if (!NSEqualSizes(frame.size, screen.size))
824     is_maximized_ = false;
825   else if (NSEqualPoints(frame.origin, screen.origin))
826     is_maximized_ = true;
828   // Update |is_fullscreen_| if needed.
829   is_fullscreen_ = ([window() styleMask] & NSFullScreenWindowMask) != 0;
830   // If not fullscreen but the window is constrained, disable the fullscreen UI
831   // control.
832   if (!is_fullscreen_ && !shows_fullscreen_controls_)
833     SetFullScreenCollectionBehavior(window(), false);
835   UpdateRestoredBounds();
838 void NativeAppWindowCocoa::WindowDidResize() {
839   app_window_->OnNativeWindowChanged();
840   UpdateDraggableRegionViews();
843 void NativeAppWindowCocoa::WindowDidMove() {
844   UpdateRestoredBounds();
845   app_window_->OnNativeWindowChanged();
848 void NativeAppWindowCocoa::WindowDidMiniaturize() {
849   app_window_->OnNativeWindowChanged();
852 void NativeAppWindowCocoa::WindowDidDeminiaturize() {
853   app_window_->OnNativeWindowChanged();
856 void NativeAppWindowCocoa::WindowWillZoom() {
857   // See top of file NOTE: Maximize and Zoom.
858   if (IsMaximized())
859     Restore();
860   else
861     Maximize();
864 bool NativeAppWindowCocoa::HandledByExtensionCommand(NSEvent* event) {
865   return extension_keybinding_registry_->ProcessKeyEvent(
866       content::NativeWebKeyboardEvent(event));
869 void NativeAppWindowCocoa::ShowWithApp() {
870   is_hidden_with_app_ = false;
871   if (!is_hidden_)
872     ShowInactive();
875 void NativeAppWindowCocoa::HideWithApp() {
876   is_hidden_with_app_ = true;
877   HideWithoutMarkingHidden();
880 void NativeAppWindowCocoa::UpdateShelfMenu() {
881   // TODO(tmdiep): To be implemented for Mac.
882   NOTIMPLEMENTED();
885 gfx::Size NativeAppWindowCocoa::GetContentMinimumSize() const {
886   return size_constraints_.GetMinimumSize();
889 gfx::Size NativeAppWindowCocoa::GetContentMaximumSize() const {
890   return size_constraints_.GetMaximumSize();
893 void NativeAppWindowCocoa::SetContentSizeConstraints(
894     const gfx::Size& min_size, const gfx::Size& max_size) {
895   // Update the size constraints.
896   size_constraints_.set_minimum_size(min_size);
897   size_constraints_.set_maximum_size(max_size);
899   gfx::Size minimum_size = size_constraints_.GetMinimumSize();
900   [window() setContentMinSize:NSMakeSize(minimum_size.width(),
901                                          minimum_size.height())];
903   gfx::Size maximum_size = size_constraints_.GetMaximumSize();
904   const int kUnboundedSize = apps::SizeConstraints::kUnboundedSize;
905   CGFloat max_width = maximum_size.width() == kUnboundedSize ?
906       CGFLOAT_MAX : maximum_size.width();
907   CGFloat max_height = maximum_size.height() == kUnboundedSize ?
908       CGFLOAT_MAX : maximum_size.height();
909   [window() setContentMaxSize:NSMakeSize(max_width, max_height)];
911   // Update the window controls.
912   shows_resize_controls_ =
913       is_resizable_ && !size_constraints_.HasFixedSize();
914   shows_fullscreen_controls_ =
915       is_resizable_ && !size_constraints_.HasMaximumSize() && has_frame_;
917   if (!is_fullscreen_) {
918     [window() setStyleMask:GetWindowStyleMask()];
920     // Set the window to participate in Lion Fullscreen mode. Setting this flag
921     // has no effect on Snow Leopard or earlier. UI controls for fullscreen are
922     // only shown for apps that have unbounded size.
923     SetFullScreenCollectionBehavior(window(), shows_fullscreen_controls_);
924   }
926   if (has_frame_) {
927     [window() setShowsResizeIndicator:shows_resize_controls_];
928     [[window() standardWindowButton:NSWindowZoomButton]
929         setEnabled:shows_fullscreen_controls_];
930   }
933 void NativeAppWindowCocoa::SetAlwaysOnTop(bool always_on_top) {
934   [window() setLevel:(always_on_top ? AlwaysOnTopWindowLevel() :
935                                       NSNormalWindowLevel)];
938 NativeAppWindowCocoa::~NativeAppWindowCocoa() {
941 ShellNSWindow* NativeAppWindowCocoa::window() const {
942   NSWindow* window = [window_controller_ window];
943   CHECK(!window || [window isKindOfClass:[ShellNSWindow class]]);
944   return static_cast<ShellNSWindow*>(window);
947 content::WebContents* NativeAppWindowCocoa::WebContents() const {
948   return app_window_->web_contents();
951 void NativeAppWindowCocoa::UpdateRestoredBounds() {
952   if (IsRestored(*this))
953     restored_bounds_ = [window() frame];
956 void NativeAppWindowCocoa::HideWithoutMarkingHidden() {
957   [window() orderOut:window_controller_];