1 // Copyright (c) 2012 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/panels/panel_window_controller_cocoa.h"
7 #import <Cocoa/Cocoa.h>
9 #include "base/auto_reset.h"
10 #include "base/logging.h"
11 #include "base/mac/bundle_locations.h"
12 #include "base/mac/mac_util.h"
13 #include "base/mac/scoped_nsautorelease_pool.h"
14 #include "base/strings/sys_string_conversions.h"
15 #include "chrome/app/chrome_command_ids.h" // IDC_*
16 #include "chrome/browser/chrome_browser_application_mac.h"
17 #include "chrome/browser/profiles/profile.h"
18 #import "chrome/browser/ui/cocoa/browser_command_executor.h"
19 #import "chrome/browser/ui/cocoa/browser_window_utils.h"
20 #import "chrome/browser/ui/cocoa/panels/mouse_drag_controller.h"
21 #import "chrome/browser/ui/cocoa/panels/panel_cocoa.h"
22 #import "chrome/browser/ui/cocoa/panels/panel_titlebar_view_cocoa.h"
23 #import "chrome/browser/ui/cocoa/panels/panel_utils_cocoa.h"
24 #import "chrome/browser/ui/cocoa/tab_contents/favicon_util_mac.h"
25 #import "chrome/browser/ui/cocoa/tab_contents/tab_contents_controller.h"
26 #import "chrome/browser/ui/cocoa/sprite_view.h"
27 #include "chrome/browser/ui/panels/panel_bounds_animation.h"
28 #include "chrome/browser/ui/panels/panel_collection.h"
29 #include "chrome/browser/ui/panels/panel_constants.h"
30 #include "chrome/browser/ui/panels/panel_manager.h"
31 #include "chrome/browser/ui/panels/stacked_panel_collection.h"
32 #include "chrome/browser/ui/tabs/tab_strip_model.h"
33 #include "chrome/browser/ui/toolbar/encoding_menu_controller.h"
34 #include "content/public/browser/render_widget_host_view.h"
35 #include "content/public/browser/web_contents.h"
36 #include "content/public/browser/web_contents_view.h"
37 #include "grit/ui_resources.h"
38 #include "ui/base/resource/resource_bundle.h"
39 #include "ui/gfx/image/image.h"
41 using content::WebContents;
43 const int kMinimumWindowSize = 1;
44 const double kBoundsAnimationSpeedPixelsPerSecond = 1000;
45 const double kBoundsAnimationMaxDurationSeconds = 0.18;
47 // Edge thickness to trigger user resizing via system, in screen pixels.
48 const double kWidthOfMouseResizeArea = 15.0;
50 @interface PanelWindowControllerCocoa (PanelsCanBecomeKey)
51 // Internal helper method for extracting the total number of panel windows
52 // from the panel manager. Used to decide if panel can become the key window.
56 @implementation PanelWindowCocoaImpl
57 // The panels cannot be reduced to 3-px windows on the edge of the screen
58 // active area (above Dock). Default constraining logic makes at least a height
59 // of the titlebar visible, so the user could still grab it. We do 'restore'
60 // differently, and minimize panels to 3 px. Hence the need to override the
61 // constraining logic.
62 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen {
66 // Prevent panel window from becoming key - for example when it is minimized.
67 // Panel windows use a higher priority NSWindowLevel to ensure they are always
68 // visible, causing the OS to prefer panel windows when selecting a window
69 // to make the key window. To counter this preference, we override
70 // -[NSWindow:canBecomeKeyWindow] to restrict when the panel can become the
71 // key window to a limited set of scenarios, such as when cycling through
72 // windows, when panels are the only remaining windows, when an event
73 // triggers window activation, etc. The panel may also be prevented from
74 // becoming the key window, regardless of the above scenarios, such as when
75 // a panel is minimized.
76 - (BOOL)canBecomeKeyWindow {
77 // Give precedence to controller preventing activation of the window.
78 PanelWindowControllerCocoa* controller =
79 base::mac::ObjCCast<PanelWindowControllerCocoa>([self windowController]);
80 if (![controller canBecomeKeyWindow])
83 BrowserCrApplication* app = base::mac::ObjCCast<BrowserCrApplication>(
84 [BrowserCrApplication sharedApplication]);
86 // A Panel window can become the key window only in limited scenarios.
87 // This prevents the system from always preferring a Panel window due
88 // to its higher priority NSWindowLevel when selecting a window to make key.
89 return ([app isHandlingSendEvent] && [[app currentEvent] window] == self) ||
90 [controller activationRequestedByPanel] ||
91 [app isCyclingWindows] ||
92 [app previousKeyWindow] == self ||
93 [[app windows] count] == static_cast<NSUInteger>([controller numPanels]);
96 - (void)performMiniaturize:(id)sender {
97 [[self windowController] minimizeButtonClicked:0];
100 // Ignore key events if window cannot become key window to fix problem
101 // where keyboard input is still going into a minimized panel even though
102 // the app has been deactivated in -[PanelWindowControllerCocoa deactivate:].
103 - (void)sendEvent:(NSEvent*)anEvent {
104 NSEventType eventType = [anEvent type];
105 if ((eventType == NSKeyDown || eventType == NSKeyUp) &&
106 ![self canBecomeKeyWindow])
108 [super sendEvent:anEvent];
111 - (void)mouseMoved:(NSEvent*)event {
112 // Cocoa does not support letting the application determine the edges that
113 // can trigger the user resizing. To work around this, we track the mouse
114 // location. When it is close to the edge/corner where the user resizing
115 // is not desired, we force the min and max size of the window to be same
116 // as current window size. For all other cases, we restore the min and max
118 PanelWindowControllerCocoa* controller =
119 base::mac::ObjCCast<PanelWindowControllerCocoa>([self windowController]);
120 NSRect frame = [self frame];
121 if ([controller canResizeByMouseAtCurrentLocation]) {
122 // Mac window server limits window sizes to 10000.
123 NSSize maxSize = NSMakeSize(10000, 10000);
125 // If the user is resizing a stacked panel by its bottom edge, make sure its
126 // height cannot grow more than what the panel below it could offer. This is
127 // because growing a stacked panel by y amount will shrink the panel below
128 // it by same amount and we do not want the panel below it being shrunk to
129 // be smaller than the titlebar.
130 Panel* panel = [controller panel];
131 NSPoint point = [NSEvent mouseLocation];
132 if (point.y < NSMinY(frame) + kWidthOfMouseResizeArea && panel->stack()) {
133 Panel* belowPanel = panel->stack()->GetPanelBelow(panel);
134 if (belowPanel && !belowPanel->IsMinimized()) {
135 maxSize.height = panel->GetBounds().height() +
136 belowPanel->GetBounds().height() - panel::kTitlebarHeight;
140 // Enable the user-resizing by setting both min and max size to the right
142 [self setMinSize:NSMakeSize(panel::kPanelMinWidth,
143 panel::kPanelMinHeight)];
144 [self setMaxSize:maxSize];
146 // Disable the user-resizing by setting both min and max size to be same as
147 // current window size.
148 [self setMinSize:frame.size];
149 [self setMaxSize:frame.size];
152 [super mouseMoved:event];
156 // ChromeEventProcessingWindow expects its controller to implement the
157 // BrowserCommandExecutor protocol.
158 @interface PanelWindowControllerCocoa (InternalAPI) <BrowserCommandExecutor>
160 // BrowserCommandExecutor methods.
161 - (void)executeCommand:(int)command;
165 @implementation PanelWindowControllerCocoa (InternalAPI)
167 // This gets called whenever a browser-specific keyboard shortcut is performed
168 // in the Panel window. We simply swallow all those events.
169 - (void)executeCommand:(int)command {}
173 @implementation PanelWindowControllerCocoa
175 - (id)initWithPanel:(PanelCocoa*)window {
177 [base::mac::FrameworkBundle() pathForResource:@"Panel" ofType:@"nib"];
178 if ((self = [super initWithWindowNibPath:nibpath owner:self])) {
179 windowShim_.reset(window);
180 animateOnBoundsChange_ = YES;
181 canBecomeKeyWindow_ = YES;
182 activationRequestedByPanel_ = NO;
188 return windowShim_->panel();
191 - (void)awakeFromNib {
192 NSWindow* window = [self window];
195 DCHECK(titlebar_view_);
196 DCHECK_EQ(self, [window delegate]);
198 [self updateWindowLevel];
200 [self updateWindowCollectionBehavior];
202 [titlebar_view_ attach];
204 // Set initial size of the window to match the size of the panel to give
205 // the renderer the proper size to work with earlier, avoiding a resize
206 // after the window is revealed.
207 gfx::Rect panelBounds = windowShim_->panel()->GetBounds();
208 NSRect frame = [window frame];
209 frame.size.width = panelBounds.width();
210 frame.size.height = panelBounds.height();
211 [window setFrame:frame display:NO];
213 // MacOS will turn the user-resizing to the user-dragging if the direction of
214 // the dragging is orthogonal to the direction of the arrow cursor. We do not
215 // want this since it will bypass our dragging logic. The panel window is
216 // still draggable because we track and handle the dragging in our custom way.
217 [[self window] setMovable:NO];
219 [self updateTrackingArea];
222 - (void)updateWebContentsViewFrame {
223 content::WebContents* webContents = windowShim_->panel()->GetWebContents();
227 // Compute the size of the web contents view. Don't assume it's similar to the
228 // size of the contentView, because the contentView is managed by the Cocoa
229 // to be (window - standard titlebar), while we have taller custom titlebar
230 // instead. In coordinate system of window's contentView.
231 NSRect contentFrame = [self contentRectForFrameRect:[[self window] frame]];
232 contentFrame.origin = NSZeroPoint;
234 NSView* contentView = webContents->GetView()->GetNativeView();
235 if (!NSEqualRects([contentView frame], contentFrame))
236 [contentView setFrame:contentFrame];
239 - (void)disableWebContentsViewAutosizing {
240 [[[self window] contentView] setAutoresizesSubviews:NO];
243 - (void)enableWebContentsViewAutosizing {
244 [self updateWebContentsViewFrame];
245 [[[self window] contentView] setAutoresizesSubviews:YES];
248 - (void)revealAnimatedWithFrame:(const NSRect&)frame {
249 NSWindow* window = [self window]; // This ensures loading the nib.
251 // Disable subview resizing while resizing the window to avoid renderer
252 // resizes during intermediate stages of animation.
253 [self disableWebContentsViewAutosizing];
255 // We grow the window from the bottom up to produce a 'reveal' animation.
256 NSRect startFrame = NSMakeRect(NSMinX(frame), NSMinY(frame),
257 NSWidth(frame), kMinimumWindowSize);
258 [window setFrame:startFrame display:NO animate:NO];
259 // Shows the window without making it key, on top of its layer, even if
260 // Chromium is not an active app.
261 [window orderFrontRegardless];
262 // TODO(dcheng): Temporary hack to work around the fact that
263 // orderFrontRegardless causes us to become the first responder. The usual
264 // Chrome assumption is that becoming the first responder = you have focus, so
265 // we always deactivate the controls here. If we're created as an active
266 // panel, we'll get a NSWindowDidBecomeKeyNotification and reactivate the web
267 // view properly. See crbug.com/97831 for more details.
268 WebContents* web_contents = windowShim_->panel()->GetWebContents();
269 // RWHV may be NULL in unit tests.
270 if (web_contents && web_contents->GetRenderWidgetHostView())
271 web_contents->GetRenderWidgetHostView()->SetActive(false);
273 // This will re-enable the content resizing after it finishes.
274 [self setPanelFrame:frame animate:YES];
277 - (void)updateTitleBar {
278 NSString* newTitle = base::SysUTF16ToNSString(
279 windowShim_->panel()->GetWindowTitle());
280 pendingWindowTitle_.reset(
281 [BrowserWindowUtils scheduleReplaceOldTitle:pendingWindowTitle_.get()
282 withNewTitle:newTitle
283 forWindow:[self window]]);
284 [titlebar_view_ setTitle:newTitle];
289 base::scoped_nsobject<NSView> iconView;
290 if (throbberShouldSpin_) {
291 // If the throbber is spinning now, no need to replace it.
292 if ([[titlebar_view_ icon] isKindOfClass:[SpriteView class]])
296 ResourceBundle::GetSharedInstance().GetNativeImageNamed(
297 IDR_THROBBER).ToNSImage();
298 SpriteView* spriteView = [[SpriteView alloc] init];
299 [spriteView setImage:iconImage];
300 iconView.reset(spriteView);
302 const gfx::Image& page_icon = windowShim_->panel()->GetCurrentPageIcon();
303 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
304 NSRect iconFrame = [[titlebar_view_ icon] frame];
305 NSImage* iconImage = page_icon.IsEmpty() ?
306 rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToNSImage() :
307 page_icon.ToNSImage();
308 NSImageView* imageView = [[NSImageView alloc] initWithFrame:iconFrame];
309 [imageView setImage:iconImage];
310 iconView.reset(imageView);
312 [titlebar_view_ setIcon:iconView];
315 - (void)updateThrobber:(BOOL)shouldSpin {
316 if (throbberShouldSpin_ == shouldSpin)
318 throbberShouldSpin_ = shouldSpin;
320 // If the titlebar view has not been attached, bail out.
327 - (void)updateTitleBarMinimizeRestoreButtonVisibility {
328 Panel* panel = windowShim_->panel();
329 [titlebar_view_ setMinimizeButtonVisibility:panel->CanShowMinimizeButton()];
330 [titlebar_view_ setRestoreButtonVisibility:panel->CanShowRestoreButton()];
333 - (void)webContentsInserted:(WebContents*)contents {
334 NSView* view = contents->GetView()->GetNativeView();
335 [[[self window] contentView] addSubview:view];
336 [view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
338 [self enableWebContentsViewAutosizing];
341 - (void)webContentsDetached:(WebContents*)contents {
342 [contents->GetView()->GetNativeView() removeFromSuperview];
345 - (PanelTitlebarViewCocoa*)titlebarView {
346 return titlebar_view_;
349 // Called to validate menu and toolbar items when this window is key. All the
350 // items we care about have been set with the |-commandDispatch:|
351 // action and a target of FirstResponder in IB.
352 // Delegate to the NSApp delegate if Panel does not care about the command or
353 // shortcut, to make sure the global items in Chrome main app menu still work.
354 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
355 if ([item action] == @selector(commandDispatch:)) {
356 NSInteger tag = [item tag];
357 CommandUpdater* command_updater = windowShim_->panel()->command_updater();
358 if (command_updater->SupportsCommand(tag))
359 return command_updater->IsCommandEnabled(tag);
361 return [[NSApp delegate] validateUserInterfaceItem:item];
366 // Called when the user picks a menu or toolbar item when this window is key.
367 // Calls through to the panel object to execute the command or delegates up.
368 - (void)commandDispatch:(id)sender {
370 NSInteger tag = [sender tag];
371 CommandUpdater* command_updater = windowShim_->panel()->command_updater();
372 if (command_updater->SupportsCommand(tag))
373 windowShim_->panel()->ExecuteCommandIfEnabled(tag);
375 [[NSApp delegate] commandDispatch:sender];
378 // Handler for the custom Close button.
380 windowShim_->panel()->Close();
383 // Handler for the custom Minimize button.
384 - (void)minimizeButtonClicked:(int)modifierFlags {
385 Panel* panel = windowShim_->panel();
386 panel->OnMinimizeButtonClicked((modifierFlags & NSShiftKeyMask) ?
387 panel::APPLY_TO_ALL : panel::NO_MODIFIER);
390 // Handler for the custom Restore button.
391 - (void)restoreButtonClicked:(int)modifierFlags {
392 Panel* panel = windowShim_->panel();
393 panel->OnRestoreButtonClicked((modifierFlags & NSShiftKeyMask) ?
394 panel::APPLY_TO_ALL : panel::NO_MODIFIER);
397 // Called when the user wants to close the panel or from the shutdown process.
398 // The Panel object is in control of whether or not we're allowed to close. It
399 // may defer closing due to several states, such as onbeforeUnload handlers
400 // needing to be fired. If closing is deferred, the Panel will handle the
401 // processing required to get us to the closing state and (by watching for
402 // the web content going away) will again call to close the window when it's
404 - (BOOL)windowShouldClose:(id)sender {
405 Panel* panel = windowShim_->panel();
406 // Give beforeunload handlers the chance to cancel the close before we hide
408 if (!panel->ShouldCloseWindow())
411 if (panel->GetWebContents()) {
412 // Terminate any playing animations.
413 [self terminateBoundsAnimation];
414 animateOnBoundsChange_ = NO;
415 // Make panel close the web content, allowing the renderer to shut down
416 // and call us back again.
417 panel->OnWindowClosing();
421 // No web content; it's ok to close the window.
425 // When windowShouldClose returns YES (or if controller receives direct 'close'
426 // signal), window will be unconditionally closed. Clean up.
427 - (void)windowWillClose:(NSNotification*)notification {
428 DCHECK(!windowShim_->panel()->GetWebContents());
429 // Avoid callbacks from a nonblocking animation in progress, if any.
430 [self terminateBoundsAnimation];
431 windowShim_->DidCloseNativeWindow();
432 // Call |-autorelease| after a zero-length delay to avoid deadlock from
433 // code in the current run loop that waits on PANEL_CLOSED notification.
434 // The notification is sent when this object is freed, but this object
435 // cannot be freed until the current run loop completes.
436 [self performSelector:@selector(autorelease)
441 - (void)startDrag:(NSPoint)mouseLocation {
442 // Convert from Cocoa's screen coordinates to platform-indepedent screen
443 // coordinates because PanelManager method takes platform-indepedent screen
445 windowShim_->panel()->manager()->StartDragging(
446 windowShim_->panel(),
447 cocoa_utils::ConvertPointFromCocoaCoordinates(mouseLocation));
450 - (void)endDrag:(BOOL)cancelled {
451 windowShim_->panel()->manager()->EndDragging(cancelled);
454 - (void)drag:(NSPoint)mouseLocation {
455 // Convert from Cocoa's screen coordinates to platform-indepedent screen
456 // coordinates because PanelManager method takes platform-indepedent screen
458 windowShim_->panel()->manager()->Drag(
459 cocoa_utils::ConvertPointFromCocoaCoordinates(mouseLocation));
462 - (void)setPanelFrame:(NSRect)frame
463 animate:(BOOL)animate {
464 BOOL jumpToDestination = (!animateOnBoundsChange_ || !animate);
466 // If no animation is in progress, apply bounds change instantly.
467 if (jumpToDestination && ![self isAnimatingBounds]) {
468 [[self window] setFrame:frame display:YES animate:NO];
472 NSDictionary *windowResize = [NSDictionary dictionaryWithObjectsAndKeys:
473 [self window], NSViewAnimationTargetKey,
474 [NSValue valueWithRect:frame], NSViewAnimationEndFrameKey, nil];
475 NSArray *animations = [NSArray arrayWithObjects:windowResize, nil];
477 // If an animation is in progress, update the animation with new target
478 // bounds. Also, set the destination frame bounds to the new value.
479 if (jumpToDestination && [self isAnimatingBounds]) {
480 [boundsAnimation_ setViewAnimations:animations];
481 [[self window] setFrame:frame display:YES animate:NO];
485 // Will be enabled back in animationDidEnd callback.
486 [self disableWebContentsViewAutosizing];
488 // Terminate previous animation, if it is still playing.
489 [self terminateBoundsAnimation];
492 [[NSViewAnimation alloc] initWithViewAnimations:animations];
493 [boundsAnimation_ setDelegate:self];
495 NSRect currentFrame = [[self window] frame];
496 // Compute duration. We use constant speed of animation, however if the change
497 // is too large, we clip the duration (effectively increasing speed) to
498 // limit total duration of animation. This makes 'small' transitions fast.
499 // 'distance' is the max travel between 4 potentially traveling corners.
500 double distanceX = std::max(std::abs(NSMinX(currentFrame) - NSMinX(frame)),
501 std::abs(NSMaxX(currentFrame) - NSMaxX(frame)));
502 double distanceY = std::max(std::abs(NSMinY(currentFrame) - NSMinY(frame)),
503 std::abs(NSMaxY(currentFrame) - NSMaxY(frame)));
504 double distance = std::max(distanceX, distanceY);
505 double duration = std::min(distance / kBoundsAnimationSpeedPixelsPerSecond,
506 kBoundsAnimationMaxDurationSeconds);
507 // Detect animation that happens when expansion state is set to MINIMIZED
508 // and there is relatively big portion of the panel to hide from view.
509 // Initialize animation differently in this case, using fast-pause-slow
510 // method, see below for more details.
512 windowShim_->panel()->expansion_state() == Panel::MINIMIZED) {
513 animationStopToShowTitlebarOnly_ = 1.0 -
514 (windowShim_->panel()->TitleOnlyHeight() - NSHeight(frame)) / distanceY;
515 if (animationStopToShowTitlebarOnly_ > 0.7) { // Relatively big movement.
516 playingMinimizeAnimation_ = YES;
520 [boundsAnimation_ setDuration: PanelManager::AdjustTimeInterval(duration)];
521 [boundsAnimation_ setFrameRate:0.0];
522 [boundsAnimation_ setAnimationBlockingMode: NSAnimationNonblocking];
523 [boundsAnimation_ startAnimation];
526 - (float)animation:(NSAnimation*)animation
527 valueForProgress:(NSAnimationProgress)progress {
528 return PanelBoundsAnimation::ComputeAnimationValue(
529 progress, playingMinimizeAnimation_, animationStopToShowTitlebarOnly_);
532 - (void)cleanupAfterAnimation {
533 playingMinimizeAnimation_ = NO;
534 if (!windowShim_->panel()->IsMinimized())
535 [self enableWebContentsViewAutosizing];
538 - (void)animationDidEnd:(NSAnimation*)animation {
539 [self cleanupAfterAnimation];
541 // Only invoke this callback from animationDidEnd, since animationDidStop can
542 // be called when we interrupt/restart animation which is in progress.
543 // We only need this notification when animation indeed finished moving
545 Panel* panel = windowShim_->panel();
546 panel->manager()->OnPanelAnimationEnded(panel);
549 - (void)animationDidStop:(NSAnimation*)animation {
550 [self cleanupAfterAnimation];
553 - (void)terminateBoundsAnimation {
554 if (!boundsAnimation_)
556 [boundsAnimation_ stopAnimation];
557 [boundsAnimation_ setDelegate:nil];
558 [boundsAnimation_ release];
559 boundsAnimation_ = nil;
562 - (BOOL)isAnimatingBounds {
563 return boundsAnimation_ && [boundsAnimation_ isAnimating];
566 - (void)onTitlebarMouseClicked:(int)modifierFlags {
567 Panel* panel = windowShim_->panel();
568 panel->OnTitlebarClicked((modifierFlags & NSShiftKeyMask) ?
569 panel::APPLY_TO_ALL : panel::NO_MODIFIER);
572 - (void)onTitlebarDoubleClicked:(int)modifierFlags {
573 // Double-clicking is only allowed to minimize docked panels.
574 Panel* panel = windowShim_->panel();
575 if (panel->collection()->type() != PanelCollection::DOCKED ||
576 panel->IsMinimized())
578 [self minimizeButtonClicked:modifierFlags];
581 - (int)titlebarHeightInScreenCoordinates {
582 NSView* titlebar = [self titlebarView];
583 return NSHeight([titlebar convertRect:[titlebar bounds] toView:nil]);
586 // TODO(dcheng): These two selectors are almost copy-and-paste from
587 // BrowserWindowController. Figure out the appropriate way of code sharing,
588 // whether it's refactoring more things into BrowserWindowUtils or making a
589 // common base controller for browser windows.
590 - (void)windowDidBecomeKey:(NSNotification*)notification {
591 // We need to activate the controls (in the "WebView"). To do this, get the
592 // selected WebContents's RenderWidgetHostView and tell it to activate.
593 if (WebContents* contents = windowShim_->panel()->GetWebContents()) {
594 if (content::RenderWidgetHostView* rwhv =
595 contents->GetRenderWidgetHostView())
596 rwhv->SetActive(true);
599 windowShim_->panel()->OnActiveStateChanged(true);
601 // Make the window user-resizable when it gains the focus.
602 [[self window] setStyleMask:
603 [[self window] styleMask] | NSResizableWindowMask];
606 - (void)windowDidResignKey:(NSNotification*)notification {
607 // If our app is still active and we're still the key window, ignore this
608 // message, since it just means that a menu extra (on the "system status bar")
609 // was activated; we'll get another |-windowDidResignKey| if we ever really
610 // lose key window status.
611 if ([NSApp isActive] && ([NSApp keyWindow] == [self window]))
614 [self onWindowDidResignKey];
616 // Make the window not user-resizable when it loses the focus. This is to
617 // solve the problem that the bottom edge of the active panel does not
618 // trigger the user-resizing if this panel stacks with another inactive
619 // panel at the bottom.
620 [[self window] setStyleMask:
621 [[self window] styleMask] & ~NSResizableWindowMask];
624 - (void)windowWillStartLiveResize:(NSNotification*)notification {
625 // Check if the user-resizing is allowed for the triggering edge/corner.
626 // This is an extra safe guard because we are not able to track the mouse
627 // movement outside the window and Cocoa could trigger the user-resizing
628 // when the mouse moves a bit outside the edge/corner.
629 if (![self canResizeByMouseAtCurrentLocation])
632 windowShim_->panel()->OnPanelStartUserResizing();
635 - (void)windowDidEndLiveResize:(NSNotification*)notification {
640 Panel* panel = windowShim_->panel();
641 panel->OnPanelEndUserResizing();
643 gfx::Rect newBounds =
644 cocoa_utils::ConvertRectFromCocoaCoordinates([[self window] frame]);
645 if (windowShim_->panel()->GetBounds() == newBounds)
647 windowShim_->set_cached_bounds_directly(newBounds);
649 panel->IncreaseMaxSize(newBounds.size());
650 panel->set_full_size(newBounds.size());
652 panel->collection()->RefreshLayout();
655 - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)newSize {
656 // As an extra safe guard, we avoid the user resizing if it is deemed not to
657 // be allowed (see comment in windowWillStartLiveResize).
658 if ([[self window] inLiveResize] && !userResizing_)
659 return [[self window] frame].size;
663 - (void)windowDidResize:(NSNotification*)notification {
664 Panel* panel = windowShim_->panel();
666 panel->collection()->OnPanelResizedByMouse(
668 cocoa_utils::ConvertRectFromCocoaCoordinates([[self window] frame]));
671 [self updateTrackingArea];
673 if (![self isAnimatingBounds] ||
674 panel->collection()->type() != PanelCollection::DOCKED)
677 // Remove the web contents view from the view hierarchy when the panel is not
678 // taller than the titlebar. Put it back when the panel grows taller than
679 // the titlebar. Note that RenderWidgetHostViewMac works for the case that
680 // the web contents view does not exist in the view hierarchy (i.e. the tab
681 // is not the main one), but it does not work well, like causing occasional
682 // crashes (http://crbug.com/265932), if the web contents view is made hidden.
684 // This is needed when the docked panels are being animated. When the
685 // animation starts, the contents view autosizing is disabled. After the
686 // animation ends, the contents view autosizing is reenabled and the frame
687 // of contents view is updated. Thus it is likely that the contents view will
688 // overlap with the titlebar view when the panel shrinks to be very small.
689 // The implementation of the web contents view assumes that it will never
690 // overlap with another view in order to paint the web contents view directly.
691 content::WebContents* webContents = panel->GetWebContents();
694 NSView* contentView = webContents->GetView()->GetNativeView();
695 if (NSHeight([self contentRectForFrameRect:[[self window] frame]]) <= 0) {
696 // No need to retain the view before it is removed from its superview
697 // because WebContentsView keeps a reference to this view.
698 if ([contentView superview])
699 [contentView removeFromSuperview];
701 if (![contentView superview]) {
702 [[[self window] contentView] addSubview:contentView];
704 // When the web contents view is put back, we need to tell its render
705 // widget host view to accept focus.
706 content::RenderWidgetHostView* rwhv =
707 webContents->GetRenderWidgetHostView();
709 [[self window] makeFirstResponder:rwhv->GetNativeView()];
710 rwhv->SetActive([[self window] isMainWindow]);
717 // Activate the window. -|windowDidBecomeKey:| will be called when
718 // window becomes active.
719 base::AutoReset<BOOL> pin(&activationRequestedByPanel_, true);
720 [BrowserWindowUtils activateWindowForController:self];
724 if (![[self window] isMainWindow])
727 // Cocoa does not support deactivating a window, so we deactivate the app.
730 // Deactivating the app does not trigger windowDidResignKey. Do it manually.
731 [self onWindowDidResignKey];
734 - (void)onWindowDidResignKey {
735 // We need to deactivate the controls (in the "WebView"). To do this, get the
736 // selected WebContents's RenderWidgetHostView and tell it to deactivate.
737 if (WebContents* contents = windowShim_->panel()->GetWebContents()) {
738 if (content::RenderWidgetHostView* rwhv =
739 contents->GetRenderWidgetHostView())
740 rwhv->SetActive(false);
743 windowShim_->panel()->OnActiveStateChanged(false);
746 - (void)preventBecomingKeyWindow:(BOOL)prevent {
747 canBecomeKeyWindow_ = !prevent;
750 - (void)fullScreenModeChanged:(bool)isFullScreen {
751 [self updateWindowLevel];
753 // If the panel is not always on top, its z-order should not be affected if
754 // some other window enters fullscreen mode.
755 if (!windowShim_->panel()->IsAlwaysOnTop())
758 // The full-screen window is in normal level and changing the panel window
759 // to same normal level will not move it below the full-screen window. Thus
760 // we need to reorder the panel window.
762 [[self window] orderOut:nil];
764 [[self window] orderFrontRegardless];
767 - (BOOL)canBecomeKeyWindow {
768 // Panel can only gain focus if it is expanded. Minimized panels do not
769 // participate in Cmd-~ rotation.
770 // TODO(dimich): If it will be ever desired to expand/focus the Panel on
771 // keyboard navigation or via main menu, the care should be taken to avoid
772 // cases when minimized Panel is getting keyboard input, invisibly.
773 return canBecomeKeyWindow_;
777 return windowShim_->panel()->manager()->num_panels();
780 - (BOOL)activationRequestedByPanel {
781 return activationRequestedByPanel_;
784 - (void)updateWindowLevel {
785 [self updateWindowLevel:windowShim_->panel()->IsMinimized()];
788 - (void)updateWindowLevel:(BOOL)panelIsMinimized {
789 if (![self isWindowLoaded])
791 Panel* panel = windowShim_->panel();
792 if (!panel->IsAlwaysOnTop()) {
793 [[self window] setLevel:NSNormalWindowLevel];
796 // If we simply use NSStatusWindowLevel (25) for all docked panel windows,
797 // IME composition windows for things like CJK languages appear behind panels.
798 // Pre 10.7, IME composition windows have a window level of 19, which is
799 // lower than the dock at level 20. Since we want panels to appear on top of
800 // the dock, it is impossible to enforce an ordering where IME > panel > dock,
802 // On 10.7, IME composition windows and the dock both live at level 20, so we
803 // use the same window level for panels. Since newly created windows appear at
804 // the top of their window level, panels are typically on top of the dock, and
805 // the IME composition window correctly draws over the panel.
806 // An autohide dock causes problems though: since it's constantly being
807 // revealed, it ends up drawing on top of other windows at the same level.
808 // While this is OK for expanded panels, it makes minimized panels impossible
809 // to activate. As a result, we still use NSStatusWindowLevel for minimized
810 // panels, since it's impossible to compose IME text in them anyway.
811 if (panelIsMinimized) {
812 [[self window] setLevel:NSStatusWindowLevel];
815 [[self window] setLevel:NSDockWindowLevel];
818 - (void)updateWindowCollectionBehavior {
819 if (![self isWindowLoaded])
821 NSWindowCollectionBehavior collectionBehavior =
822 NSWindowCollectionBehaviorParticipatesInCycle;
823 if (windowShim_->panel()->IsAlwaysOnTop())
824 collectionBehavior |= NSWindowCollectionBehaviorCanJoinAllSpaces;
825 [[self window] setCollectionBehavior:collectionBehavior];
828 - (void)updateTrackingArea {
829 NSView* superview = [[[self window] contentView] superview];
831 if (trackingArea_.get())
832 [superview removeTrackingArea:trackingArea_.get()];
835 [[CrTrackingArea alloc] initWithRect:[superview bounds]
836 options:NSTrackingInVisibleRect |
837 NSTrackingMouseMoved |
838 NSTrackingActiveInKeyWindow
841 [superview addTrackingArea:trackingArea_.get()];
844 - (void)showShadow:(BOOL)show {
845 if (![self isWindowLoaded])
847 [[self window] setHasShadow:show];
850 - (void)miniaturize {
851 [[self window] miniaturize:nil];
854 - (BOOL)isMiniaturized {
855 return [[self window] isMiniaturized];
858 - (BOOL)canResizeByMouseAtCurrentLocation {
859 panel::Resizability resizability = windowShim_->panel()->CanResizeByMouse();
860 NSRect frame = [[self window] frame];
861 NSPoint point = [NSEvent mouseLocation];
863 if (point.y < NSMinY(frame) + kWidthOfMouseResizeArea) {
864 if (point.x < NSMinX(frame) + kWidthOfMouseResizeArea &&
865 (resizability & panel::RESIZABLE_BOTTOM_LEFT) == 0) {
868 if (point.x > NSMaxX(frame) - kWidthOfMouseResizeArea &&
869 (resizability & panel::RESIZABLE_BOTTOM_RIGHT) == 0) {
872 if ((resizability & panel::RESIZABLE_BOTTOM) == 0)
874 } else if (point.y > NSMaxY(frame) - kWidthOfMouseResizeArea) {
875 if (point.x < NSMinX(frame) + kWidthOfMouseResizeArea &&
876 (resizability & panel::RESIZABLE_TOP_LEFT) == 0) {
879 if (point.x > NSMaxX(frame) - kWidthOfMouseResizeArea &&
880 (resizability & panel::RESIZABLE_TOP_RIGHT) == 0) {
883 if ((resizability & panel::RESIZABLE_TOP) == 0)
886 if (point.x < NSMinX(frame) + kWidthOfMouseResizeArea &&
887 (resizability & panel::RESIZABLE_LEFT) == 0) {
890 if (point.x > NSMaxX(frame) - kWidthOfMouseResizeArea &&
891 (resizability & panel::RESIZABLE_RIGHT) == 0) {
898 // We have custom implementation of these because our titlebar height is custom
899 // and does not match the standard one.
900 - (NSRect)frameRectForContentRect:(NSRect)contentRect {
901 // contentRect is in contentView coord system. We should add a titlebar on top
902 // and then convert to the windows coord system.
903 contentRect.size.height += panel::kTitlebarHeight;
904 NSRect frameRect = [[[self window] contentView] convertRect:contentRect
909 - (NSRect)contentRectForFrameRect:(NSRect)frameRect {
910 NSRect contentRect = [[[self window] contentView] convertRect:frameRect
912 contentRect.size.height -= panel::kTitlebarHeight;
913 if (contentRect.size.height < 0)
914 contentRect.size.height = 0;