1 // Copyright 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 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
10 #include "base/command_line.h"
11 #include "base/mac/bundle_locations.h"
12 #import "base/mac/foundation_util.h"
13 #include "base/mac/mac_util.h"
14 #import "base/mac/sdk_forward_declarations.h"
15 #include "base/strings/sys_string_conversions.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/app/chrome_command_ids.h" // IDC_*
18 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
19 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
20 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/devtools/devtools_window.h"
23 #include "chrome/browser/fullscreen.h"
24 #include "chrome/browser/profiles/avatar_menu.h"
25 #include "chrome/browser/profiles/profile.h"
26 #include "chrome/browser/profiles/profile_info_cache.h"
27 #include "chrome/browser/profiles/profile_manager.h"
28 #include "chrome/browser/profiles/profiles_state.h"
29 #include "chrome/browser/signin/signin_ui_util.h"
30 #include "chrome/browser/themes/theme_service.h"
31 #include "chrome/browser/themes/theme_service_factory.h"
32 #include "chrome/browser/translate/chrome_translate_client.h"
33 #include "chrome/browser/ui/bookmarks/bookmark_editor.h"
34 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
35 #include "chrome/browser/ui/browser.h"
36 #include "chrome/browser/ui/browser_command_controller.h"
37 #include "chrome/browser/ui/browser_commands.h"
38 #include "chrome/browser/ui/browser_instant_controller.h"
39 #include "chrome/browser/ui/browser_list.h"
40 #include "chrome/browser/ui/browser_window_state.h"
41 #import "chrome/browser/ui/cocoa/background_gradient_view.h"
42 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_bar_controller.h"
43 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_editor_controller.h"
44 #import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
45 #import "chrome/browser/ui/cocoa/browser_window_controller_private.h"
46 #import "chrome/browser/ui/cocoa/browser_window_utils.h"
47 #import "chrome/browser/ui/cocoa/dev_tools_controller.h"
48 #import "chrome/browser/ui/cocoa/download/download_shelf_controller.h"
49 #include "chrome/browser/ui/cocoa/extensions/extension_keybinding_registry_cocoa.h"
50 #import "chrome/browser/ui/cocoa/fast_resize_view.h"
51 #import "chrome/browser/ui/cocoa/find_bar/find_bar_bridge.h"
52 #import "chrome/browser/ui/cocoa/find_bar/find_bar_cocoa_controller.h"
53 #import "chrome/browser/ui/cocoa/framed_browser_window.h"
54 #import "chrome/browser/ui/cocoa/fullscreen_window.h"
55 #import "chrome/browser/ui/cocoa/infobars/infobar_container_controller.h"
56 #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.h"
57 #import "chrome/browser/ui/cocoa/nsview_additions.h"
58 #import "chrome/browser/ui/cocoa/presentation_mode_controller.h"
59 #import "chrome/browser/ui/cocoa/profiles/avatar_base_controller.h"
60 #import "chrome/browser/ui/cocoa/profiles/avatar_button_controller.h"
61 #import "chrome/browser/ui/cocoa/profiles/avatar_icon_controller.h"
62 #import "chrome/browser/ui/cocoa/status_bubble_mac.h"
63 #import "chrome/browser/ui/cocoa/tab_contents/overlayable_contents_controller.h"
64 #import "chrome/browser/ui/cocoa/tab_contents/sad_tab_controller.h"
65 #import "chrome/browser/ui/cocoa/tab_contents/tab_contents_controller.h"
66 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
67 #import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h"
68 #import "chrome/browser/ui/cocoa/tabs/tab_view.h"
69 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
70 #import "chrome/browser/ui/cocoa/translate/translate_bubble_controller.h"
71 #include "chrome/browser/ui/cocoa/website_settings/permission_bubble_cocoa.h"
72 #include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
73 #include "chrome/browser/ui/omnibox/location_bar.h"
74 #include "chrome/browser/ui/tabs/tab_strip_model.h"
75 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
76 #include "chrome/browser/ui/toolbar/encoding_menu_controller.h"
77 #include "chrome/browser/ui/translate/translate_bubble_model_impl.h"
78 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
79 #include "chrome/browser/ui/window_sizer/window_sizer.h"
80 #include "chrome/common/chrome_switches.h"
81 #include "chrome/common/extensions/command.h"
82 #include "chrome/common/url_constants.h"
83 #include "components/bookmarks/browser/bookmark_model.h"
84 #include "components/signin/core/common/profile_management_switches.h"
85 #include "components/translate/core/browser/translate_manager.h"
86 #include "components/translate/core/browser/translate_ui_delegate.h"
87 #include "components/web_modal/web_contents_modal_dialog_manager.h"
88 #include "content/public/browser/render_view_host.h"
89 #include "content/public/browser/render_widget_host_view.h"
90 #include "content/public/browser/web_contents.h"
91 #include "grit/chromium_strings.h"
92 #include "grit/generated_resources.h"
93 #include "grit/locale_settings.h"
94 #import "ui/base/cocoa/cocoa_base_utils.h"
95 #include "ui/base/l10n/l10n_util.h"
96 #include "ui/base/l10n/l10n_util_mac.h"
97 #include "ui/gfx/mac/scoped_ns_disable_screen_updates.h"
99 using l10n_util::GetStringUTF16;
100 using l10n_util::GetNSStringWithFixup;
101 using l10n_util::GetNSStringFWithFixup;
103 // ORGANIZATION: This is a big file. It is (in principle) organized as follows
105 // 1. Interfaces. Very short, one-time-use classes may include an implementation
106 // immediately after their interface.
107 // 2. The general implementation section, ordered as follows:
108 // i. Public methods and overrides.
109 // ii. Overrides/implementations of undocumented methods.
110 // iii. Delegate methods for various protocols, formal and informal, to which
111 // |BrowserWindowController| conforms.
112 // 3. (temporary) Implementation sections for various categories.
114 // Private methods are defined and implemented separately in
115 // browser_window_controller_private.{h,mm}.
117 // Not all of the above guidelines are followed and more (re-)organization is
118 // needed. BUT PLEASE TRY TO KEEP THIS FILE ORGANIZED. I'd rather re-organize as
119 // little as possible, since doing so messes up the file's history.
121 // TODO(viettrungluu): [crbug.com/35543] on-going re-organization, splitting
122 // things into multiple files -- the plan is as follows:
123 // - in general, everything stays in browser_window_controller.h, but is split
124 // off into categories (see below)
125 // - core stuff stays in browser_window_controller.mm
126 // - ... overrides also stay (without going into a category, in particular)
127 // - private stuff which everyone needs goes into
128 // browser_window_controller_private.{h,mm}; if no one else needs them, they
129 // can go in individual files (see below)
130 // - area/task-specific stuff go in browser_window_controller_<area>.mm
131 // - ... in categories called "(<Area>)" or "(<PrivateArea>)"
133 // - first re-organize into categories
134 // - then split into files
136 // Notes on self-inflicted (not user-inflicted) window resizing and moving:
138 // When the bookmark bar goes from hidden to shown (on a non-NTP) page, or when
139 // the download shelf goes from hidden to shown, we grow the window downwards in
140 // order to maintain a constant content area size. When either goes from shown
141 // to hidden, we consequently shrink the window from the bottom, also to keep
142 // the content area size constant. To keep things simple, if the window is not
143 // entirely on-screen, we don't grow/shrink the window.
145 // The complications come in when there isn't enough room (on screen) below the
146 // window to accomodate the growth. In this case, we grow the window first
147 // downwards, and then upwards. So, when it comes to shrinking, we do the
148 // opposite: shrink from the top by the amount by which we grew at the top, and
149 // then from the bottom -- unless the user moved/resized/zoomed the window, in
150 // which case we "reset state" and just shrink from the bottom.
152 // A further complication arises due to the way in which "zoom" ("maximize")
153 // works on Mac OS X. Basically, for our purposes, a window is "zoomed" whenever
154 // it occupies the full available vertical space. (Note that the green zoom
155 // button does not track zoom/unzoomed state per se, but basically relies on
156 // this heuristic.) We don't, in general, want to shrink the window if the
157 // window is zoomed (scenario: window is zoomed, download shelf opens -- which
158 // doesn't cause window growth, download shelf closes -- shouldn't cause the
159 // window to become unzoomed!). However, if we grew the window
160 // (upwards/downwards) to become zoomed in the first place, we *should* shrink
161 // the window by the amounts by which we grew (scenario: window occupies *most*
162 // of vertical space, download shelf opens causing growth so that window
163 // occupies all of vertical space -- i.e., window is effectively zoomed,
164 // download shelf closes -- should return the window to its previous state).
166 // A major complication is caused by the way grows/shrinks are handled and
167 // animated. Basically, the BWC doesn't see the global picture, but it sees
168 // grows and shrinks in small increments (as dictated by the animation). Thus
169 // window growth/shrinkage (at the top/bottom) have to be tracked incrementally.
170 // Allowing shrinking from the zoomed state also requires tracking: We check on
171 // any shrink whether we're both zoomed and have previously grown -- if so, we
172 // set a flag, and constrain any resize by the allowed amounts. On further
173 // shrinks, we check the flag (since the size/position of the window will no
174 // longer indicate that the window is shrinking from an apparent zoomed state)
175 // and if it's set we continue to constrain the resize.
177 using content::OpenURLParams;
178 using content::Referrer;
179 using content::RenderWidgetHostView;
180 using content::WebContents;
181 using web_modal::WebContentsModalDialogManager;
183 @interface NSWindow (NSPrivateApis)
184 // Note: These functions are private, use -[NSObject respondsToSelector:]
185 // before calling them.
187 - (void)setBottomCornerRounded:(BOOL)rounded;
189 - (NSRect)_growBoxRect;
193 @implementation BrowserWindowController
195 + (BrowserWindowController*)browserWindowControllerForWindow:(NSWindow*)window {
197 id controller = [window windowController];
198 if ([controller isKindOfClass:[BrowserWindowController class]])
199 return (BrowserWindowController*)controller;
200 window = [window parentWindow];
205 + (BrowserWindowController*)browserWindowControllerForView:(NSView*)view {
206 NSWindow* window = [view window];
207 return [BrowserWindowController browserWindowControllerForWindow:window];
210 + (void)updateSigninItem:(id)signinItem
211 shouldShow:(BOOL)showSigninMenuItem
212 currentProfile:(Profile*)profile {
213 DCHECK([signinItem isKindOfClass:[NSMenuItem class]]);
214 NSMenuItem* signinMenuItem = static_cast<NSMenuItem*>(signinItem);
216 // Look for a separator immediately after the menu item so it can be hidden
217 // or shown appropriately along with the signin menu item.
218 NSMenuItem* followingSeparator = nil;
219 NSMenu* menu = [signinItem menu];
221 NSInteger signinItemIndex = [menu indexOfItem:signinMenuItem];
222 DCHECK_NE(signinItemIndex, -1);
223 if ((signinItemIndex + 1) < [menu numberOfItems]) {
224 NSMenuItem* menuItem = [menu itemAtIndex:(signinItemIndex + 1)];
225 if ([menuItem isSeparatorItem]) {
226 followingSeparator = menuItem;
231 base::string16 label = signin_ui_util::GetSigninMenuLabel(profile);
232 [signinMenuItem setTitle:l10n_util::FixUpWindowsStyleLabel(label)];
233 [signinMenuItem setHidden:!showSigninMenuItem];
234 [followingSeparator setHidden:!showSigninMenuItem];
237 // Load the browser window nib and do any Cocoa-specific initialization.
238 // Takes ownership of |browser|. Note that the nib also sets this controller
239 // up as the window's delegate.
240 - (id)initWithBrowser:(Browser*)browser {
241 return [self initWithBrowser:browser takeOwnership:YES];
244 // Private(TestingAPI) init routine with testing options.
245 - (id)initWithBrowser:(Browser*)browser takeOwnership:(BOOL)ownIt {
246 bool hasTabStrip = browser->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
247 if ((self = [super initTabWindowControllerWithTabStrip:hasTabStrip])) {
250 browser_.reset(browser);
251 ownsBrowser_ = ownIt;
252 NSWindow* window = [self window];
253 // Make the content view for the window have a layer. This will make all
254 // sub-views have layers. This is necessary to ensure correct layer
255 // ordering of all child views and their layers.
256 [[window contentView] cr_setWantsLayer:YES];
257 windowShim_.reset(new BrowserWindowCocoa(browser, self));
259 // Set different minimum sizes on tabbed windows vs non-tabbed, e.g. popups.
260 // This has to happen before -enforceMinWindowSize: is called further down.
261 NSSize minSize = [self isTabbedWindow] ?
262 NSMakeSize(400, 272) : NSMakeSize(100, 122);
263 [[self window] setMinSize:minSize];
265 // Create the bar visibility lock set; 10 is arbitrary, but should hopefully
266 // be big enough to hold all locks that'll ever be needed.
267 barVisibilityLocks_.reset([[NSMutableSet setWithCapacity:10] retain]);
269 // Set the window to not have rounded corners, which prevents the resize
270 // control from being inset slightly and looking ugly. Only bother to do
271 // this on Snow Leopard; on Lion and later all windows have rounded bottom
272 // corners, and this won't work anyway.
273 if (base::mac::IsOSSnowLeopard() &&
274 [window respondsToSelector:@selector(setBottomCornerRounded:)])
275 [window setBottomCornerRounded:NO];
277 // Lion will attempt to automagically save and restore the UI. This
278 // functionality appears to be leaky (or at least interacts badly with our
279 // architecture) and thus BrowserWindowController never gets released. This
280 // prevents the browser from being able to quit <http://crbug.com/79113>.
281 if ([window respondsToSelector:@selector(setRestorable:)])
282 [window setRestorable:NO];
284 // Get the windows to swish in on Lion.
285 if ([window respondsToSelector:@selector(setAnimationBehavior:)])
286 [window setAnimationBehavior:NSWindowAnimationBehaviorDocumentWindow];
288 // Get the most appropriate size for the window, then enforce the
289 // minimum width and height. The window shim will handle flipping
290 // the coordinates for us so we can use it to save some code.
291 // Note that this may leave a significant portion of the window
292 // offscreen, but there will always be enough window onscreen to
293 // drag the whole window back into view.
294 ui::WindowShowState show_state = ui::SHOW_STATE_DEFAULT;
295 gfx::Rect desiredContentRect;
296 chrome::GetSavedWindowBoundsAndShowState(browser_.get(),
299 gfx::Rect windowRect = desiredContentRect;
300 windowRect = [self enforceMinWindowSize:windowRect];
302 // When we are given x/y coordinates of 0 on a created popup window, assume
303 // none were given by the window.open() command.
304 if (browser_->is_type_popup() &&
305 windowRect.x() == 0 && windowRect.y() == 0) {
306 gfx::Size size = windowRect.size();
307 windowRect.set_origin(
308 WindowSizer::GetDefaultPopupOrigin(size,
309 browser_->host_desktop_type()));
312 // Size and position the window. Note that it is not yet onscreen. Popup
313 // windows may get resized later on in this function, once the actual size
314 // of the toolbar/tabstrip is known.
315 windowShim_->SetBounds(windowRect);
317 // Puts the incognito badge on the window frame, if necessary.
318 [self installAvatar];
320 // Create a sub-controller for the docked devTools and add its view to the
322 devToolsController_.reset([[DevToolsController alloc] init]);
323 [[devToolsController_ view] setFrame:[[self tabContentArea] bounds]];
324 [[self tabContentArea] addSubview:[devToolsController_ view]];
326 // Create the overlayable contents controller. This provides the switch
327 // view that TabStripController needs.
328 overlayableContentsController_.reset(
329 [[OverlayableContentsController alloc] initWithBrowser:browser]);
330 [[overlayableContentsController_ view]
331 setFrame:[[devToolsController_ view] bounds]];
332 [[devToolsController_ view]
333 addSubview:[overlayableContentsController_ view]];
335 // Create a controller for the tab strip, giving it the model object for
336 // this window's Browser and the tab strip view. The controller will handle
337 // registering for the appropriate tab notifications from the back-end and
338 // managing the creation of new tabs.
339 [self createTabStripController];
341 // Create a controller for the toolbar, giving it the toolbar model object
342 // and the toolbar view from the nib. The controller will handle
343 // registering for the appropriate command state changes from the back-end.
344 // Adds the toolbar to the content area.
345 toolbarController_.reset([[ToolbarController alloc]
346 initWithCommands:browser->command_controller()->command_updater()
347 profile:browser->profile()
349 resizeDelegate:self]);
350 [toolbarController_ setHasToolbar:[self hasToolbar]
351 hasLocationBar:[self hasLocationBar]];
353 // Create a sub-controller for the bookmark bar.
354 bookmarkBarController_.reset(
355 [[BookmarkBarController alloc]
356 initWithBrowser:browser_.get()
357 initialWidth:NSWidth([[[self window] contentView] frame])
359 resizeDelegate:self]);
360 [bookmarkBarController_ setBookmarkBarEnabled:[self supportsBookmarkBar]];
362 // Create the infobar container view, so we can pass it to the
363 // ToolbarController.
364 infoBarContainerController_.reset(
365 [[InfoBarContainerController alloc] initWithResizeDelegate:self]);
366 [self updateInfoBarTipVisibility];
368 // We don't want to try and show the bar before it gets placed in its parent
369 // view, so this step shoudn't be inside the bookmark bar controller's
371 windowShim_->BookmarkBarStateChanged(
372 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
374 // Allow bar visibility to be changed.
375 [self enableBarVisibilityUpdates];
377 // Force a relayout of all the various bars.
378 [self layoutSubviews];
380 // Set the window to participate in Lion Fullscreen mode. Setting this flag
381 // has no effect on Snow Leopard or earlier. Panels can share a fullscreen
382 // space with a tabbed window, but they can not be primary fullscreen
383 // windows. Do this after |-layoutSubviews| so that the fullscreen button
384 // can be adjusted in FramedBrowserWindow.
385 NSUInteger collectionBehavior = [window collectionBehavior];
386 collectionBehavior |=
387 browser_->type() == Browser::TYPE_TABBED ||
388 browser_->type() == Browser::TYPE_POPUP ?
389 NSWindowCollectionBehaviorFullScreenPrimary :
390 NSWindowCollectionBehaviorFullScreenAuxiliary;
391 [window setCollectionBehavior:collectionBehavior];
393 // For a popup window, |desiredContentRect| contains the desired height of
394 // the content, not of the whole window. Now that all the views are laid
395 // out, measure the current content area size and grow if needed. The
396 // window has not been placed onscreen yet, so this extra resize will not
397 // cause visible jank.
398 if (browser_->is_type_popup()) {
399 CGFloat deltaH = desiredContentRect.height() -
400 NSHeight([[self tabContentArea] frame]);
401 // Do not shrink the window, as that may break minimum size invariants.
403 // Convert from tabContentArea coordinates to window coordinates.
404 NSSize convertedSize =
405 [[self tabContentArea] convertSize:NSMakeSize(0, deltaH)
407 NSRect frame = [[self window] frame];
408 frame.size.height += convertedSize.height;
409 frame.origin.y -= convertedSize.height;
410 [[self window] setFrame:frame display:NO];
414 // Create the bridge for the status bubble.
415 statusBubble_ = new StatusBubbleMac([self window], self);
417 // Create the permissions bubble.
418 permissionBubbleCocoa_.reset(new PermissionBubbleCocoa([self window]));
420 // Register for application hide/unhide notifications.
421 [[NSNotificationCenter defaultCenter]
423 selector:@selector(applicationDidHide:)
424 name:NSApplicationDidHideNotification
426 [[NSNotificationCenter defaultCenter]
428 selector:@selector(applicationDidUnhide:)
429 name:NSApplicationDidUnhideNotification
432 // This must be done after the view is added to the window since it relies
433 // on the window bounds to determine whether to show buttons or not.
434 if ([self hasToolbar]) // Do not create the buttons in popups.
435 [toolbarController_ createBrowserActionButtons];
437 extension_keybinding_registry_.reset(
438 new ExtensionKeybindingRegistryCocoa(browser_->profile(),
440 extensions::ExtensionKeybindingRegistry::ALL_EXTENSIONS,
443 // We are done initializing now.
450 browser_->tab_strip_model()->CloseAllTabs();
451 [downloadShelfController_ exiting];
453 // Explicitly release |presentationModeController_| here, as it may call back
454 // to this BWC in |-dealloc|. We are required to call |-exitPresentationMode|
455 // before releasing the controller.
456 [presentationModeController_ exitPresentationMode];
457 presentationModeController_.reset();
459 // Under certain testing configurations we may not actually own the browser.
460 if (ownsBrowser_ == NO)
461 ignore_result(browser_.release());
463 [[NSNotificationCenter defaultCenter] removeObserver:self];
468 - (gfx::Rect)enforceMinWindowSize:(gfx::Rect)bounds {
469 gfx::Rect checkedBounds = bounds;
471 NSSize minSize = [[self window] minSize];
472 if (bounds.width() < minSize.width)
473 checkedBounds.set_width(minSize.width);
474 if (bounds.height() < minSize.height)
475 checkedBounds.set_height(minSize.height);
477 return checkedBounds;
480 - (BrowserWindow*)browserWindow {
481 return windowShim_.get();
484 - (ToolbarController*)toolbarController {
485 return toolbarController_.get();
488 - (TabStripController*)tabStripController {
489 return tabStripController_.get();
492 - (FindBarCocoaController*)findBarCocoaController {
493 return findBarCocoaController_.get();
496 - (InfoBarContainerController*)infoBarContainerController {
497 return infoBarContainerController_.get();
500 - (StatusBubbleMac*)statusBubble {
501 return statusBubble_;
504 - (LocationBarViewMac*)locationBarBridge {
505 return [toolbarController_ locationBarBridge];
508 - (NSView*)floatingBarBackingView {
509 return floatingBarBackingView_;
512 - (OverlayableContentsController*)overlayableContentsController {
513 return overlayableContentsController_;
516 - (Profile*)profile {
517 return browser_->profile();
520 - (AvatarBaseController*)avatarButtonController {
521 return avatarButtonController_.get();
524 - (void)destroyBrowser {
525 [NSApp removeWindowsItem:[self window]];
527 // We need the window to go away now.
528 // We can't actually use |-autorelease| here because there's an embedded
529 // run loop in the |-performClose:| which contains its own autorelease pool.
530 // Instead call it after a zero-length delay, which gets us back to the main
532 [self performSelector:@selector(autorelease)
537 // Called when the window meets the criteria to be closed (ie,
538 // |-windowShouldClose:| returns YES). We must be careful to preserve the
539 // semantics of BrowserWindow::Close() and not call the Browser's dtor directly
541 - (void)windowWillClose:(NSNotification*)notification {
542 DCHECK_EQ([notification object], [self window]);
543 DCHECK(browser_->tab_strip_model()->empty());
544 [savedRegularWindow_ close];
545 // We delete statusBubble here because we need to kill off the dependency
546 // that its window has on our window before our window goes away.
547 delete statusBubble_;
548 statusBubble_ = NULL;
549 // We can't actually use |-autorelease| here because there's an embedded
550 // run loop in the |-performClose:| which contains its own autorelease pool.
551 // Instead call it after a zero-length delay, which gets us back to the main
553 [self performSelector:@selector(autorelease)
558 - (void)updateDevToolsForContents:(WebContents*)contents {
559 [devToolsController_ updateDevToolsForWebContents:contents
560 withProfile:browser_->profile()];
561 [self updateAllowOverlappingViews:[self inPresentationMode]];
564 // Called when the user wants to close a window or from the shutdown process.
565 // The Browser object is in control of whether or not we're allowed to close. It
566 // may defer closing due to several states, such as onUnload handlers needing to
567 // be fired. If closing is deferred, the Browser will handle the processing
568 // required to get us to the closing state and (by watching for all the tabs
569 // going away) will again call to close the window when it's finally ready.
570 - (BOOL)windowShouldClose:(id)sender {
571 // Disable updates while closing all tabs to avoid flickering.
572 gfx::ScopedNSDisableScreenUpdates disabler;
573 // Give beforeunload handlers the chance to cancel the close before we hide
575 if (!browser_->ShouldCloseWindow())
578 // saveWindowPositionIfNeeded: only works if we are the last active
579 // window, but orderOut: ends up activating another window, so we
580 // have to save the window position before we call orderOut:.
581 [self saveWindowPositionIfNeeded];
583 bool fast_tab_closing_enabled =
584 CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableFastUnload);
586 if (!browser_->tab_strip_model()->empty()) {
587 // Tab strip isn't empty. Hide the frame (so it appears to have closed
588 // immediately) and close all the tabs, allowing the renderers to shut
589 // down. When the tab strip is empty we'll be called back again.
590 [[self window] orderOut:self];
591 browser_->OnWindowClosing();
592 if (fast_tab_closing_enabled)
593 browser_->tab_strip_model()->CloseAllTabs();
595 } else if (fast_tab_closing_enabled &&
596 !browser_->HasCompletedUnloadProcessing()) {
597 // The browser needs to finish running unload handlers.
598 // Hide the window (so it appears to have closed immediately), and
599 // the browser will call us back again when it is ready to close.
600 [[self window] orderOut:self];
604 // the tab strip is empty, it's ok to close the window
608 // Called right after our window became the main window.
609 - (void)windowDidBecomeMain:(NSNotification*)notification {
610 BrowserList::SetLastActive(browser_.get());
611 [self saveWindowPositionIfNeeded];
613 // TODO(dmaclach): Instead of redrawing the whole window, views that care
614 // about the active window state should be registering for notifications.
615 [[self window] setViewsNeedDisplay:YES];
617 // TODO(viettrungluu): For some reason, the above doesn't suffice.
618 if ([self isFullscreen])
619 [floatingBarBackingView_ setNeedsDisplay:YES]; // Okay even if nil.
622 - (void)windowDidResignMain:(NSNotification*)notification {
623 // TODO(dmaclach): Instead of redrawing the whole window, views that care
624 // about the active window state should be registering for notifications.
625 [[self window] setViewsNeedDisplay:YES];
627 // TODO(viettrungluu): For some reason, the above doesn't suffice.
628 if ([self isFullscreen])
629 [floatingBarBackingView_ setNeedsDisplay:YES]; // Okay even if nil.
632 // Called when we are activated (when we gain focus).
633 - (void)windowDidBecomeKey:(NSNotification*)notification {
634 // We need to activate the controls (in the "WebView"). To do this, get the
635 // selected WebContents's RenderWidgetHostView and tell it to activate.
636 if (WebContents* contents =
637 browser_->tab_strip_model()->GetActiveWebContents()) {
639 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
642 RenderWidgetHostView* devtoolsView = devtools->GetRenderWidgetHostView();
643 if (devtoolsView && devtoolsView->HasFocus()) {
644 devtoolsView->SetActive(true);
649 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
650 rwhv->SetActive(true);
654 // Called when we are deactivated (when we lose focus).
655 - (void)windowDidResignKey:(NSNotification*)notification {
656 // If our app is still active and we're still the key window, ignore this
657 // message, since it just means that a menu extra (on the "system status bar")
658 // was activated; we'll get another |-windowDidResignKey| if we ever really
659 // lose key window status.
660 if ([NSApp isActive] && ([NSApp keyWindow] == [self window]))
663 // We need to deactivate the controls (in the "WebView"). To do this, get the
664 // selected WebContents's RenderWidgetHostView and tell it to deactivate.
665 if (WebContents* contents =
666 browser_->tab_strip_model()->GetActiveWebContents()) {
668 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
671 RenderWidgetHostView* devtoolsView = devtools->GetRenderWidgetHostView();
672 if (devtoolsView && devtoolsView->HasFocus()) {
673 devtoolsView->SetActive(false);
678 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
679 rwhv->SetActive(false);
683 // Called when we have been minimized.
684 - (void)windowDidMiniaturize:(NSNotification *)notification {
685 [self saveWindowPositionIfNeeded];
687 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
688 if (WebContents* contents =
689 browser_->tab_strip_model()->GetActiveWebContents()) {
690 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
691 rwhv->SetWindowVisibility(false);
695 // Called when we have been unminimized.
696 - (void)windowDidDeminiaturize:(NSNotification *)notification {
697 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
698 if (WebContents* contents =
699 browser_->tab_strip_model()->GetActiveWebContents()) {
700 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
701 rwhv->SetWindowVisibility(true);
705 // Called when the application has been hidden.
706 - (void)applicationDidHide:(NSNotification *)notification {
707 // Let the selected RenderWidgetHostView know, so that it can tell plugins
708 // (unless we are minimized, in which case nothing has really changed).
709 if (![[self window] isMiniaturized]) {
710 if (WebContents* contents =
711 browser_->tab_strip_model()->GetActiveWebContents()) {
712 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
713 rwhv->SetWindowVisibility(false);
718 // Called when the application has been unhidden.
719 - (void)applicationDidUnhide:(NSNotification *)notification {
720 // Let the selected RenderWidgetHostView know, so that it can tell plugins
721 // (unless we are minimized, in which case nothing has really changed).
722 if (![[self window] isMiniaturized]) {
723 if (WebContents* contents =
724 browser_->tab_strip_model()->GetActiveWebContents()) {
725 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
726 rwhv->SetWindowVisibility(true);
731 // Called when the user clicks the zoom button (or selects it from the Window
732 // menu) to determine the "standard size" of the window, based on the content
733 // and other factors. If the current size/location differs nontrivally from the
734 // standard size, Cocoa resizes the window to the standard size, and saves the
735 // current size as the "user size". If the current size/location is the same (up
736 // to a fudge factor) as the standard size, Cocoa resizes the window to the
737 // saved user size. (It is possible for the two to coincide.) In this way, the
738 // zoom button acts as a toggle. We determine the standard size based on the
739 // content, but enforce a minimum width (calculated using the dimensions of the
740 // screen) to ensure websites with small intrinsic width (such as google.com)
741 // don't end up with a wee window. Moreover, we always declare the standard
742 // width to be at least as big as the current width, i.e., we never want zooming
743 // to the standard width to shrink the window. This is consistent with other
744 // browsers' behaviour, and is desirable in multi-tab situations. Note, however,
745 // that the "toggle" behaviour means that the window can still be "unzoomed" to
747 - (NSRect)windowWillUseStandardFrame:(NSWindow*)window
748 defaultFrame:(NSRect)frame {
749 // Forget that we grew the window up (if we in fact did).
750 [self resetWindowGrowthState];
752 // |frame| already fills the current screen. Never touch y and height since we
753 // always want to fill vertically.
755 // If the shift key is down, maximize. Hopefully this should make the
756 // "switchers" happy.
757 if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask) {
761 // To prevent strange results on portrait displays, the basic minimum zoomed
762 // width is the larger of: 60% of available width, 60% of available height
763 // (bounded by available width).
764 const CGFloat kProportion = 0.6;
765 CGFloat zoomedWidth =
766 std::max(kProportion * NSWidth(frame),
767 std::min(kProportion * NSHeight(frame), NSWidth(frame)));
769 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
771 // If the intrinsic width is bigger, then make it the zoomed width.
772 const int kScrollbarWidth = 16; // TODO(viettrungluu): ugh.
773 CGFloat intrinsicWidth = static_cast<CGFloat>(
774 contents->GetPreferredSize().width() + kScrollbarWidth);
775 zoomedWidth = std::max(zoomedWidth,
776 std::min(intrinsicWidth, NSWidth(frame)));
779 // Never shrink from the current size on zoom (see above).
780 NSRect currentFrame = [[self window] frame];
781 zoomedWidth = std::max(zoomedWidth, NSWidth(currentFrame));
783 // |frame| determines our maximum extents. We need to set the origin of the
784 // frame -- and only move it left if necessary.
785 if (currentFrame.origin.x + zoomedWidth > NSMaxX(frame))
786 frame.origin.x = NSMaxX(frame) - zoomedWidth;
788 frame.origin.x = currentFrame.origin.x;
790 // Set the width. Don't touch y or height.
791 frame.size.width = zoomedWidth;
797 [BrowserWindowUtils activateWindowForController:self];
800 // Determine whether we should let a window zoom/unzoom to the given |newFrame|.
801 // We avoid letting unzoom move windows between screens, because it's really
802 // strange and unintuitive.
803 - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame {
804 // Figure out which screen |newFrame| is on.
805 NSScreen* newScreen = nil;
806 CGFloat newScreenOverlapArea = 0.0;
807 for (NSScreen* screen in [NSScreen screens]) {
808 NSRect overlap = NSIntersectionRect(newFrame, [screen frame]);
809 CGFloat overlapArea = NSWidth(overlap) * NSHeight(overlap);
810 if (overlapArea > newScreenOverlapArea) {
812 newScreenOverlapArea = overlapArea;
815 // If we're somehow not on any screen, allow the zoom.
819 // If the new screen is the current screen, we can return a definitive YES.
820 // Note: This check is not strictly necessary, but just short-circuits in the
821 // "no-brainer" case. To test the complicated logic below, comment this out!
822 NSScreen* curScreen = [window screen];
823 if (newScreen == curScreen)
826 // Worry a little: What happens when a window is on two (or more) screens?
827 // E.g., what happens in a 50-50 scenario? Cocoa may reasonably elect to zoom
828 // to the other screen rather than staying on the officially current one. So
829 // we compare overlaps with the current window frame, and see if Cocoa's
830 // choice was reasonable (allowing a small rounding error). This should
831 // hopefully avoid us ever erroneously denying a zoom when a window is on
833 NSRect curFrame = [window frame];
834 NSRect newScrIntersectCurFr = NSIntersectionRect([newScreen frame], curFrame);
835 NSRect curScrIntersectCurFr = NSIntersectionRect([curScreen frame], curFrame);
836 if (NSWidth(newScrIntersectCurFr) * NSHeight(newScrIntersectCurFr) >=
837 (NSWidth(curScrIntersectCurFr) * NSHeight(curScrIntersectCurFr) - 1.0)) {
841 // If it wasn't reasonable, return NO.
845 // Adjusts the window height by the given amount.
846 - (BOOL)adjustWindowHeightBy:(CGFloat)deltaH {
847 // By not adjusting the window height when initializing, we can ensure that
848 // the window opens with the same size that was saved on close.
849 if (initializing_ || [self isFullscreen] || deltaH == 0)
852 NSWindow* window = [self window];
853 NSRect windowFrame = [window frame];
854 NSRect workarea = [[window screen] visibleFrame];
856 // If the window is not already fully in the workarea, do not adjust its frame
858 if (!NSContainsRect(workarea, windowFrame))
861 // Record the position of the top/bottom of the window, so we can easily check
862 // whether we grew the window upwards/downwards.
863 CGFloat oldWindowMaxY = NSMaxY(windowFrame);
864 CGFloat oldWindowMinY = NSMinY(windowFrame);
866 // We are "zoomed" if we occupy the full vertical space.
867 bool isZoomed = (windowFrame.origin.y == workarea.origin.y &&
868 NSHeight(windowFrame) == NSHeight(workarea));
870 // If we're shrinking the window....
872 bool didChange = false;
874 // Don't reset if not currently zoomed since shrinking can take several
877 isShrinkingFromZoomed_ = YES;
879 // If we previously grew at the top, shrink as much as allowed at the top
881 if (windowTopGrowth_ > 0) {
882 CGFloat shrinkAtTopBy = MIN(-deltaH, windowTopGrowth_);
883 windowFrame.size.height -= shrinkAtTopBy; // Shrink the window.
884 deltaH += shrinkAtTopBy; // Update the amount left to shrink.
885 windowTopGrowth_ -= shrinkAtTopBy; // Update the growth state.
889 // Similarly for the bottom (not an "else if" since we may have to
890 // simultaneously shrink at both the top and at the bottom). Note that
891 // |deltaH| may no longer be nonzero due to the above.
892 if (deltaH < 0 && windowBottomGrowth_ > 0) {
893 CGFloat shrinkAtBottomBy = MIN(-deltaH, windowBottomGrowth_);
894 windowFrame.origin.y += shrinkAtBottomBy; // Move the window up.
895 windowFrame.size.height -= shrinkAtBottomBy; // Shrink the window.
896 deltaH += shrinkAtBottomBy; // Update the amount left....
897 windowBottomGrowth_ -= shrinkAtBottomBy; // Update the growth state.
901 // If we're shrinking from zoomed but we didn't change the top or bottom
902 // (since we've reached the limits imposed by |window...Growth_|), then stop
903 // here. Don't reset |isShrinkingFromZoomed_| since we might get called
904 // again for the same shrink.
905 if (isShrinkingFromZoomed_ && !didChange)
908 isShrinkingFromZoomed_ = NO;
910 // Don't bother with anything else.
915 // Shrinking from zoomed is handled above (and is constrained by
916 // |window...Growth_|).
917 if (!isShrinkingFromZoomed_) {
918 // Resize the window down until it hits the bottom of the workarea, then if
919 // needed continue resizing upwards. Do not resize the window to be taller
920 // than the current workarea.
921 // Resize the window as requested, keeping the top left corner fixed.
922 windowFrame.origin.y -= deltaH;
923 windowFrame.size.height += deltaH;
925 // If the bottom left corner is now outside the visible frame, move the
926 // window up to make it fit, but make sure not to move the top left corner
927 // out of the visible frame.
928 if (windowFrame.origin.y < workarea.origin.y) {
929 windowFrame.origin.y = workarea.origin.y;
930 windowFrame.size.height =
931 std::min(NSHeight(windowFrame), NSHeight(workarea));
934 // Record (if applicable) how much we grew the window in either direction.
935 // (N.B.: These only record growth, not shrinkage.)
936 if (NSMaxY(windowFrame) > oldWindowMaxY)
937 windowTopGrowth_ += NSMaxY(windowFrame) - oldWindowMaxY;
938 if (NSMinY(windowFrame) < oldWindowMinY)
939 windowBottomGrowth_ += oldWindowMinY - NSMinY(windowFrame);
942 // Disable subview resizing while resizing the window, or else we will get
943 // unwanted renderer resizes. The calling code must call layoutSubviews to
944 // make things right again.
945 NSView* contentView = [window contentView];
946 [contentView setAutoresizesSubviews:NO];
947 [window setFrame:windowFrame display:NO];
948 [contentView setAutoresizesSubviews:YES];
952 // Main method to resize browser window subviews. This method should be called
953 // when resizing any child of the content view, rather than resizing the views
954 // directly. If the view is already the correct height, does not force a
956 - (void)resizeView:(NSView*)view newHeight:(CGFloat)height {
957 // We should only ever be called for one of the following four views.
958 // |downloadShelfController_| may be nil. If we are asked to size the bookmark
959 // bar directly, its superview must be this controller's content view.
961 DCHECK(view == [toolbarController_ view] ||
962 view == [infoBarContainerController_ view] ||
963 view == [downloadShelfController_ view] ||
964 view == [bookmarkBarController_ view]);
966 // Change the height of the view and call |-layoutSubViews|. We set the height
967 // here without regard to where the view is on the screen or whether it needs
968 // to "grow up" or "grow down." The below call to |-layoutSubviews| will
969 // position each view correctly.
970 NSRect frame = [view frame];
971 if (NSHeight(frame) == height)
974 // Disable screen updates to prevent flickering.
975 gfx::ScopedNSDisableScreenUpdates disabler;
977 // Grow or shrink the window by the amount of the height change. We adjust
978 // the window height only in two cases:
979 // 1) We are adjusting the height of the bookmark bar and it is currently
980 // animating either open or closed.
981 // 2) We are adjusting the height of the download shelf.
983 // We do not adjust the window height for bookmark bar changes on the NTP.
984 BOOL shouldAdjustBookmarkHeight =
985 [bookmarkBarController_ isAnimatingBetweenState:BookmarkBar::HIDDEN
986 andState:BookmarkBar::SHOW];
988 BOOL resizeRectDirty = NO;
989 if ((shouldAdjustBookmarkHeight && view == [bookmarkBarController_ view]) ||
990 view == [downloadShelfController_ view]) {
991 CGFloat deltaH = height - NSHeight(frame);
992 if ([self adjustWindowHeightBy:deltaH] &&
993 view == [downloadShelfController_ view]) {
994 // If the window height didn't change, the download shelf will change the
995 // size of the contents. If the contents size doesn't change, send it
996 // an explicit grow box invalidation (else, the resize message does that.)
997 resizeRectDirty = YES;
1001 frame.size.height = height;
1002 // TODO(rohitrao): Determine if calling setFrame: twice is bad.
1003 [view setFrame:frame];
1004 [self layoutSubviews];
1006 if (resizeRectDirty) {
1007 // Send new resize rect to foreground tab.
1008 if (content::WebContents* contents =
1009 browser_->tab_strip_model()->GetActiveWebContents()) {
1010 if (content::RenderViewHost* rvh = contents->GetRenderViewHost()) {
1011 rvh->ResizeRectChanged(windowShim_->GetRootWindowResizerRect());
1017 - (void)setAnimationInProgress:(BOOL)inProgress {
1018 [[self tabContentArea] setFastResizeMode:inProgress];
1021 // Update a toggle state for an NSMenuItem if modified.
1022 // Take care to ensure |item| looks like a NSMenuItem.
1023 // Called by validateUserInterfaceItem:.
1024 - (void)updateToggleStateWithTag:(NSInteger)tag forItem:(id)item {
1025 if (![item respondsToSelector:@selector(state)] ||
1026 ![item respondsToSelector:@selector(setState:)])
1029 // On Windows this logic happens in bookmark_bar_view.cc. On the
1030 // Mac we're a lot more MVC happy so we've moved it into a
1031 // controller. To be clear, this simply updates the menu item; it
1032 // does not display the bookmark bar itself.
1033 if (tag == IDC_SHOW_BOOKMARK_BAR) {
1034 bool toggled = windowShim_->IsBookmarkBarVisible();
1035 NSInteger oldState = [(NSMenuItem*)item state];
1036 NSInteger newState = toggled ? NSOnState : NSOffState;
1037 if (oldState != newState)
1038 [item setState:newState];
1041 // Update the checked/Unchecked state of items in the encoding menu.
1042 // On Windows, this logic is part of |EncodingMenuModel| in
1043 // browser/ui/views/toolbar_view.h.
1044 EncodingMenuController encoding_controller;
1045 if (encoding_controller.DoesCommandBelongToEncodingMenu(tag)) {
1046 DCHECK(browser_.get());
1047 Profile* profile = browser_->profile();
1049 WebContents* current_tab =
1050 browser_->tab_strip_model()->GetActiveWebContents();
1054 const std::string encoding = current_tab->GetEncoding();
1056 bool toggled = encoding_controller.IsItemChecked(profile, encoding, tag);
1057 NSInteger oldState = [(NSMenuItem*)item state];
1058 NSInteger newState = toggled ? NSOnState : NSOffState;
1059 if (oldState != newState)
1060 [item setState:newState];
1064 // Called to validate menu and toolbar items when this window is key. All the
1065 // items we care about have been set with the |-commandDispatch:| or
1066 // |-commandDispatchUsingKeyModifiers:| actions and a target of FirstResponder
1067 // in IB. If it's not one of those, let it continue up the responder chain to be
1068 // handled elsewhere. We pull out the tag as the cross-platform constant to
1069 // differentiate and dispatch the various commands.
1070 // NOTE: we might have to handle state for app-wide menu items,
1071 // although we could cheat and directly ask the app controller if our
1072 // command_updater doesn't support the command. This may or may not be an issue,
1073 // too early to tell.
1074 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
1075 SEL action = [item action];
1077 if (action == @selector(commandDispatch:) ||
1078 action == @selector(commandDispatchUsingKeyModifiers:)) {
1079 NSInteger tag = [item tag];
1080 if (chrome::SupportsCommand(browser_.get(), tag)) {
1081 // Generate return value (enabled state)
1082 enable = chrome::IsCommandEnabled(browser_.get(), tag);
1085 // Disable "close tab" if the receiving window is not tabbed.
1086 // We simply check whether the item has a keyboard shortcut set here;
1087 // app_controller_mac.mm actually determines whether the item should
1089 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item))
1090 enable &= !![[menuItem keyEquivalent] length];
1092 case IDC_FULLSCREEN: {
1093 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item)) {
1094 NSString* menuTitle = l10n_util::GetNSString(
1095 [self isFullscreen] && ![self inPresentationMode] ?
1096 IDS_EXIT_FULLSCREEN_MAC :
1097 IDS_ENTER_FULLSCREEN_MAC);
1098 [menuItem setTitle:menuTitle];
1100 if (!chrome::mac::SupportsSystemFullscreen())
1101 [menuItem setHidden:YES];
1105 case IDC_PRESENTATION_MODE: {
1106 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item)) {
1107 NSString* menuTitle = l10n_util::GetNSString(
1108 [self inPresentationMode] ? IDS_EXIT_PRESENTATION_MAC :
1109 IDS_ENTER_PRESENTATION_MAC);
1110 [menuItem setTitle:menuTitle];
1114 case IDC_SHOW_SIGNIN: {
1115 Profile* original_profile =
1116 browser_->profile()->GetOriginalProfile();
1117 [BrowserWindowController updateSigninItem:item
1119 currentProfile:original_profile];
1122 case IDC_BOOKMARK_PAGE: {
1123 // Extensions have the ability to hide the bookmark page menu item.
1124 // This only affects the bookmark page menu item under the main menu.
1125 // The bookmark page menu item under the wrench menu has its
1126 // visibility controlled by WrenchMenuModel.
1128 chrome::ShouldRemoveBookmarkThisPageUI(browser_->profile());
1129 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
1130 [menuItem setHidden:shouldHide];
1133 case IDC_BOOKMARK_ALL_TABS: {
1134 // Extensions have the ability to hide the bookmark all tabs menu
1135 // item. This only affects the bookmark page menu item under the main
1136 // menu. The bookmark page menu item under the wrench menu has its
1137 // visibility controlled by WrenchMenuModel.
1139 chrome::ShouldRemoveBookmarkOpenPagesUI(browser_->profile());
1140 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
1141 [menuItem setHidden:shouldHide];
1145 // Special handling for the contents of the Text Encoding submenu. On
1146 // Mac OS, instead of enabling/disabling the top-level menu item, we
1147 // enable/disable the submenu's contents (per Apple's HIG).
1148 EncodingMenuController encoding_controller;
1149 if (encoding_controller.DoesCommandBelongToEncodingMenu(tag)) {
1150 enable &= chrome::IsCommandEnabled(browser_.get(),
1151 IDC_ENCODING_MENU) ? YES : NO;
1155 // If the item is toggleable, find its toggle state and
1156 // try to update it. This is a little awkward, but the alternative is
1157 // to check after a commandDispatch, which seems worse.
1158 [self updateToggleStateWithTag:tag forItem:item];
1164 // Called when the user picks a menu or toolbar item when this window is key.
1165 // Calls through to the browser object to execute the command. This assumes that
1166 // the command is supported and doesn't check, otherwise it would have been
1167 // disabled in the UI in validateUserInterfaceItem:.
1168 - (void)commandDispatch:(id)sender {
1170 // Identify the actual BWC to which the command should be dispatched. It might
1171 // belong to a background window, yet this controller gets it because it is
1172 // the foreground window's controller and thus in the responder chain. Some
1173 // senders don't have this problem (for example, menus only operate on the
1174 // foreground window), so this is only an issue for senders that are part of
1176 BrowserWindowController* targetController = self;
1177 if ([sender respondsToSelector:@selector(window)])
1178 targetController = [[sender window] windowController];
1179 DCHECK([targetController isKindOfClass:[BrowserWindowController class]]);
1180 DCHECK(targetController->browser_.get());
1181 chrome::ExecuteCommand(targetController->browser_.get(), [sender tag]);
1184 // Same as |-commandDispatch:|, but executes commands using a disposition
1185 // determined by the key flags. If the window is in the background and the
1186 // command key is down, ignore the command key, but process any other modifiers.
1187 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1190 if (![sender isEnabled]) {
1191 // This code is reachable e.g. if the user mashes the back button, queuing
1192 // up a bunch of events before the button's enabled state is updated:
1193 // http://crbug.com/63254
1197 // See comment above for why we do this.
1198 BrowserWindowController* targetController = self;
1199 if ([sender respondsToSelector:@selector(window)])
1200 targetController = [[sender window] windowController];
1201 DCHECK([targetController isKindOfClass:[BrowserWindowController class]]);
1202 DCHECK(targetController->browser_.get());
1204 NSInteger command = [sender tag];
1205 NSUInteger modifierFlags = [[NSApp currentEvent] modifierFlags];
1206 if ((command == IDC_RELOAD) &&
1207 (modifierFlags & (NSShiftKeyMask | NSControlKeyMask))) {
1208 command = IDC_RELOAD_IGNORING_CACHE;
1209 // Mask off Shift and Control so they don't affect the disposition below.
1210 modifierFlags &= ~(NSShiftKeyMask | NSControlKeyMask);
1212 if (![[sender window] isMainWindow]) {
1213 // Remove the command key from the flags, it means "keep the window in
1214 // the background" in this case.
1215 modifierFlags &= ~NSCommandKeyMask;
1217 chrome::ExecuteCommandWithDisposition(
1218 targetController->browser_.get(), command,
1219 ui::WindowOpenDispositionFromNSEventWithFlags(
1220 [NSApp currentEvent], modifierFlags));
1223 // Called when another part of the internal codebase needs to execute a
1225 - (void)executeCommand:(int)command {
1226 chrome::ExecuteCommand(browser_.get(), command);
1229 - (BOOL)handledByExtensionCommand:(NSEvent*)event {
1230 return extension_keybinding_registry_->ProcessKeyEvent(
1231 content::NativeWebKeyboardEvent(event));
1234 // StatusBubble delegate method: tell the status bubble the frame it should
1235 // position itself in.
1236 - (NSRect)statusBubbleBaseFrame {
1237 NSView* view = [overlayableContentsController_ view];
1238 return [view convertRect:[view bounds] toView:nil];
1241 - (void)updateToolbarWithContents:(WebContents*)tab {
1242 [toolbarController_ updateToolbarWithContents:tab];
1245 - (void)setStarredState:(BOOL)isStarred {
1246 [toolbarController_ setStarredState:isStarred];
1249 - (void)setCurrentPageIsTranslated:(BOOL)on {
1250 [toolbarController_ setTranslateIconLit:on];
1253 - (void)zoomChangedForActiveTab:(BOOL)canShowBubble {
1254 [toolbarController_ zoomChangedForActiveTab:canShowBubble];
1257 // Return the rect, in WebKit coordinates (flipped), of the window's grow box
1258 // in the coordinate system of the content area of the currently selected tab.
1259 // |windowGrowBox| needs to be in the window's coordinate system.
1260 - (NSRect)selectedTabGrowBoxRect {
1261 NSWindow* window = [self window];
1262 if (![window respondsToSelector:@selector(_growBoxRect)])
1265 // Before we return a rect, we need to convert it from window coordinates
1266 // to tab content area coordinates and flip the coordinate system.
1267 NSRect growBoxRect =
1268 [[self tabContentArea] convertRect:[window _growBoxRect] fromView:nil];
1269 growBoxRect.origin.y =
1270 NSHeight([[self tabContentArea] frame]) - NSMaxY(growBoxRect);
1274 // Accept tabs from a BrowserWindowController with the same Profile.
1275 - (BOOL)canReceiveFrom:(TabWindowController*)source {
1276 BrowserWindowController* realSource =
1277 base::mac::ObjCCast<BrowserWindowController>(source);
1278 if (!realSource || browser_->profile() != realSource->browser_->profile()) {
1282 // Can't drag a tab from a normal browser to a pop-up
1283 if (browser_->type() != realSource->browser_->type()) {
1290 // Move a given tab view to the location of the current placeholder. If there is
1291 // no placeholder, it will go at the end. |controller| is the window controller
1292 // of a tab being dropped from a different window. It will be nil if the drag is
1293 // within the window, otherwise the tab is removed from that window before being
1294 // placed into this one. The implementation will call |-removePlaceholder| since
1295 // the drag is now complete. This also calls |-layoutTabs| internally so
1296 // clients do not need to call it again.
1297 - (void)moveTabViews:(NSArray*)views
1298 fromController:(TabWindowController*)dragController {
1299 if (dragController) {
1300 // Moving between windows.
1301 NSView* activeTabView = [dragController activeTabView];
1302 BrowserWindowController* dragBWC =
1303 base::mac::ObjCCastStrict<BrowserWindowController>(dragController);
1305 // We will drop the tabs starting at indexOfPlaceholder, and increment from
1306 // there. We remove the placehoder before dropping the tabs, so that the
1307 // new tab animation's destination frame is correct.
1308 int tabIndex = [tabStripController_ indexOfPlaceholder];
1309 [self removePlaceholder];
1311 for (NSView* view in views) {
1312 // Figure out the WebContents to drop into our tab model from the source
1314 int index = [dragBWC->tabStripController_ modelIndexForTabView:view];
1315 WebContents* contents =
1316 dragBWC->browser_->tab_strip_model()->GetWebContentsAt(index);
1317 // The tab contents may have gone away if given a window.close() while it
1318 // is being dragged. If so, bail, we've got nothing to drop.
1322 // Convert |view|'s frame (which starts in the source tab strip's
1323 // coordinate system) to the coordinate system of the destination tab
1324 // strip. This needs to be done before being detached so the window
1325 // transforms can be performed.
1326 NSRect destinationFrame = [view frame];
1327 NSPoint tabOrigin = destinationFrame.origin;
1328 tabOrigin = [[dragController tabStripView] convertPoint:tabOrigin
1330 tabOrigin = [[dragController window] convertBaseToScreen:tabOrigin];
1331 tabOrigin = [[self window] convertScreenToBase:tabOrigin];
1332 tabOrigin = [[self tabStripView] convertPoint:tabOrigin fromView:nil];
1333 destinationFrame.origin = tabOrigin;
1335 // Before the tab is detached from its originating tab strip, store the
1336 // pinned state so that it can be maintained between the windows.
1337 bool isPinned = dragBWC->browser_->tab_strip_model()->IsTabPinned(index);
1339 // Now that we have enough information about the tab, we can remove it
1340 // from the dragging window. We need to do this *before* we add it to the
1341 // new window as this will remove the WebContents' delegate.
1342 [dragController detachTabView:view];
1344 // Deposit it into our model at the appropriate location (it already knows
1345 // where it should go from tracking the drag). Doing this sets the tab's
1346 // delegate to be the Browser.
1347 [tabStripController_ dropWebContents:contents
1349 withFrame:destinationFrame
1350 asPinnedTab:isPinned
1351 activate:view == activeTabView];
1354 // Moving within a window.
1355 for (NSView* view in views) {
1356 int index = [tabStripController_ modelIndexForTabView:view];
1357 [tabStripController_ moveTabFromIndex:index];
1359 [self removePlaceholder];
1363 // Tells the tab strip to forget about this tab in preparation for it being
1364 // put into a different tab strip, such as during a drop on another window.
1365 - (void)detachTabView:(NSView*)view {
1366 int index = [tabStripController_ modelIndexForTabView:view];
1367 browser_->tab_strip_model()->DetachWebContentsAt(index);
1370 - (NSArray*)tabViews {
1371 return [tabStripController_ tabViews];
1374 - (NSView*)activeTabView {
1375 return [tabStripController_ activeTabView];
1378 - (void)setIsLoading:(BOOL)isLoading force:(BOOL)force {
1379 [toolbarController_ setIsLoading:isLoading force:force];
1382 // Make the location bar the first responder, if possible.
1383 - (void)focusLocationBar:(BOOL)selectAll {
1384 [[self window] makeKeyWindow];
1385 [toolbarController_ focusLocationBar:selectAll];
1388 - (void)focusTabContents {
1389 content::WebContents* const activeWebContents =
1390 browser_->tab_strip_model()->GetActiveWebContents();
1391 if (activeWebContents)
1392 activeWebContents->Focus();
1395 - (void)layoutTabs {
1396 [tabStripController_ layoutTabs];
1399 - (TabWindowController*)detachTabsToNewWindow:(NSArray*)tabViews
1400 draggedTab:(NSView*)draggedTab {
1401 DCHECK_GT([tabViews count], 0U);
1403 // Disable screen updates so that this appears as a single visual change.
1404 gfx::ScopedNSDisableScreenUpdates disabler;
1406 // Set the window size. Need to do this before we detach the tab so it's
1407 // still in the window. We have to flip the coordinates as that's what
1408 // is expected by the Browser code.
1409 NSWindow* sourceWindow = [draggedTab window];
1410 NSRect windowRect = [sourceWindow frame];
1411 NSScreen* screen = [sourceWindow screen];
1412 windowRect.origin.y = NSHeight([screen frame]) - NSMaxY(windowRect);
1413 gfx::Rect browserRect(windowRect.origin.x, windowRect.origin.y,
1414 NSWidth(windowRect), NSHeight(windowRect));
1416 std::vector<TabStripModelDelegate::NewStripContents> contentses;
1417 TabStripModel* model = browser_->tab_strip_model();
1419 for (TabView* tabView in tabViews) {
1420 // Fetch the tab contents for the tab being dragged.
1421 int index = [tabStripController_ modelIndexForTabView:tabView];
1422 bool isPinned = model->IsTabPinned(index);
1423 bool isActive = (index == model->active_index());
1425 TabStripModelDelegate::NewStripContents item;
1426 item.web_contents = model->GetWebContentsAt(index);
1428 (isActive ? TabStripModel::ADD_ACTIVE : TabStripModel::ADD_NONE) |
1429 (isPinned ? TabStripModel::ADD_PINNED : TabStripModel::ADD_NONE);
1430 contentses.push_back(item);
1433 for (TabView* tabView in tabViews) {
1434 int index = [tabStripController_ modelIndexForTabView:tabView];
1435 // Detach it from the source window, which just updates the model without
1436 // deleting the tab contents. This needs to come before creating the new
1437 // Browser because it clears the WebContents' delegate, which gets hooked
1438 // up during creation of the new window.
1439 model->DetachWebContentsAt(index);
1442 // Create a new window with the dragged tabs in its model.
1443 Browser* newBrowser = browser_->tab_strip_model()->delegate()->
1444 CreateNewStripWithContents(contentses, browserRect, false);
1446 // Get the new controller by asking the new window for its delegate.
1447 BrowserWindowController* controller =
1448 reinterpret_cast<BrowserWindowController*>(
1449 [newBrowser->window()->GetNativeWindow() delegate]);
1450 DCHECK(controller && [controller isKindOfClass:[TabWindowController class]]);
1452 // And make sure we use the correct frame in the new view.
1453 TabStripController* tabStripController = [controller tabStripController];
1454 NSView* tabStrip = [self tabStripView];
1455 NSEnumerator* tabEnumerator = [tabViews objectEnumerator];
1456 for (NSView* newView in [tabStripController tabViews]) {
1457 NSView* oldView = [tabEnumerator nextObject];
1459 // Pushes tabView's frame back inside the tabstrip.
1460 NSRect sourceTabRect = [oldView frame];
1461 NSSize tabOverflow =
1462 [self overflowFrom:[tabStrip convertRect:sourceTabRect toView:nil]
1463 to:[tabStrip frame]];
1465 NSOffsetRect(sourceTabRect, -tabOverflow.width, -tabOverflow.height);
1466 // Force the added tab to the right size (remove stretching.)
1467 tabRect.size.height = [TabStripController defaultTabHeight];
1469 [tabStripController setFrame:tabRect ofTabView:newView];
1476 - (void)insertPlaceholderForTab:(TabView*)tab
1477 frame:(NSRect)frame {
1478 [super insertPlaceholderForTab:tab frame:frame];
1479 [tabStripController_ insertPlaceholderForTab:tab frame:frame];
1482 - (void)removePlaceholder {
1483 [super removePlaceholder];
1484 [tabStripController_ insertPlaceholderForTab:nil frame:NSZeroRect];
1487 - (BOOL)isDragSessionActive {
1488 // The tab can be dragged within the existing tab strip or detached
1489 // into its own window (then the overlay window will be present).
1490 return [[self tabStripController] isDragSessionActive] ||
1491 [self overlayWindow] != nil;
1494 - (BOOL)tabDraggingAllowed {
1495 return [tabStripController_ tabDraggingAllowed];
1498 - (BOOL)tabTearingAllowed {
1499 return ![self isFullscreen];
1502 - (BOOL)windowMovementAllowed {
1503 return ![self isFullscreen];
1506 - (BOOL)isTabFullyVisible:(TabView*)tab {
1507 return [tabStripController_ isTabFullyVisible:tab];
1510 - (void)showNewTabButton:(BOOL)show {
1511 [tabStripController_ showNewTabButton:show];
1514 - (BOOL)shouldShowAvatar {
1515 if (![self hasTabStrip])
1517 if (browser_->profile()->IsOffTheRecord())
1520 ProfileInfoCache& cache =
1521 g_browser_process->profile_manager()->GetProfileInfoCache();
1522 if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) ==
1523 std::string::npos) {
1527 return AvatarMenu::ShouldShowAvatarMenu();
1530 - (BOOL)shouldUseNewAvatarButton {
1531 return switches::IsNewAvatarMenu() &&
1532 profiles::IsRegularOrGuestSession(browser_.get());
1535 - (BOOL)isBookmarkBarVisible {
1536 return [bookmarkBarController_ isVisible];
1539 - (BOOL)isBookmarkBarAnimating {
1540 return [bookmarkBarController_ isAnimationRunning];
1543 - (BookmarkBarController*)bookmarkBarController {
1544 return bookmarkBarController_;
1547 - (DevToolsController*)devToolsController {
1548 return devToolsController_;
1551 - (BOOL)isDownloadShelfVisible {
1552 return downloadShelfController_ != nil &&
1553 [downloadShelfController_ isVisible];
1556 - (DownloadShelfController*)downloadShelf {
1557 if (!downloadShelfController_.get()) {
1558 downloadShelfController_.reset([[DownloadShelfController alloc]
1559 initWithBrowser:browser_.get() resizeDelegate:self]);
1560 [[[self window] contentView] addSubview:[downloadShelfController_ view]];
1562 return downloadShelfController_;
1565 - (void)addFindBar:(FindBarCocoaController*)findBarCocoaController {
1566 // Shouldn't call addFindBar twice.
1567 DCHECK(!findBarCocoaController_.get());
1569 // Create a controller for the findbar.
1570 findBarCocoaController_.reset([findBarCocoaController retain]);
1571 [self layoutSubviews];
1572 [self updateSubviewZOrder:[self inPresentationMode]];
1575 - (NSWindow*)createFullscreenWindow {
1576 return [[[FullscreenWindow alloc] initForScreen:[[self window] screen]]
1580 - (NSInteger)numberOfTabs {
1581 // count() includes pinned tabs.
1582 return browser_->tab_strip_model()->count();
1585 - (BOOL)hasLiveTabs {
1586 return !browser_->tab_strip_model()->empty();
1589 - (NSString*)activeTabTitle {
1590 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1591 return base::SysUTF16ToNSString(contents->GetTitle());
1594 - (NSRect)regularWindowFrame {
1595 return [self isFullscreen] ? savedRegularWindowFrame_ :
1596 [[self window] frame];
1599 // (Override of |TabWindowController| method.)
1600 - (BOOL)hasTabStrip {
1601 return [self supportsWindowFeature:Browser::FEATURE_TABSTRIP];
1604 - (BOOL)isTabDraggable:(NSView*)tabView {
1605 // TODO(avi, thakis): ConstrainedWindowSheetController has no api to move
1606 // tabsheets between windows. Until then, we have to prevent having to move a
1607 // tabsheet between windows, e.g. no tearing off of tabs.
1608 int index = [tabStripController_ modelIndexForTabView:tabView];
1609 WebContents* contents = browser_->tab_strip_model()->GetWebContentsAt(index);
1612 return !WebContentsModalDialogManager::FromWebContents(contents)->
1616 // TabStripControllerDelegate protocol.
1617 - (void)onActivateTabWithContents:(WebContents*)contents {
1618 // Update various elements that are interested in knowing the current
1621 // Update all the UI bits.
1622 windowShim_->UpdateTitleBar();
1624 // Update the bookmark bar.
1625 // TODO(viettrungluu): perhaps update to not terminate running animations (if
1627 windowShim_->BookmarkBarStateChanged(
1628 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
1630 [infoBarContainerController_ changeWebContents:contents];
1632 // No need to remove previous bubble. It will close itself.
1633 // TODO(leng): The PermissionBubbleManager for the previous contents should
1634 // have SetView(NULL) called. Fix this when the previous contents are
1635 // available here or move to BrowserWindowCocoa::OnActiveTabChanged().
1637 PermissionBubbleManager::FromWebContents(contents)->SetView(
1638 permissionBubbleCocoa_.get());
1640 // Must do this after bookmark and infobar updates to avoid
1641 // unnecesary resize in contents.
1642 [devToolsController_ updateDevToolsForWebContents:contents
1643 withProfile:browser_->profile()];
1645 [self updateAllowOverlappingViews:[self inPresentationMode]];
1648 - (void)onTabChanged:(TabStripModelObserver::TabChangeType)change
1649 withContents:(WebContents*)contents {
1650 // Update titles if this is the currently selected tab and if it isn't just
1651 // the loading state which changed.
1652 if (change != TabStripModelObserver::LOADING_ONLY)
1653 windowShim_->UpdateTitleBar();
1655 // Update the bookmark bar if this is the currently selected tab and if it
1656 // isn't just the title which changed. This for transitions between the NTP
1657 // (showing its floating bookmark bar) and normal web pages (showing no
1659 // TODO(viettrungluu): perhaps update to not terminate running animations?
1660 if (change != TabStripModelObserver::TITLE_NOT_LOADING) {
1661 windowShim_->BookmarkBarStateChanged(
1662 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
1666 - (void)onTabDetachedWithContents:(WebContents*)contents {
1667 [infoBarContainerController_ tabDetachedWithContents:contents];
1670 - (void)userChangedTheme {
1671 [[[[self window] contentView] superview] cr_recursivelySetNeedsDisplay:YES];
1674 - (ui::ThemeProvider*)themeProvider {
1675 return ThemeServiceFactory::GetForProfile(browser_->profile());
1678 - (ThemedWindowStyle)themedWindowStyle {
1679 ThemedWindowStyle style = 0;
1680 if (browser_->profile()->IsOffTheRecord())
1681 style |= THEMED_INCOGNITO;
1683 if (browser_->is_devtools())
1684 style |= THEMED_DEVTOOLS;
1685 if (browser_->is_type_popup())
1686 style |= THEMED_POPUP;
1691 - (NSPoint)themeImagePositionForAlignment:(ThemeImageAlignment)alignment {
1692 NSView* windowChromeView = [[[self window] contentView] superview];
1693 NSView* tabStripView = nil;
1694 if ([self hasTabStrip])
1695 tabStripView = [self tabStripView];
1696 return [BrowserWindowUtils themeImagePositionFor:windowChromeView
1697 withTabStrip:tabStripView
1698 alignment:alignment];
1701 - (NSPoint)bookmarkBubblePoint {
1702 return [toolbarController_ bookmarkBubblePoint];
1705 // Show the bookmark bubble (e.g. user just clicked on the STAR).
1706 - (void)showBookmarkBubbleForURL:(const GURL&)url
1707 alreadyBookmarked:(BOOL)alreadyMarked {
1708 if (!bookmarkBubbleController_) {
1709 BookmarkModel* model =
1710 BookmarkModelFactory::GetForProfile(browser_->profile());
1711 ChromeBookmarkClient* client =
1712 ChromeBookmarkClientFactory::GetForProfile(browser_->profile());
1713 const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(url);
1714 bookmarkBubbleController_ =
1715 [[BookmarkBubbleController alloc] initWithParentWindow:[self window]
1719 alreadyBookmarked:alreadyMarked];
1720 [bookmarkBubbleController_ showWindow:self];
1721 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1722 [center addObserver:self
1723 selector:@selector(bookmarkBubbleWindowWillClose:)
1724 name:NSWindowWillCloseNotification
1725 object:[bookmarkBubbleController_ window]];
1729 // Nil out the weak bookmark bubble controller reference.
1730 - (void)bookmarkBubbleWindowWillClose:(NSNotification*)notification {
1731 DCHECK_EQ([notification object], [bookmarkBubbleController_ window]);
1733 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1734 [center removeObserver:self
1735 name:NSWindowWillCloseNotification
1736 object:[bookmarkBubbleController_ window]];
1737 bookmarkBubbleController_ = nil;
1740 // Handle the editBookmarkNode: action sent from bookmark bubble controllers.
1741 - (void)editBookmarkNode:(id)sender {
1742 BOOL responds = [sender respondsToSelector:@selector(node)];
1745 const BookmarkNode* node = [sender node];
1747 BookmarkEditor::Show([self window], browser_->profile(),
1748 BookmarkEditor::EditDetails::EditNode(node),
1749 BookmarkEditor::SHOW_TREE);
1753 - (void)showTranslateBubbleForWebContents:(content::WebContents*)contents
1754 step:(translate::TranslateStep)step
1755 errorType:(TranslateErrors::Type)errorType {
1756 // TODO(hajimehoshi): The similar logic exists at TranslateBubbleView::
1757 // ShowBubble. This should be unified.
1758 if (translateBubbleController_) {
1759 // When the user reads the advanced setting panel, the bubble should not be
1760 // changed because he/she is focusing on the bubble.
1761 if (translateBubbleController_.webContents == contents &&
1762 translateBubbleController_.model->GetViewState() ==
1763 TranslateBubbleModel::VIEW_STATE_ADVANCED) {
1766 if (step != translate::TRANSLATE_STEP_TRANSLATE_ERROR) {
1767 TranslateBubbleModel::ViewState viewState =
1768 TranslateBubbleModelImpl::TranslateStepToViewState(step);
1769 [translateBubbleController_ switchView:viewState];
1771 [translateBubbleController_ switchToErrorView:errorType];
1776 std::string sourceLanguage;
1777 std::string targetLanguage;
1778 ChromeTranslateClient::GetTranslateLanguages(
1779 contents, &sourceLanguage, &targetLanguage);
1781 scoped_ptr<TranslateUIDelegate> uiDelegate(new TranslateUIDelegate(
1782 ChromeTranslateClient::GetManagerFromWebContents(contents)->GetWeakPtr(),
1785 scoped_ptr<TranslateBubbleModel> model(
1786 new TranslateBubbleModelImpl(step, uiDelegate.Pass()));
1787 translateBubbleController_ = [[TranslateBubbleController alloc]
1788 initWithParentWindow:self
1790 webContents:contents];
1791 [translateBubbleController_ showWindow:nil];
1793 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1794 [center addObserver:self
1795 selector:@selector(translateBubbleWindowWillClose:)
1796 name:NSWindowWillCloseNotification
1797 object:[translateBubbleController_ window]];
1800 // Nil out the weak translate bubble controller reference.
1801 - (void)translateBubbleWindowWillClose:(NSNotification*)notification {
1802 DCHECK_EQ([notification object], [translateBubbleController_ window]);
1804 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1805 [center removeObserver:self
1806 name:NSWindowWillCloseNotification
1807 object:[translateBubbleController_ window]];
1808 translateBubbleController_ = nil;
1811 // If the browser is in incognito mode or has multi-profiles, install the image
1812 // view to decorate the window at the upper right. Use the same base y
1813 // coordinate as the tab strip.
1814 - (void)installAvatar {
1815 // Install the image into the badge view. Hide it for now; positioning and
1816 // sizing will be done by the layout code. The AvatarIcon will choose which
1817 // image to display based on the browser. The AvatarButton will display
1818 // the browser profile's name unless the browser is incognito.
1820 if ([self shouldUseNewAvatarButton]) {
1821 avatarButtonController_.reset(
1822 [[AvatarButtonController alloc] initWithBrowser:browser_.get()]);
1824 avatarButtonController_.reset(
1825 [[AvatarIconController alloc] initWithBrowser:browser_.get()]);
1827 view = [avatarButtonController_ view];
1828 [view setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
1829 [view setHidden:![self shouldShowAvatar]];
1831 // Install the view.
1832 [[[self window] cr_windowView] addSubview:view];
1835 // Called when we get a three-finger swipe.
1836 - (void)swipeWithEvent:(NSEvent*)event {
1837 CGFloat deltaX = [event deltaX];
1838 CGFloat deltaY = [event deltaY];
1840 // Map forwards and backwards to history; left is positive, right is negative.
1841 unsigned int command = 0;
1844 } else if (deltaX < -0.5) {
1845 command = IDC_FORWARD;
1846 } else if (deltaY > 0.5) {
1847 // TODO(pinkerton): figure out page-up, http://crbug.com/16305
1848 } else if (deltaY < -0.5) {
1849 // TODO(pinkerton): figure out page-down, http://crbug.com/16305
1852 // Ensure the command is valid first (ExecuteCommand() won't do that) and
1854 if (chrome::IsCommandEnabled(browser_.get(), command)) {
1855 chrome::ExecuteCommandWithDisposition(
1858 ui::WindowOpenDispositionFromNSEvent(event));
1862 // Delegate method called when window is resized.
1863 - (void)windowDidResize:(NSNotification*)notification {
1864 [self saveWindowPositionIfNeeded];
1866 // Resize (and possibly move) the status bubble. Note that we may get called
1867 // when the status bubble does not exist.
1868 if (statusBubble_) {
1869 statusBubble_->UpdateSizeAndPosition();
1872 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
1873 if (WebContents* contents =
1874 browser_->tab_strip_model()->GetActiveWebContents()) {
1875 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
1876 rwhv->WindowFrameChanged();
1879 // The FindBar needs to know its own position to properly detect overlaps
1880 // with find results. The position changes whenever the window is resized,
1881 // and |layoutSubviews| computes the FindBar's position.
1882 // TODO: calling |layoutSubviews| here is a waste, find a better way to
1884 if ([findBarCocoaController_ isFindBarVisible])
1885 [self layoutSubviews];
1888 // Handle the openLearnMoreAboutCrashLink: action from SadTabController when
1889 // "Learn more" link in "Aw snap" page (i.e. crash page or sad tab) is
1890 // clicked. Decoupling the action from its target makes unit testing possible.
1891 - (void)openLearnMoreAboutCrashLink:(id)sender {
1892 if (SadTabController* sadTab =
1893 base::mac::ObjCCast<SadTabController>(sender)) {
1894 WebContents* webContents = [sadTab webContents];
1896 OpenURLParams params(
1897 GURL(chrome::kCrashReasonURL), Referrer(), CURRENT_TAB,
1898 content::PAGE_TRANSITION_LINK, false);
1899 webContents->OpenURL(params);
1904 // Delegate method called when window did move. (See below for why we don't use
1905 // |-windowWillMove:|, which is called less frequently than |-windowDidMove|
1907 - (void)windowDidMove:(NSNotification*)notification {
1908 [self saveWindowPositionIfNeeded];
1910 NSWindow* window = [self window];
1911 NSRect windowFrame = [window frame];
1912 NSRect workarea = [[window screen] visibleFrame];
1914 // We reset the window growth state whenever the window is moved out of the
1915 // work area or away (up or down) from the bottom or top of the work area.
1916 // Unfortunately, Cocoa sends |-windowWillMove:| too frequently (including
1917 // when clicking on the title bar to activate), and of course
1918 // |-windowWillMove| is called too early for us to apply our heuristic. (The
1919 // heuristic we use for detecting window movement is that if |windowTopGrowth_
1920 // > 0|, then we should be at the bottom of the work area -- if we're not,
1921 // we've moved. Similarly for the other side.)
1922 if (!NSContainsRect(workarea, windowFrame) ||
1923 (windowTopGrowth_ > 0 && NSMinY(windowFrame) != NSMinY(workarea)) ||
1924 (windowBottomGrowth_ > 0 && NSMaxY(windowFrame) != NSMaxY(workarea)))
1925 [self resetWindowGrowthState];
1927 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
1928 if (WebContents* contents =
1929 browser_->tab_strip_model()->GetActiveWebContents()) {
1930 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
1931 rwhv->WindowFrameChanged();
1935 // Delegate method called when window will be resized; not called for
1936 // |-setFrame:display:|.
1937 - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize {
1938 [self resetWindowGrowthState];
1942 // Delegate method: see |NSWindowDelegate| protocol.
1943 - (id)windowWillReturnFieldEditor:(NSWindow*)sender toObject:(id)obj {
1944 // Ask the toolbar controller if it wants to return a custom field editor
1945 // for the specific object.
1946 return [toolbarController_ customFieldEditorForObject:obj];
1949 // (Needed for |BookmarkBarControllerDelegate| protocol.)
1950 - (void)bookmarkBar:(BookmarkBarController*)controller
1951 didChangeFromState:(BookmarkBar::State)oldState
1952 toState:(BookmarkBar::State)newState {
1953 [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
1954 [self adjustToolbarAndBookmarkBarForCompression:
1955 [controller getDesiredToolbarHeightCompression]];
1958 // (Needed for |BookmarkBarControllerDelegate| protocol.)
1959 - (void)bookmarkBar:(BookmarkBarController*)controller
1960 willAnimateFromState:(BookmarkBar::State)oldState
1961 toState:(BookmarkBar::State)newState {
1962 [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
1963 [self adjustToolbarAndBookmarkBarForCompression:
1964 [controller getDesiredToolbarHeightCompression]];
1967 // (Private/TestingAPI)
1968 - (void)resetWindowGrowthState {
1969 windowTopGrowth_ = 0;
1970 windowBottomGrowth_ = 0;
1971 isShrinkingFromZoomed_ = NO;
1974 - (NSSize)overflowFrom:(NSRect)source
1976 // If |source|'s boundary is outside of |target|'s, set its distance
1977 // to |x|. Note that |source| can overflow to both side, but we
1978 // have nothing to do for such case.
1980 if (NSMaxX(target) < NSMaxX(source)) // |source| overflows to right
1981 x = NSMaxX(source) - NSMaxX(target);
1982 else if (NSMinX(source) < NSMinX(target)) // |source| overflows to left
1983 x = NSMinX(source) - NSMinX(target);
1985 // Same as |x| above.
1987 if (NSMaxY(target) < NSMaxY(source))
1988 y = NSMaxY(source) - NSMaxY(target);
1989 else if (NSMinY(source) < NSMinY(target))
1990 y = NSMinY(source) - NSMinY(target);
1992 return NSMakeSize(x, y);
1995 // (Private/TestingAPI)
1996 - (FullscreenExitBubbleController*)fullscreenExitBubbleController {
1997 return fullscreenExitBubbleController_.get();
2000 - (NSRect)omniboxPopupAnchorRect {
2001 // Start with toolbar rect.
2002 NSView* toolbarView = [toolbarController_ view];
2003 NSRect anchorRect = [toolbarView frame];
2005 // Adjust to account for height and possible bookmark bar. Compress by 1
2006 // to account for the separator.
2007 anchorRect.origin.y =
2008 NSMaxY(anchorRect) - [toolbarController_ desiredHeightForCompression:1];
2010 // Shift to window base coordinates.
2011 return [[toolbarView superview] convertRect:anchorRect toView:nil];
2014 - (void)layoutInfoBars {
2015 [self layoutSubviews];
2018 - (void)sheetDidEnd:(NSWindow*)sheet
2019 returnCode:(NSInteger)code
2020 context:(void*)context {
2021 [sheet orderOut:self];
2024 - (void)onFindBarVisibilityChanged {
2025 [self updateAllowOverlappingViews:[self inPresentationMode]];
2028 - (void)onOverlappedViewShown {
2029 ++overlappedViewCount_;
2030 [self updateAllowOverlappingViews:[self inPresentationMode]];
2033 - (void)onOverlappedViewHidden {
2034 --overlappedViewCount_;
2035 [self updateAllowOverlappingViews:[self inPresentationMode]];
2038 - (void)executeExtensionCommand:(const std::string&)extension_id
2039 command:(const extensions::Command&)command {
2040 // Global commands are handled by the ExtensionCommandsGlobalRegistry
2042 DCHECK(!command.global());
2043 extension_keybinding_registry_->ExecuteCommand(extension_id,
2044 command.accelerator());
2047 - (void)activatePageAction:(const std::string&)extension_id {
2048 [toolbarController_ activatePageAction:extension_id];
2051 - (void)activateBrowserAction:(const std::string&)extension_id {
2052 [toolbarController_ activateBrowserAction:extension_id];
2055 @end // @implementation BrowserWindowController
2058 @implementation BrowserWindowController(Fullscreen)
2060 - (void)handleLionToggleFullscreen {
2061 DCHECK(base::mac::IsOSLionOrLater());
2062 chrome::ExecuteCommand(browser_.get(), IDC_FULLSCREEN);
2065 // Called to transition into or out of fullscreen mode. Only use System
2066 // Fullscreen mode if the system supports it and we aren't trying to go
2067 // fullscreen for the renderer-initiated use cases.
2068 // Discussion: http://crbug.com/179181 and http:/crbug.com/351252
2069 - (void)setFullscreen:(BOOL)fullscreen {
2070 if (fullscreen == [self isFullscreen])
2074 const BOOL shouldUseSystemFullscreen =
2075 chrome::mac::SupportsSystemFullscreen() && !fullscreenWindow_ &&
2076 !browser_->fullscreen_controller()->IsWindowFullscreenForTabOrPending();
2077 if (shouldUseSystemFullscreen) {
2078 if (FramedBrowserWindow* framedBrowserWindow =
2079 base::mac::ObjCCast<FramedBrowserWindow>([self window])) {
2080 [framedBrowserWindow toggleSystemFullScreen];
2083 [self enterImmersiveFullscreen];
2086 if ([self isInSystemFullscreen]) {
2087 if (FramedBrowserWindow* framedBrowserWindow =
2088 base::mac::ObjCCast<FramedBrowserWindow>([self window])) {
2089 [framedBrowserWindow toggleSystemFullScreen];
2092 DCHECK(fullscreenWindow_.get());
2093 [self exitImmersiveFullscreen];
2098 - (void)enterFullscreen {
2099 [self setFullscreen:YES];
2102 - (void)exitFullscreen {
2103 [self setFullscreen:NO];
2106 - (void)updateFullscreenExitBubbleURL:(const GURL&)url
2107 bubbleType:(FullscreenExitBubbleType)bubbleType {
2108 fullscreenUrl_ = url;
2109 fullscreenBubbleType_ = bubbleType;
2110 [self layoutSubviews];
2111 [self showFullscreenExitBubbleIfNecessary];
2114 - (BOOL)isFullscreen {
2115 return [self isInImmersiveFullscreen] ||
2116 [self isInSystemFullscreen] ||
2117 enteringFullscreen_;
2120 - (BOOL)isInImmersiveFullscreen {
2121 return fullscreenWindow_.get() != nil;
2124 - (BOOL)isInSystemFullscreen {
2125 return ([[self window] styleMask] & NSFullScreenWindowMask) ==
2126 NSFullScreenWindowMask;
2129 // On Lion, this function is called by either the presentation mode toggle
2130 // button or the "Enter Presentation Mode" menu item. In the latter case, this
2131 // function also triggers the Lion machinery to enter fullscreen mode as well as
2132 // set presentation mode. On Snow Leopard, this function is called by the
2133 // "Enter Presentation Mode" menu item, and triggering presentation mode always
2134 // moves the user into fullscreen mode.
2135 - (void)setPresentationMode:(BOOL)presentationMode
2136 url:(const GURL&)url
2137 bubbleType:(FullscreenExitBubbleType)bubbleType {
2138 fullscreenUrl_ = url;
2139 fullscreenBubbleType_ = bubbleType;
2141 // Presentation mode on systems without fullscreen support maps directly to
2143 if (!chrome::mac::SupportsSystemFullscreen()) {
2144 [self setFullscreen:presentationMode];
2148 if (presentationMode) {
2149 BOOL fullscreen = [self isFullscreen];
2150 enteringPresentationMode_ = YES;
2153 // If already in fullscreen mode, just toggle the presentation mode
2154 // setting. Go through an elaborate dance to force the overlay to show,
2155 // then animate out once the mouse moves away. This helps draw attention
2156 // to the fact that the UI is in an overlay. Focus the tab contents
2157 // because the omnibox is the most likely source of bar visibility locks,
2158 // and taking focus away from the omnibox releases its lock.
2159 [self lockBarVisibilityForOwner:self withAnimation:NO delay:NO];
2160 [self focusTabContents];
2161 [self setPresentationModeInternal:YES forceDropdown:YES];
2162 [self releaseBarVisibilityForOwner:self withAnimation:YES delay:YES];
2163 // Since -windowDidEnterFullScreen: won't be called in the
2164 // fullscreen --> presentation mode case, manually show the exit bubble
2165 // and notify the change happened with WindowFullscreenStateChanged().
2166 [self showFullscreenExitBubbleIfNecessary];
2167 browser_->WindowFullscreenStateChanged();
2169 // Need to transition into fullscreen mode. Presentation mode will
2170 // automatically be enabled in |-windowWillEnterFullScreen:|.
2171 [self setFullscreen:YES];
2174 // Exiting presentation mode does not exit system fullscreen; it merely
2175 // switches from presentation mode to normal fullscreen.
2176 [self setPresentationModeInternal:NO forceDropdown:NO];
2178 // Since -windowDidExitFullScreen: won't be called in the
2179 // presentation mode --> normal fullscreen case, manually show the exit
2180 // bubble and notify the change happened with
2181 // WindowFullscreenStateChanged().
2182 [self showFullscreenExitBubbleIfNecessary];
2183 browser_->WindowFullscreenStateChanged();
2187 - (void)enterPresentationModeForURL:(const GURL&)url
2188 bubbleType:(FullscreenExitBubbleType)bubbleType {
2189 [self setPresentationMode:YES url:url bubbleType:bubbleType];
2192 - (void)exitPresentationMode {
2193 // url: and bubbleType: are ignored when leaving presentation mode.
2194 [self setPresentationMode:NO url:GURL() bubbleType:FEB_TYPE_NONE];
2197 - (void)enterFullscreenForURL:(const GURL&)url
2198 bubbleType:(FullscreenExitBubbleType)bubbleType {
2199 // This method may only be called in simplified fullscreen mode.
2200 const CommandLine* command_line = CommandLine::ForCurrentProcess();
2201 DCHECK(command_line->HasSwitch(switches::kEnableSimplifiedFullscreen));
2203 [self enterImmersiveFullscreen];
2204 [self updateFullscreenExitBubbleURL:url bubbleType:bubbleType];
2207 - (BOOL)inPresentationMode {
2208 return presentationModeController_.get() &&
2209 [presentationModeController_ inPresentationMode];
2212 - (void)resizeFullscreenWindow {
2213 DCHECK([self isFullscreen]);
2214 if (![self isFullscreen])
2217 NSWindow* window = [self window];
2218 [window setFrame:[[window screen] frame] display:YES];
2219 [self layoutSubviews];
2222 - (CGFloat)floatingBarShownFraction {
2223 return floatingBarShownFraction_;
2226 - (void)setFloatingBarShownFraction:(CGFloat)fraction {
2227 floatingBarShownFraction_ = fraction;
2228 [self layoutSubviews];
2231 - (BOOL)isBarVisibilityLockedForOwner:(id)owner {
2233 DCHECK(barVisibilityLocks_);
2234 return [barVisibilityLocks_ containsObject:owner];
2237 - (void)lockBarVisibilityForOwner:(id)owner
2238 withAnimation:(BOOL)animate
2240 if (![self isBarVisibilityLockedForOwner:owner]) {
2241 [barVisibilityLocks_ addObject:owner];
2243 // If enabled, show the overlay if necessary (and if in presentation mode).
2244 if (barVisibilityUpdatesEnabled_) {
2245 [presentationModeController_ ensureOverlayShownWithAnimation:animate
2251 - (void)releaseBarVisibilityForOwner:(id)owner
2252 withAnimation:(BOOL)animate
2254 if ([self isBarVisibilityLockedForOwner:owner]) {
2255 [barVisibilityLocks_ removeObject:owner];
2257 // If enabled, hide the overlay if necessary (and if in presentation mode).
2258 if (barVisibilityUpdatesEnabled_ &&
2259 ![barVisibilityLocks_ count]) {
2260 [presentationModeController_ ensureOverlayHiddenWithAnimation:animate
2266 - (BOOL)floatingBarHasFocus {
2267 NSResponder* focused = [[self window] firstResponder];
2268 return [focused isKindOfClass:[AutocompleteTextFieldEditor class]];
2271 @end // @implementation BrowserWindowController(Fullscreen)
2274 @implementation BrowserWindowController(WindowType)
2276 - (BOOL)supportsWindowFeature:(int)feature {
2277 return browser_->SupportsWindowFeature(
2278 static_cast<Browser::WindowFeature>(feature));
2281 - (BOOL)hasTitleBar {
2282 return [self supportsWindowFeature:Browser::FEATURE_TITLEBAR];
2285 - (BOOL)hasToolbar {
2286 return [self supportsWindowFeature:Browser::FEATURE_TOOLBAR];
2289 - (BOOL)hasLocationBar {
2290 return [self supportsWindowFeature:Browser::FEATURE_LOCATIONBAR];
2293 - (BOOL)supportsBookmarkBar {
2294 return [self supportsWindowFeature:Browser::FEATURE_BOOKMARKBAR];
2297 - (BOOL)isTabbedWindow {
2298 return browser_->is_type_tabbed();
2301 @end // @implementation BrowserWindowController(WindowType)