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 #import "chrome/browser/app_controller_mac.h"
19 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
20 #include "chrome/browser/bookmarks/managed_bookmark_service_factory.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/devtools/devtools_window.h"
23 #include "chrome/browser/extensions/extension_commands_global_registry.h"
24 #include "chrome/browser/fullscreen.h"
25 #include "chrome/browser/profiles/avatar_menu.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/profiles/profile_info_cache.h"
28 #include "chrome/browser/profiles/profile_manager.h"
29 #include "chrome/browser/profiles/profiles_state.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_layout.h"
47 #import "chrome/browser/ui/cocoa/browser_window_utils.h"
48 #import "chrome/browser/ui/cocoa/dev_tools_controller.h"
49 #import "chrome/browser/ui/cocoa/download/download_shelf_controller.h"
50 #include "chrome/browser/ui/cocoa/extensions/extension_keybinding_registry_cocoa.h"
51 #import "chrome/browser/ui/cocoa/fast_resize_view.h"
52 #import "chrome/browser/ui/cocoa/find_bar/find_bar_bridge.h"
53 #import "chrome/browser/ui/cocoa/find_bar/find_bar_cocoa_controller.h"
54 #import "chrome/browser/ui/cocoa/framed_browser_window.h"
55 #import "chrome/browser/ui/cocoa/fullscreen_window.h"
56 #import "chrome/browser/ui/cocoa/infobars/infobar_container_controller.h"
57 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
58 #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.h"
59 #import "chrome/browser/ui/cocoa/presentation_mode_controller.h"
60 #import "chrome/browser/ui/cocoa/profiles/avatar_base_controller.h"
61 #import "chrome/browser/ui/cocoa/profiles/avatar_button_controller.h"
62 #import "chrome/browser/ui/cocoa/profiles/avatar_icon_controller.h"
63 #import "chrome/browser/ui/cocoa/status_bubble_mac.h"
64 #import "chrome/browser/ui/cocoa/tab_contents/overlayable_contents_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/exclusive_access/fullscreen_controller.h"
73 #include "chrome/browser/ui/location_bar/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 "chrome/grit/generated_resources.h"
84 #include "chrome/grit/locale_settings.h"
85 #include "components/bookmarks/browser/bookmark_model.h"
86 #include "components/bookmarks/managed/managed_bookmark_service.h"
87 #include "components/signin/core/common/profile_management_switches.h"
88 #include "components/translate/core/browser/translate_manager.h"
89 #include "components/translate/core/browser/translate_ui_delegate.h"
90 #include "components/web_modal/web_contents_modal_dialog_manager.h"
91 #include "content/public/browser/render_view_host.h"
92 #include "content/public/browser/render_widget_host_view.h"
93 #include "content/public/browser/web_contents.h"
94 #import "ui/base/cocoa/cocoa_base_utils.h"
95 #import "ui/base/cocoa/nsview_additions.h"
96 #include "ui/base/l10n/l10n_util.h"
97 #include "ui/base/l10n/l10n_util_mac.h"
98 #include "ui/gfx/mac/scoped_cocoa_disable_screen_updates.h"
100 using bookmarks::BookmarkModel;
101 using bookmarks::BookmarkNode;
102 using l10n_util::GetStringUTF16;
103 using l10n_util::GetNSStringWithFixup;
104 using l10n_util::GetNSStringFWithFixup;
106 // ORGANIZATION: This is a big file. It is (in principle) organized as follows
108 // 1. Interfaces. Very short, one-time-use classes may include an implementation
109 // immediately after their interface.
110 // 2. The general implementation section, ordered as follows:
111 // i. Public methods and overrides.
112 // ii. Overrides/implementations of undocumented methods.
113 // iii. Delegate methods for various protocols, formal and informal, to which
114 // |BrowserWindowController| conforms.
115 // 3. (temporary) Implementation sections for various categories.
117 // Private methods are defined and implemented separately in
118 // browser_window_controller_private.{h,mm}.
120 // Not all of the above guidelines are followed and more (re-)organization is
121 // needed. BUT PLEASE TRY TO KEEP THIS FILE ORGANIZED. I'd rather re-organize as
122 // little as possible, since doing so messes up the file's history.
124 // TODO(viettrungluu): [crbug.com/35543] on-going re-organization, splitting
125 // things into multiple files -- the plan is as follows:
126 // - in general, everything stays in browser_window_controller.h, but is split
127 // off into categories (see below)
128 // - core stuff stays in browser_window_controller.mm
129 // - ... overrides also stay (without going into a category, in particular)
130 // - private stuff which everyone needs goes into
131 // browser_window_controller_private.{h,mm}; if no one else needs them, they
132 // can go in individual files (see below)
133 // - area/task-specific stuff go in browser_window_controller_<area>.mm
134 // - ... in categories called "(<Area>)" or "(<PrivateArea>)"
136 // - first re-organize into categories
137 // - then split into files
139 // Notes on self-inflicted (not user-inflicted) window resizing and moving:
141 // When the bookmark bar goes from hidden to shown (on a non-NTP) page, or when
142 // the download shelf goes from hidden to shown, we grow the window downwards in
143 // order to maintain a constant content area size. When either goes from shown
144 // to hidden, we consequently shrink the window from the bottom, also to keep
145 // the content area size constant. To keep things simple, if the window is not
146 // entirely on-screen, we don't grow/shrink the window.
148 // The complications come in when there isn't enough room (on screen) below the
149 // window to accomodate the growth. In this case, we grow the window first
150 // downwards, and then upwards. So, when it comes to shrinking, we do the
151 // opposite: shrink from the top by the amount by which we grew at the top, and
152 // then from the bottom -- unless the user moved/resized/zoomed the window, in
153 // which case we "reset state" and just shrink from the bottom.
155 // A further complication arises due to the way in which "zoom" ("maximize")
156 // works on Mac OS X. Basically, for our purposes, a window is "zoomed" whenever
157 // it occupies the full available vertical space. (Note that the green zoom
158 // button does not track zoom/unzoomed state per se, but basically relies on
159 // this heuristic.) We don't, in general, want to shrink the window if the
160 // window is zoomed (scenario: window is zoomed, download shelf opens -- which
161 // doesn't cause window growth, download shelf closes -- shouldn't cause the
162 // window to become unzoomed!). However, if we grew the window
163 // (upwards/downwards) to become zoomed in the first place, we *should* shrink
164 // the window by the amounts by which we grew (scenario: window occupies *most*
165 // of vertical space, download shelf opens causing growth so that window
166 // occupies all of vertical space -- i.e., window is effectively zoomed,
167 // download shelf closes -- should return the window to its previous state).
169 // A major complication is caused by the way grows/shrinks are handled and
170 // animated. Basically, the BWC doesn't see the global picture, but it sees
171 // grows and shrinks in small increments (as dictated by the animation). Thus
172 // window growth/shrinkage (at the top/bottom) have to be tracked incrementally.
173 // Allowing shrinking from the zoomed state also requires tracking: We check on
174 // any shrink whether we're both zoomed and have previously grown -- if so, we
175 // set a flag, and constrain any resize by the allowed amounts. On further
176 // shrinks, we check the flag (since the size/position of the window will no
177 // longer indicate that the window is shrinking from an apparent zoomed state)
178 // and if it's set we continue to constrain the resize.
180 using content::OpenURLParams;
181 using content::Referrer;
182 using content::RenderWidgetHostView;
183 using content::WebContents;
185 @interface NSWindow (NSPrivateApis)
186 // Note: These functions are private, use -[NSObject respondsToSelector:]
187 // before calling them.
189 - (void)setBottomCornerRounded:(BOOL)rounded;
191 - (NSRect)_growBoxRect;
195 @implementation BrowserWindowController
197 + (BrowserWindowController*)browserWindowControllerForWindow:(NSWindow*)window {
199 id controller = [window windowController];
200 if ([controller isKindOfClass:[BrowserWindowController class]])
201 return (BrowserWindowController*)controller;
202 window = [window parentWindow];
207 + (BrowserWindowController*)browserWindowControllerForView:(NSView*)view {
208 NSWindow* window = [view window];
209 return [BrowserWindowController browserWindowControllerForWindow:window];
212 // Load the browser window nib and do any Cocoa-specific initialization.
213 // Takes ownership of |browser|. Note that the nib also sets this controller
214 // up as the window's delegate.
215 - (id)initWithBrowser:(Browser*)browser {
216 return [self initWithBrowser:browser takeOwnership:YES];
219 // Private(TestingAPI) init routine with testing options.
220 - (id)initWithBrowser:(Browser*)browser takeOwnership:(BOOL)ownIt {
221 bool hasTabStrip = browser->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
222 if ((self = [super initTabWindowControllerWithTabStrip:hasTabStrip])) {
225 browser_.reset(browser);
226 ownsBrowser_ = ownIt;
227 NSWindow* window = [self window];
228 // Make the content view for the window have a layer. This will make all
229 // sub-views have layers. This is necessary to ensure correct layer
230 // ordering of all child views and their layers.
231 [[window contentView] setWantsLayer:YES];
232 windowShim_.reset(new BrowserWindowCocoa(browser, self));
234 // Set different minimum sizes on tabbed windows vs non-tabbed, e.g. popups.
235 // This has to happen before -enforceMinWindowSize: is called further down.
236 NSSize minSize = [self isTabbedWindow] ?
237 NSMakeSize(400, 272) : NSMakeSize(100, 122);
238 [[self window] setMinSize:minSize];
240 // Create the bar visibility lock set; 10 is arbitrary, but should hopefully
241 // be big enough to hold all locks that'll ever be needed.
242 barVisibilityLocks_.reset([[NSMutableSet setWithCapacity:10] retain]);
244 // Set the window to not have rounded corners, which prevents the resize
245 // control from being inset slightly and looking ugly. Only bother to do
246 // this on Snow Leopard; on Lion and later all windows have rounded bottom
247 // corners, and this won't work anyway.
248 if (base::mac::IsOSSnowLeopard() &&
249 [window respondsToSelector:@selector(setBottomCornerRounded:)])
250 [window setBottomCornerRounded:NO];
252 // Lion will attempt to automagically save and restore the UI. This
253 // functionality appears to be leaky (or at least interacts badly with our
254 // architecture) and thus BrowserWindowController never gets released. This
255 // prevents the browser from being able to quit <http://crbug.com/79113>.
256 if ([window respondsToSelector:@selector(setRestorable:)])
257 [window setRestorable:NO];
259 // Get the windows to swish in on Lion.
260 if ([window respondsToSelector:@selector(setAnimationBehavior:)])
261 [window setAnimationBehavior:NSWindowAnimationBehaviorDocumentWindow];
263 // Get the most appropriate size for the window, then enforce the
264 // minimum width and height. The window shim will handle flipping
265 // the coordinates for us so we can use it to save some code.
266 // Note that this may leave a significant portion of the window
267 // offscreen, but there will always be enough window onscreen to
268 // drag the whole window back into view.
269 ui::WindowShowState show_state = ui::SHOW_STATE_DEFAULT;
270 gfx::Rect desiredContentRect;
271 chrome::GetSavedWindowBoundsAndShowState(browser_.get(),
274 gfx::Rect windowRect = desiredContentRect;
275 windowRect = [self enforceMinWindowSize:windowRect];
277 // When we are given x/y coordinates of 0 on a created popup window, assume
278 // none were given by the window.open() command.
279 if (browser_->is_type_popup() &&
280 windowRect.x() == 0 && windowRect.y() == 0) {
281 gfx::Size size = windowRect.size();
282 windowRect.set_origin(
283 WindowSizer::GetDefaultPopupOrigin(size,
284 browser_->host_desktop_type()));
287 // Size and position the window. Note that it is not yet onscreen. Popup
288 // windows may get resized later on in this function, once the actual size
289 // of the toolbar/tabstrip is known.
290 windowShim_->SetBounds(windowRect);
292 // Puts the incognito badge on the window frame, if necessary.
293 [self installAvatar];
295 // Create a sub-controller for the docked devTools and add its view to the
297 devToolsController_.reset([[DevToolsController alloc] init]);
298 [[devToolsController_ view] setFrame:[[self tabContentArea] bounds]];
299 [[self tabContentArea] addSubview:[devToolsController_ view]];
301 // Create the overlayable contents controller. This provides the switch
302 // view that TabStripController needs.
303 overlayableContentsController_.reset(
304 [[OverlayableContentsController alloc] init]);
305 [[overlayableContentsController_ view]
306 setFrame:[[devToolsController_ view] bounds]];
307 [[devToolsController_ view]
308 addSubview:[overlayableContentsController_ view]];
310 // Create a controller for the tab strip, giving it the model object for
311 // this window's Browser and the tab strip view. The controller will handle
312 // registering for the appropriate tab notifications from the back-end and
313 // managing the creation of new tabs.
314 [self createTabStripController];
316 // Create a controller for the toolbar, giving it the toolbar model object
317 // and the toolbar view from the nib. The controller will handle
318 // registering for the appropriate command state changes from the back-end.
319 // Adds the toolbar to the content area.
320 toolbarController_.reset([[ToolbarController alloc]
321 initWithCommands:browser->command_controller()->command_updater()
322 profile:browser->profile()
324 [toolbarController_ setHasToolbar:[self hasToolbar]
325 hasLocationBar:[self hasLocationBar]];
327 // Create a sub-controller for the bookmark bar.
328 bookmarkBarController_.reset(
329 [[BookmarkBarController alloc]
330 initWithBrowser:browser_.get()
331 initialWidth:NSWidth([[[self window] contentView] frame])
333 resizeDelegate:self]);
334 [bookmarkBarController_ setBookmarkBarEnabled:[self supportsBookmarkBar]];
336 // Create the infobar container view, so we can pass it to the
337 // ToolbarController.
338 infoBarContainerController_.reset(
339 [[InfoBarContainerController alloc] initWithResizeDelegate:self]);
340 [self updateInfoBarTipVisibility];
342 // We don't want to try and show the bar before it gets placed in its parent
343 // view, so this step shoudn't be inside the bookmark bar controller's
345 windowShim_->BookmarkBarStateChanged(
346 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
348 // Allow bar visibility to be changed.
349 [self enableBarVisibilityUpdates];
351 // Set the window to participate in Lion Fullscreen mode. Setting this flag
352 // has no effect on Snow Leopard or earlier. Panels can share a fullscreen
353 // space with a tabbed window, but they can not be primary fullscreen
355 // This ensures the fullscreen button is appropriately positioned. It must
356 // be done before calling layoutSubviews because the new avatar button's
357 // position depends on the fullscreen button's position, as well as
358 // TabStripController's rightIndentForControls.
359 // The fullscreen button's position may depend on the old avatar button's
360 // width, but that does not require calling layoutSubviews first.
361 NSUInteger collectionBehavior = [window collectionBehavior];
362 collectionBehavior |=
363 browser_->type() == Browser::TYPE_TABBED ||
364 browser_->type() == Browser::TYPE_POPUP ?
365 NSWindowCollectionBehaviorFullScreenPrimary :
366 NSWindowCollectionBehaviorFullScreenAuxiliary;
367 [window setCollectionBehavior:collectionBehavior];
369 [self layoutSubviews];
371 // For a popup window, |desiredContentRect| contains the desired height of
372 // the content, not of the whole window. Now that all the views are laid
373 // out, measure the current content area size and grow if needed. The
374 // window has not been placed onscreen yet, so this extra resize will not
375 // cause visible jank.
376 if (browser_->is_type_popup()) {
377 CGFloat deltaH = desiredContentRect.height() -
378 NSHeight([[self tabContentArea] frame]);
379 // Do not shrink the window, as that may break minimum size invariants.
381 // Convert from tabContentArea coordinates to window coordinates.
382 NSSize convertedSize =
383 [[self tabContentArea] convertSize:NSMakeSize(0, deltaH)
385 NSRect frame = [[self window] frame];
386 frame.size.height += convertedSize.height;
387 frame.origin.y -= convertedSize.height;
388 [[self window] setFrame:frame display:NO];
392 // Create the bridge for the status bubble.
393 statusBubble_ = new StatusBubbleMac([self window], self);
395 // Register for application hide/unhide notifications.
396 [[NSNotificationCenter defaultCenter]
398 selector:@selector(applicationDidHide:)
399 name:NSApplicationDidHideNotification
401 [[NSNotificationCenter defaultCenter]
403 selector:@selector(applicationDidUnhide:)
404 name:NSApplicationDidUnhideNotification
407 // This must be done after the view is added to the window since it relies
408 // on the window bounds to determine whether to show buttons or not.
409 if ([self hasToolbar]) // Do not create the buttons in popups.
410 [toolbarController_ createBrowserActionButtons];
412 extension_keybinding_registry_.reset(
413 new ExtensionKeybindingRegistryCocoa(browser_->profile(),
415 extensions::ExtensionKeybindingRegistry::ALL_EXTENSIONS,
418 // We are done initializing now.
425 browser_->tab_strip_model()->CloseAllTabs();
427 // Explicitly release |presentationModeController_| here, as it may call back
428 // to this BWC in |-dealloc|. We are required to call |-exitPresentationMode|
429 // before releasing the controller.
430 [presentationModeController_ exitPresentationMode];
431 presentationModeController_.reset();
433 // Under certain testing configurations we may not actually own the browser.
434 if (ownsBrowser_ == NO)
435 ignore_result(browser_.release());
437 [[NSNotificationCenter defaultCenter] removeObserver:self];
439 // Inform reference counted objects that the Browser will be destroyed. This
440 // ensures they invalidate their weak Browser* to prevent use-after-free.
441 // These may outlive the Browser if they are retained by something else. For
442 // example, since 10.10, the Nib loader internally creates an NSDictionary
443 // that retains NSViewControllers and is autoreleased, so there is no way to
444 // guarantee that the [super dealloc] call below will also call dealloc on the
446 [toolbarController_ browserWillBeDestroyed];
447 [tabStripController_ browserWillBeDestroyed];
448 [findBarCocoaController_ browserWillBeDestroyed];
449 [downloadShelfController_ browserWillBeDestroyed];
450 [bookmarkBarController_ browserWillBeDestroyed];
451 [avatarButtonController_ browserWillBeDestroyed];
456 - (gfx::Rect)enforceMinWindowSize:(gfx::Rect)bounds {
457 gfx::Rect checkedBounds = bounds;
459 NSSize minSize = [[self window] minSize];
460 if (bounds.width() < minSize.width)
461 checkedBounds.set_width(minSize.width);
462 if (bounds.height() < minSize.height)
463 checkedBounds.set_height(minSize.height);
465 return checkedBounds;
468 - (BrowserWindow*)browserWindow {
469 return windowShim_.get();
472 - (ToolbarController*)toolbarController {
473 return toolbarController_.get();
476 - (TabStripController*)tabStripController {
477 return tabStripController_.get();
480 - (FindBarCocoaController*)findBarCocoaController {
481 return findBarCocoaController_.get();
484 - (InfoBarContainerController*)infoBarContainerController {
485 return infoBarContainerController_.get();
488 - (StatusBubbleMac*)statusBubble {
489 return statusBubble_;
492 - (LocationBarViewMac*)locationBarBridge {
493 return [toolbarController_ locationBarBridge];
496 - (NSView*)floatingBarBackingView {
497 return floatingBarBackingView_;
500 - (OverlayableContentsController*)overlayableContentsController {
501 return overlayableContentsController_;
504 - (Profile*)profile {
505 return browser_->profile();
508 - (AvatarBaseController*)avatarButtonController {
509 return avatarButtonController_.get();
512 - (void)destroyBrowser {
513 [NSApp removeWindowsItem:[self window]];
515 // We need the window to go away now.
516 // We can't actually use |-autorelease| here because there's an embedded
517 // run loop in the |-performClose:| which contains its own autorelease pool.
518 // Instead call it after a zero-length delay, which gets us back to the main
520 [self performSelector:@selector(autorelease)
525 // Called when the window meets the criteria to be closed (ie,
526 // |-windowShouldClose:| returns YES). We must be careful to preserve the
527 // semantics of BrowserWindow::Close() and not call the Browser's dtor directly
529 - (void)windowWillClose:(NSNotification*)notification {
530 DCHECK_EQ([notification object], [self window]);
531 DCHECK(browser_->tab_strip_model()->empty());
532 [savedRegularWindow_ close];
533 // We delete statusBubble here because we need to kill off the dependency
534 // that its window has on our window before our window goes away.
535 delete statusBubble_;
536 statusBubble_ = NULL;
537 // We can't actually use |-autorelease| here because there's an embedded
538 // run loop in the |-performClose:| which contains its own autorelease pool.
539 // Instead call it after a zero-length delay, which gets us back to the main
541 [self performSelector:@selector(autorelease)
546 - (void)updateDevToolsForContents:(WebContents*)contents {
547 BOOL layout_changed =
548 [devToolsController_ updateDevToolsForWebContents:contents
549 withProfile:browser_->profile()];
550 if (layout_changed && [findBarCocoaController_ isFindBarVisible])
551 [self layoutSubviews];
554 // Called when the user wants to close a window or from the shutdown process.
555 // The Browser object is in control of whether or not we're allowed to close. It
556 // may defer closing due to several states, such as onUnload handlers needing to
557 // be fired. If closing is deferred, the Browser will handle the processing
558 // required to get us to the closing state and (by watching for all the tabs
559 // going away) will again call to close the window when it's finally ready.
560 - (BOOL)windowShouldClose:(id)sender {
561 // Disable updates while closing all tabs to avoid flickering.
562 gfx::ScopedCocoaDisableScreenUpdates disabler;
563 // Give beforeunload handlers the chance to cancel the close before we hide
565 if (!browser_->ShouldCloseWindow())
568 // saveWindowPositionIfNeeded: only works if we are the last active
569 // window, but orderOut: ends up activating another window, so we
570 // have to save the window position before we call orderOut:.
571 [self saveWindowPositionIfNeeded];
573 bool fast_tab_closing_enabled =
574 base::CommandLine::ForCurrentProcess()->HasSwitch(
575 switches::kEnableFastUnload);
577 if (!browser_->tab_strip_model()->empty()) {
578 // Tab strip isn't empty. Hide the frame (so it appears to have closed
579 // immediately) and close all the tabs, allowing the renderers to shut
580 // down. When the tab strip is empty we'll be called back again.
581 [[self window] orderOut:self];
582 browser_->OnWindowClosing();
583 if (fast_tab_closing_enabled)
584 browser_->tab_strip_model()->CloseAllTabs();
586 } else if (fast_tab_closing_enabled &&
587 !browser_->HasCompletedUnloadProcessing()) {
588 // The browser needs to finish running unload handlers.
589 // Hide the window (so it appears to have closed immediately), and
590 // the browser will call us back again when it is ready to close.
591 [[self window] orderOut:self];
595 // the tab strip is empty, it's ok to close the window
599 // Called right after our window became the main window.
600 - (void)windowDidBecomeMain:(NSNotification*)notification {
601 if (chrome::GetLastActiveBrowser() != browser_) {
602 BrowserList::SetLastActive(browser_.get());
603 [self saveWindowPositionIfNeeded];
606 [[[self window] contentView] cr_recursivelyInvokeBlock:^(id view) {
607 if ([view conformsToProtocol:@protocol(ThemedWindowDrawing)])
608 [view windowDidChangeActive];
611 extensions::ExtensionCommandsGlobalRegistry::Get(browser_->profile())
612 ->set_registry_for_active_window(extension_keybinding_registry_.get());
615 - (void)windowDidResignMain:(NSNotification*)notification {
616 [[[self window] contentView] cr_recursivelyInvokeBlock:^(id view) {
617 if ([view conformsToProtocol:@protocol(ThemedWindowDrawing)])
618 [view windowDidChangeActive];
621 extensions::ExtensionCommandsGlobalRegistry::Get(browser_->profile())
622 ->set_registry_for_active_window(nullptr);
625 // Called when we are activated (when we gain focus).
626 - (void)windowDidBecomeKey:(NSNotification*)notification {
627 // We need to activate the controls (in the "WebView"). To do this, get the
628 // selected WebContents's RenderWidgetHostView and tell it to activate.
629 if (WebContents* contents = [self webContents]) {
630 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
633 RenderWidgetHostView* devtoolsView = devtools->GetRenderWidgetHostView();
634 if (devtoolsView && devtoolsView->HasFocus()) {
635 devtoolsView->SetActive(true);
640 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
641 rwhv->SetActive(true);
645 // Called when we are deactivated (when we lose focus).
646 - (void)windowDidResignKey:(NSNotification*)notification {
647 // If our app is still active and we're still the key window, ignore this
648 // message, since it just means that a menu extra (on the "system status bar")
649 // was activated; we'll get another |-windowDidResignKey| if we ever really
650 // lose key window status.
651 if ([NSApp isActive] && ([NSApp keyWindow] == [self window]))
654 // We need to deactivate the controls (in the "WebView"). To do this, get the
655 // selected WebContents's RenderWidgetHostView and tell it to deactivate.
656 if (WebContents* contents = [self webContents]) {
657 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
660 RenderWidgetHostView* devtoolsView = devtools->GetRenderWidgetHostView();
661 if (devtoolsView && devtoolsView->HasFocus()) {
662 devtoolsView->SetActive(false);
667 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
668 rwhv->SetActive(false);
672 // Called when we have been minimized.
673 - (void)windowDidMiniaturize:(NSNotification *)notification {
674 [self saveWindowPositionIfNeeded];
676 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
677 if (WebContents* contents = [self webContents]) {
678 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
679 rwhv->SetWindowVisibility(false);
683 // Called when we have been unminimized.
684 - (void)windowDidDeminiaturize:(NSNotification *)notification {
685 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
686 if (WebContents* contents = [self webContents]) {
687 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
688 rwhv->SetWindowVisibility(true);
692 // Called when the application has been hidden.
693 - (void)applicationDidHide:(NSNotification *)notification {
694 // Let the selected RenderWidgetHostView know, so that it can tell plugins
695 // (unless we are minimized, in which case nothing has really changed).
696 if (![[self window] isMiniaturized]) {
697 if (WebContents* contents = [self webContents]) {
698 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
699 rwhv->SetWindowVisibility(false);
704 // Called when the application has been unhidden.
705 - (void)applicationDidUnhide:(NSNotification *)notification {
706 // Let the selected RenderWidgetHostView know, so that it can tell plugins
707 // (unless we are minimized, in which case nothing has really changed).
708 if (![[self window] isMiniaturized]) {
709 if (WebContents* contents = [self webContents]) {
710 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
711 rwhv->SetWindowVisibility(true);
716 // Called when the user clicks the zoom button (or selects it from the Window
717 // menu) to determine the "standard size" of the window, based on the content
718 // and other factors. If the current size/location differs nontrivally from the
719 // standard size, Cocoa resizes the window to the standard size, and saves the
720 // current size as the "user size". If the current size/location is the same (up
721 // to a fudge factor) as the standard size, Cocoa resizes the window to the
722 // saved user size. (It is possible for the two to coincide.) In this way, the
723 // zoom button acts as a toggle. We determine the standard size based on the
724 // content, but enforce a minimum width (calculated using the dimensions of the
725 // screen) to ensure websites with small intrinsic width (such as google.com)
726 // don't end up with a wee window. Moreover, we always declare the standard
727 // width to be at least as big as the current width, i.e., we never want zooming
728 // to the standard width to shrink the window. This is consistent with other
729 // browsers' behaviour, and is desirable in multi-tab situations. Note, however,
730 // that the "toggle" behaviour means that the window can still be "unzoomed" to
732 // Note: this method is also called from -isZoomed. If the returned zoomed rect
733 // equals the current window's frame, -isZoomed returns YES.
734 - (NSRect)windowWillUseStandardFrame:(NSWindow*)window
735 defaultFrame:(NSRect)frame {
736 // Forget that we grew the window up (if we in fact did).
737 [self resetWindowGrowthState];
739 // |frame| already fills the current screen. Never touch y and height since we
740 // always want to fill vertically.
742 // If the shift key is down, maximize. Hopefully this should make the
743 // "switchers" happy.
744 if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask) {
748 // To prevent strange results on portrait displays, the basic minimum zoomed
749 // width is the larger of: 60% of available width, 60% of available height
750 // (bounded by available width).
751 const CGFloat kProportion = 0.6;
752 CGFloat zoomedWidth =
753 std::max(kProportion * NSWidth(frame),
754 std::min(kProportion * NSHeight(frame), NSWidth(frame)));
756 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
758 // If the intrinsic width is bigger, then make it the zoomed width.
759 const int kScrollbarWidth = 16; // TODO(viettrungluu): ugh.
760 CGFloat intrinsicWidth = static_cast<CGFloat>(
761 contents->GetPreferredSize().width() + kScrollbarWidth);
762 zoomedWidth = std::max(zoomedWidth,
763 std::min(intrinsicWidth, NSWidth(frame)));
766 // Never shrink from the current size on zoom (see above).
767 NSRect currentFrame = [[self window] frame];
768 zoomedWidth = std::max(zoomedWidth, NSWidth(currentFrame));
770 // |frame| determines our maximum extents. We need to set the origin of the
771 // frame -- and only move it left if necessary.
772 if (currentFrame.origin.x + zoomedWidth > NSMaxX(frame))
773 frame.origin.x = NSMaxX(frame) - zoomedWidth;
775 frame.origin.x = currentFrame.origin.x;
777 // Set the width. Don't touch y or height.
778 frame.size.width = zoomedWidth;
784 [BrowserWindowUtils activateWindowForController:self];
787 // Determine whether we should let a window zoom/unzoom to the given |newFrame|.
788 // We avoid letting unzoom move windows between screens, because it's really
789 // strange and unintuitive.
790 - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame {
791 // Figure out which screen |newFrame| is on.
792 NSScreen* newScreen = nil;
793 CGFloat newScreenOverlapArea = 0.0;
794 for (NSScreen* screen in [NSScreen screens]) {
795 NSRect overlap = NSIntersectionRect(newFrame, [screen frame]);
796 CGFloat overlapArea = NSWidth(overlap) * NSHeight(overlap);
797 if (overlapArea > newScreenOverlapArea) {
799 newScreenOverlapArea = overlapArea;
802 // If we're somehow not on any screen, allow the zoom.
806 // If the new screen is the current screen, we can return a definitive YES.
807 // Note: This check is not strictly necessary, but just short-circuits in the
808 // "no-brainer" case. To test the complicated logic below, comment this out!
809 NSScreen* curScreen = [window screen];
810 if (newScreen == curScreen)
813 // Worry a little: What happens when a window is on two (or more) screens?
814 // E.g., what happens in a 50-50 scenario? Cocoa may reasonably elect to zoom
815 // to the other screen rather than staying on the officially current one. So
816 // we compare overlaps with the current window frame, and see if Cocoa's
817 // choice was reasonable (allowing a small rounding error). This should
818 // hopefully avoid us ever erroneously denying a zoom when a window is on
820 NSRect curFrame = [window frame];
821 NSRect newScrIntersectCurFr = NSIntersectionRect([newScreen frame], curFrame);
822 NSRect curScrIntersectCurFr = NSIntersectionRect([curScreen frame], curFrame);
823 if (NSWidth(newScrIntersectCurFr) * NSHeight(newScrIntersectCurFr) >=
824 (NSWidth(curScrIntersectCurFr) * NSHeight(curScrIntersectCurFr) - 1.0)) {
828 // If it wasn't reasonable, return NO.
832 // Adjusts the window height by the given amount.
833 - (BOOL)adjustWindowHeightBy:(CGFloat)deltaH {
834 // By not adjusting the window height when initializing, we can ensure that
835 // the window opens with the same size that was saved on close.
836 if (initializing_ || [self isInAnyFullscreenMode] || deltaH == 0)
839 NSWindow* window = [self window];
840 NSRect windowFrame = [window frame];
841 NSRect workarea = [[window screen] visibleFrame];
843 // Prevent the window from growing smaller than its minimum height:
844 // http://crbug.com/230400 .
846 CGFloat minWindowHeight = [window minSize].height;
847 if (windowFrame.size.height + deltaH < minWindowHeight) {
848 // |deltaH| + |windowFrame.size.height| = |minWindowHeight|.
849 deltaH = minWindowHeight - windowFrame.size.height;
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* chromeContentView = [self chromeContentView];
946 BOOL autoresizesSubviews = [chromeContentView autoresizesSubviews];
947 [chromeContentView setAutoresizesSubviews:NO];
949 // On Yosemite the toolbar can flicker when hiding or showing the bookmarks
950 // bar. Here, |chromeContentView| is set to not autoresize its subviews during
951 // the window resize. Because |chromeContentView| is not flipped, if the
952 // window is getting shorter, the toolbar will move up within the window.
953 // Soon after, a call to layoutSubviews corrects its position. Passing NO to
954 // setFrame:display: should keep the toolbarView's intermediate position
955 // hidden, as should the prior call to disable screen updates. For some
956 // reason, neither prevents the toolbarView's intermediate position from
957 // becoming visible. Its subsequent appearance in its correct location causes
958 // the flicker. It may be that the Appkit assumes that updating the window
959 // immediately is not a big deal given that everything in it is layer-backed.
960 // Indeed, turning off layer backing for all ancestors of the toolbarView
961 // causes the flicker to go away.
963 // By shifting the toolbarView enough so that it's in its correct location
964 // immediately after the call to setFrame:display:, the toolbar will be in
965 // the right spot when the Appkit prematurely flushes the window contents to
966 // the screen. http://crbug.com/444080 .
967 if ([self hasToolbar]) {
968 NSView* toolbarView = [toolbarController_ view];
969 NSRect currentWindowFrame = [window frame];
970 NSRect toolbarViewFrame = [toolbarView frame];
971 toolbarViewFrame.origin.y += windowFrame.size.height -
972 currentWindowFrame.size.height;
973 [toolbarView setFrame:toolbarViewFrame];
976 [window setFrame:windowFrame display:NO];
977 [chromeContentView setAutoresizesSubviews:autoresizesSubviews];
981 // Main method to resize browser window subviews. This method should be called
982 // when resizing any child of the content view, rather than resizing the views
983 // directly. If the view is already the correct height, does not force a
985 - (void)resizeView:(NSView*)view newHeight:(CGFloat)height {
986 // We should only ever be called for one of the following four views.
987 // |downloadShelfController_| may be nil. If we are asked to size the bookmark
988 // bar directly, its superview must be this controller's content view.
990 DCHECK(view == [toolbarController_ view] ||
991 view == [infoBarContainerController_ view] ||
992 view == [downloadShelfController_ view] ||
993 view == [bookmarkBarController_ view]);
995 // The infobar has insufficient information to determine its new height. It
996 // knows the total height of all of the info bars (which is what it passes
997 // into this method), but knows nothing about the maximum arrow height, which
998 // is determined by this class.
999 if (view == [infoBarContainerController_ view]) {
1000 base::scoped_nsobject<BrowserWindowLayout> layout(
1001 [[BrowserWindowLayout alloc] init]);
1002 [self updateLayoutParameters:layout];
1003 // Use the new height for the info bar.
1004 [layout setInfoBarHeight:height];
1006 chrome::LayoutOutput output = [layout computeLayout];
1008 height = NSHeight(output.infoBarFrame);
1011 // Change the height of the view and call |-layoutSubViews|. We set the height
1012 // here without regard to where the view is on the screen or whether it needs
1013 // to "grow up" or "grow down." The below call to |-layoutSubviews| will
1014 // position each view correctly.
1015 NSRect frame = [view frame];
1016 if (NSHeight(frame) == height)
1019 // Disable screen updates to prevent flickering.
1020 gfx::ScopedCocoaDisableScreenUpdates disabler;
1022 // Grow or shrink the window by the amount of the height change. We adjust
1023 // the window height only in two cases:
1024 // 1) We are adjusting the height of the bookmark bar and it is currently
1025 // animating either open or closed.
1026 // 2) We are adjusting the height of the download shelf.
1028 // We do not adjust the window height for bookmark bar changes on the NTP.
1029 BOOL shouldAdjustBookmarkHeight =
1030 [bookmarkBarController_ isAnimatingBetweenState:BookmarkBar::HIDDEN
1031 andState:BookmarkBar::SHOW];
1033 BOOL resizeRectDirty = NO;
1034 if ((shouldAdjustBookmarkHeight && view == [bookmarkBarController_ view]) ||
1035 view == [downloadShelfController_ view]) {
1036 CGFloat deltaH = height - NSHeight(frame);
1037 if ([self adjustWindowHeightBy:deltaH] &&
1038 view == [downloadShelfController_ view]) {
1039 // If the window height didn't change, the download shelf will change the
1040 // size of the contents. If the contents size doesn't change, send it
1041 // an explicit grow box invalidation (else, the resize message does that.)
1042 resizeRectDirty = YES;
1046 frame.size.height = height;
1047 // TODO(rohitrao): Determine if calling setFrame: twice is bad.
1048 [view setFrame:frame];
1049 [self layoutSubviews];
1051 if (resizeRectDirty) {
1052 // Send new resize rect to foreground tab.
1053 if (WebContents* contents = [self webContents]) {
1054 if (content::RenderViewHost* rvh = contents->GetRenderViewHost()) {
1055 rvh->ResizeRectChanged(windowShim_->GetRootWindowResizerRect());
1061 // Update a toggle state for an NSMenuItem if modified.
1062 // Take care to ensure |item| looks like a NSMenuItem.
1063 // Called by validateUserInterfaceItem:.
1064 - (void)updateToggleStateWithTag:(NSInteger)tag forItem:(id)item {
1065 if (![item respondsToSelector:@selector(state)] ||
1066 ![item respondsToSelector:@selector(setState:)])
1069 // On Windows this logic happens in bookmark_bar_view.cc. On the
1070 // Mac we're a lot more MVC happy so we've moved it into a
1071 // controller. To be clear, this simply updates the menu item; it
1072 // does not display the bookmark bar itself.
1073 if (tag == IDC_SHOW_BOOKMARK_BAR) {
1074 bool toggled = windowShim_->IsBookmarkBarVisible();
1075 NSInteger oldState = [(NSMenuItem*)item state];
1076 NSInteger newState = toggled ? NSOnState : NSOffState;
1077 if (oldState != newState)
1078 [item setState:newState];
1081 // Update the checked/Unchecked state of items in the encoding menu.
1082 // On Windows, this logic is part of |EncodingMenuModel| in
1083 // browser/ui/views/toolbar_view.h.
1084 EncodingMenuController encoding_controller;
1085 if (encoding_controller.DoesCommandBelongToEncodingMenu(tag)) {
1086 DCHECK(browser_.get());
1087 Profile* profile = browser_->profile();
1089 WebContents* current_tab =
1090 browser_->tab_strip_model()->GetActiveWebContents();
1094 const std::string encoding = current_tab->GetEncoding();
1096 bool toggled = encoding_controller.IsItemChecked(profile, encoding, tag);
1097 NSInteger oldState = [(NSMenuItem*)item state];
1098 NSInteger newState = toggled ? NSOnState : NSOffState;
1099 if (oldState != newState)
1100 [item setState:newState];
1104 // Called to validate menu and toolbar items when this window is key. All the
1105 // items we care about have been set with the |-commandDispatch:| or
1106 // |-commandDispatchUsingKeyModifiers:| actions and a target of FirstResponder
1107 // in IB. If it's not one of those, let it continue up the responder chain to be
1108 // handled elsewhere. We pull out the tag as the cross-platform constant to
1109 // differentiate and dispatch the various commands.
1110 // NOTE: we might have to handle state for app-wide menu items,
1111 // although we could cheat and directly ask the app controller if our
1112 // command_updater doesn't support the command. This may or may not be an issue,
1113 // too early to tell.
1114 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
1115 SEL action = [item action];
1117 if (action == @selector(commandDispatch:) ||
1118 action == @selector(commandDispatchUsingKeyModifiers:)) {
1119 NSInteger tag = [item tag];
1120 if (chrome::SupportsCommand(browser_.get(), tag)) {
1121 // Generate return value (enabled state)
1122 enable = chrome::IsCommandEnabled(browser_.get(), tag);
1125 // Disable "close tab" if the receiving window is not tabbed.
1126 // We simply check whether the item has a keyboard shortcut set here;
1127 // app_controller_mac.mm actually determines whether the item should
1129 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item))
1130 enable &= !![[menuItem keyEquivalent] length];
1132 case IDC_FULLSCREEN: {
1133 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item)) {
1134 if (chrome::mac::SupportsSystemFullscreen()) {
1135 [menuItem setTitle:[self titleForFullscreenMenuItem]];
1137 [menuItem setHidden:YES];
1142 case IDC_PRESENTATION_MODE: {
1143 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item)) {
1144 [menuItem setTitle:[self titleForFullscreenMenuItem]];
1146 if (chrome::mac::SupportsSystemFullscreen())
1147 [menuItem setAlternate:YES];
1151 case IDC_BOOKMARK_PAGE: {
1152 // Extensions have the ability to hide the bookmark page menu item.
1153 // This only affects the bookmark page menu item under the main menu.
1154 // The bookmark page menu item under the wrench menu has its
1155 // visibility controlled by WrenchMenuModel.
1157 chrome::ShouldRemoveBookmarkThisPageUI(browser_->profile());
1158 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
1159 [menuItem setHidden:shouldHide];
1162 case IDC_BOOKMARK_ALL_TABS: {
1163 // Extensions have the ability to hide the bookmark all tabs menu
1164 // item. This only affects the bookmark page menu item under the main
1165 // menu. The bookmark page menu item under the wrench menu has its
1166 // visibility controlled by WrenchMenuModel.
1168 chrome::ShouldRemoveBookmarkOpenPagesUI(browser_->profile());
1169 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
1170 [menuItem setHidden:shouldHide];
1174 // Special handling for the contents of the Text Encoding submenu. On
1175 // Mac OS, instead of enabling/disabling the top-level menu item, we
1176 // enable/disable the submenu's contents (per Apple's HIG).
1177 EncodingMenuController encoding_controller;
1178 if (encoding_controller.DoesCommandBelongToEncodingMenu(tag)) {
1179 enable &= chrome::IsCommandEnabled(browser_.get(),
1180 IDC_ENCODING_MENU) ? YES : NO;
1184 // If the item is toggleable, find its toggle state and
1185 // try to update it. This is a little awkward, but the alternative is
1186 // to check after a commandDispatch, which seems worse.
1187 [self updateToggleStateWithTag:tag forItem:item];
1193 // Called when the user picks a menu or toolbar item when this window is key.
1194 // Calls through to the browser object to execute the command. This assumes that
1195 // the command is supported and doesn't check, otherwise it would have been
1196 // disabled in the UI in validateUserInterfaceItem:.
1197 - (void)commandDispatch:(id)sender {
1199 // Identify the actual BWC to which the command should be dispatched. It might
1200 // belong to a background window, yet this controller gets it because it is
1201 // the foreground window's controller and thus in the responder chain. Some
1202 // senders don't have this problem (for example, menus only operate on the
1203 // foreground window), so this is only an issue for senders that are part of
1205 BrowserWindowController* targetController = self;
1206 if ([sender respondsToSelector:@selector(window)])
1207 targetController = [[sender window] windowController];
1208 DCHECK([targetController isKindOfClass:[BrowserWindowController class]]);
1209 DCHECK(targetController->browser_.get());
1211 // When system fullscreen is available, it supercedes presentation mode.
1212 int tag = [sender tag];
1213 if (tag == IDC_PRESENTATION_MODE && chrome::mac::SupportsSystemFullscreen())
1214 tag = IDC_FULLSCREEN;
1216 chrome::ExecuteCommand(targetController->browser_.get(), tag);
1219 // Same as |-commandDispatch:|, but executes commands using a disposition
1220 // determined by the key flags. If the window is in the background and the
1221 // command key is down, ignore the command key, but process any other modifiers.
1222 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1225 if (![sender isEnabled]) {
1226 // This code is reachable e.g. if the user mashes the back button, queuing
1227 // up a bunch of events before the button's enabled state is updated:
1228 // http://crbug.com/63254
1232 // See comment above for why we do this.
1233 BrowserWindowController* targetController = self;
1234 if ([sender respondsToSelector:@selector(window)])
1235 targetController = [[sender window] windowController];
1236 DCHECK([targetController isKindOfClass:[BrowserWindowController class]]);
1237 DCHECK(targetController->browser_.get());
1239 NSInteger command = [sender tag];
1240 NSUInteger modifierFlags = [[NSApp currentEvent] modifierFlags];
1241 if ((command == IDC_RELOAD) &&
1242 (modifierFlags & (NSShiftKeyMask | NSControlKeyMask))) {
1243 command = IDC_RELOAD_IGNORING_CACHE;
1244 // Mask off Shift and Control so they don't affect the disposition below.
1245 modifierFlags &= ~(NSShiftKeyMask | NSControlKeyMask);
1247 if (![[sender window] isMainWindow]) {
1248 // Remove the command key from the flags, it means "keep the window in
1249 // the background" in this case.
1250 modifierFlags &= ~NSCommandKeyMask;
1252 chrome::ExecuteCommandWithDisposition(
1253 targetController->browser_.get(), command,
1254 ui::WindowOpenDispositionFromNSEventWithFlags(
1255 [NSApp currentEvent], modifierFlags));
1258 - (BOOL)handledByExtensionCommand:(NSEvent*)event
1259 priority:(ui::AcceleratorManager::HandlerPriority)priority {
1260 return extension_keybinding_registry_->ProcessKeyEvent(
1261 content::NativeWebKeyboardEvent(event), priority);
1264 // StatusBubble delegate method: tell the status bubble the frame it should
1265 // position itself in.
1266 - (NSRect)statusBubbleBaseFrame {
1267 NSView* view = [overlayableContentsController_ view];
1268 return [view convertRect:[view bounds] toView:nil];
1271 - (void)updateToolbarWithContents:(WebContents*)tab {
1272 [toolbarController_ updateToolbarWithContents:tab];
1275 - (void)resetTabState:(WebContents*)tab {
1276 [toolbarController_ resetTabState:tab];
1279 - (void)setStarredState:(BOOL)isStarred {
1280 [toolbarController_ setStarredState:isStarred];
1283 - (void)setCurrentPageIsTranslated:(BOOL)on {
1284 [toolbarController_ setTranslateIconLit:on];
1287 - (void)onActiveTabChanged:(content::WebContents*)oldContents
1288 to:(content::WebContents*)newContents {
1289 // No need to remove previous bubble. It will close itself.
1290 PermissionBubbleManager* manager(nullptr);
1292 manager = PermissionBubbleManager::FromWebContents(oldContents);
1294 manager->HideBubble();
1298 manager = PermissionBubbleManager::FromWebContents(newContents);
1300 manager->DisplayPendingRequests(browser_.get());
1304 - (void)zoomChangedForActiveTab:(BOOL)canShowBubble {
1305 [toolbarController_ zoomChangedForActiveTab:canShowBubble];
1308 // Return the rect, in WebKit coordinates (flipped), of the window's grow box
1309 // in the coordinate system of the content area of the currently selected tab.
1310 // |windowGrowBox| needs to be in the window's coordinate system.
1311 - (NSRect)selectedTabGrowBoxRect {
1312 NSWindow* window = [self window];
1313 if (![window respondsToSelector:@selector(_growBoxRect)])
1316 // Before we return a rect, we need to convert it from window coordinates
1317 // to tab content area coordinates and flip the coordinate system.
1318 NSRect growBoxRect =
1319 [[self tabContentArea] convertRect:[window _growBoxRect] fromView:nil];
1320 growBoxRect.origin.y =
1321 NSHeight([[self tabContentArea] frame]) - NSMaxY(growBoxRect);
1325 // Accept tabs from a BrowserWindowController with the same Profile.
1326 - (BOOL)canReceiveFrom:(TabWindowController*)source {
1327 BrowserWindowController* realSource =
1328 base::mac::ObjCCast<BrowserWindowController>(source);
1329 if (!realSource || browser_->profile() != realSource->browser_->profile()) {
1333 // Can't drag a tab from a normal browser to a pop-up
1334 if (browser_->type() != realSource->browser_->type()) {
1341 // Move a given tab view to the location of the current placeholder. If there is
1342 // no placeholder, it will go at the end. |controller| is the window controller
1343 // of a tab being dropped from a different window. It will be nil if the drag is
1344 // within the window, otherwise the tab is removed from that window before being
1345 // placed into this one. The implementation will call |-removePlaceholder| since
1346 // the drag is now complete. This also calls |-layoutTabs| internally so
1347 // clients do not need to call it again.
1348 - (void)moveTabViews:(NSArray*)views
1349 fromController:(TabWindowController*)dragController {
1350 if (dragController) {
1351 // Moving between windows.
1352 NSView* activeTabView = [dragController activeTabView];
1353 BrowserWindowController* dragBWC =
1354 base::mac::ObjCCastStrict<BrowserWindowController>(dragController);
1356 // We will drop the tabs starting at indexOfPlaceholder, and increment from
1357 // there. We remove the placehoder before dropping the tabs, so that the
1358 // new tab animation's destination frame is correct.
1359 int tabIndex = [tabStripController_ indexOfPlaceholder];
1360 [self removePlaceholder];
1362 for (NSView* view in views) {
1363 // Figure out the WebContents to drop into our tab model from the source
1365 int index = [dragBWC->tabStripController_ modelIndexForTabView:view];
1366 WebContents* contents =
1367 dragBWC->browser_->tab_strip_model()->GetWebContentsAt(index);
1368 // The tab contents may have gone away if given a window.close() while it
1369 // is being dragged. If so, bail, we've got nothing to drop.
1373 // Convert |view|'s frame (which starts in the source tab strip's
1374 // coordinate system) to the coordinate system of the destination tab
1375 // strip. This needs to be done before being detached so the window
1376 // transforms can be performed.
1377 NSRect destinationFrame = [view frame];
1378 NSPoint tabOrigin = destinationFrame.origin;
1379 tabOrigin = [[dragController tabStripView] convertPoint:tabOrigin
1381 tabOrigin = [[dragController window] convertBaseToScreen:tabOrigin];
1382 tabOrigin = [[self window] convertScreenToBase:tabOrigin];
1383 tabOrigin = [[self tabStripView] convertPoint:tabOrigin fromView:nil];
1384 destinationFrame.origin = tabOrigin;
1386 // Before the tab is detached from its originating tab strip, store the
1387 // pinned state so that it can be maintained between the windows.
1388 bool isPinned = dragBWC->browser_->tab_strip_model()->IsTabPinned(index);
1390 // Now that we have enough information about the tab, we can remove it
1391 // from the dragging window. We need to do this *before* we add it to the
1392 // new window as this will remove the WebContents' delegate.
1393 [dragController detachTabView:view];
1395 // Deposit it into our model at the appropriate location (it already knows
1396 // where it should go from tracking the drag). Doing this sets the tab's
1397 // delegate to be the Browser.
1398 [tabStripController_ dropWebContents:contents
1400 withFrame:destinationFrame
1401 asPinnedTab:isPinned
1402 activate:view == activeTabView];
1405 // Moving within a window.
1406 for (NSView* view in views) {
1407 int index = [tabStripController_ modelIndexForTabView:view];
1408 [tabStripController_ moveTabFromIndex:index];
1410 [self removePlaceholder];
1414 // Tells the tab strip to forget about this tab in preparation for it being
1415 // put into a different tab strip, such as during a drop on another window.
1416 - (void)detachTabView:(NSView*)view {
1417 int index = [tabStripController_ modelIndexForTabView:view];
1418 browser_->tab_strip_model()->DetachWebContentsAt(index);
1421 - (NSArray*)tabViews {
1422 return [tabStripController_ tabViews];
1425 - (NSView*)activeTabView {
1426 return [tabStripController_ activeTabView];
1429 - (void)setIsLoading:(BOOL)isLoading force:(BOOL)force {
1430 [toolbarController_ setIsLoading:isLoading force:force];
1433 // Make the location bar the first responder, if possible.
1434 - (void)focusLocationBar:(BOOL)selectAll {
1435 [toolbarController_ focusLocationBar:selectAll];
1438 - (void)focusTabContents {
1439 content::WebContents* const activeWebContents =
1440 browser_->tab_strip_model()->GetActiveWebContents();
1441 if (activeWebContents)
1442 activeWebContents->Focus();
1445 - (void)layoutTabs {
1446 [tabStripController_ layoutTabs];
1449 - (TabWindowController*)detachTabsToNewWindow:(NSArray*)tabViews
1450 draggedTab:(NSView*)draggedTab {
1451 DCHECK_GT([tabViews count], 0U);
1453 // Disable screen updates so that this appears as a single visual change.
1454 gfx::ScopedCocoaDisableScreenUpdates disabler;
1456 // Set the window size. Need to do this before we detach the tab so it's
1457 // still in the window. We have to flip the coordinates as that's what
1458 // is expected by the Browser code.
1459 NSWindow* sourceWindow = [draggedTab window];
1460 NSRect windowRect = [sourceWindow frame];
1461 NSScreen* screen = [sourceWindow screen];
1462 windowRect.origin.y = NSHeight([screen frame]) - NSMaxY(windowRect);
1463 gfx::Rect browserRect(windowRect.origin.x, windowRect.origin.y,
1464 NSWidth(windowRect), NSHeight(windowRect));
1466 std::vector<TabStripModelDelegate::NewStripContents> contentses;
1467 TabStripModel* model = browser_->tab_strip_model();
1469 for (TabView* tabView in tabViews) {
1470 // Fetch the tab contents for the tab being dragged.
1471 int index = [tabStripController_ modelIndexForTabView:tabView];
1472 bool isPinned = model->IsTabPinned(index);
1473 bool isActive = (index == model->active_index());
1475 TabStripModelDelegate::NewStripContents item;
1476 item.web_contents = model->GetWebContentsAt(index);
1478 (isActive ? TabStripModel::ADD_ACTIVE : TabStripModel::ADD_NONE) |
1479 (isPinned ? TabStripModel::ADD_PINNED : TabStripModel::ADD_NONE);
1480 contentses.push_back(item);
1483 for (TabView* tabView in tabViews) {
1484 int index = [tabStripController_ modelIndexForTabView:tabView];
1485 // Detach it from the source window, which just updates the model without
1486 // deleting the tab contents. This needs to come before creating the new
1487 // Browser because it clears the WebContents' delegate, which gets hooked
1488 // up during creation of the new window.
1489 model->DetachWebContentsAt(index);
1492 // Create a new window with the dragged tabs in its model.
1493 Browser* newBrowser = browser_->tab_strip_model()->delegate()->
1494 CreateNewStripWithContents(contentses, browserRect, false);
1496 // Get the new controller by asking the new window for its delegate.
1497 BrowserWindowController* controller =
1498 reinterpret_cast<BrowserWindowController*>(
1499 [newBrowser->window()->GetNativeWindow() delegate]);
1500 DCHECK(controller && [controller isKindOfClass:[TabWindowController class]]);
1502 // And make sure we use the correct frame in the new view.
1503 TabStripController* tabStripController = [controller tabStripController];
1504 NSView* tabStrip = [self tabStripView];
1505 NSEnumerator* tabEnumerator = [tabViews objectEnumerator];
1506 for (NSView* newView in [tabStripController tabViews]) {
1507 NSView* oldView = [tabEnumerator nextObject];
1509 // Pushes tabView's frame back inside the tabstrip.
1510 NSRect sourceTabRect = [oldView frame];
1511 NSSize tabOverflow =
1512 [self overflowFrom:[tabStrip convertRect:sourceTabRect toView:nil]
1513 to:[tabStrip frame]];
1515 NSOffsetRect(sourceTabRect, -tabOverflow.width, -tabOverflow.height);
1516 // Force the added tab to the right size (remove stretching.)
1517 tabRect.size.height = [TabStripController defaultTabHeight];
1519 [tabStripController setFrame:tabRect ofTabView:newView];
1526 - (void)insertPlaceholderForTab:(TabView*)tab
1527 frame:(NSRect)frame {
1528 [super insertPlaceholderForTab:tab frame:frame];
1529 [tabStripController_ insertPlaceholderForTab:tab frame:frame];
1532 - (void)removePlaceholder {
1533 [super removePlaceholder];
1534 [tabStripController_ insertPlaceholderForTab:nil frame:NSZeroRect];
1537 - (BOOL)isDragSessionActive {
1538 // The tab can be dragged within the existing tab strip or detached
1539 // into its own window (then the overlay window will be present).
1540 return [[self tabStripController] isDragSessionActive] ||
1541 [self overlayWindow] != nil;
1544 - (BOOL)tabDraggingAllowed {
1545 return [tabStripController_ tabDraggingAllowed];
1548 - (BOOL)tabTearingAllowed {
1549 return ![self isInAnyFullscreenMode];
1552 - (BOOL)windowMovementAllowed {
1553 return ![self isInAnyFullscreenMode];
1556 - (BOOL)isTabFullyVisible:(TabView*)tab {
1557 return [tabStripController_ isTabFullyVisible:tab];
1560 - (void)showNewTabButton:(BOOL)show {
1561 [tabStripController_ showNewTabButton:show];
1564 - (BOOL)shouldShowAvatar {
1565 if (![self hasTabStrip])
1567 if (browser_->profile()->IsOffTheRecord())
1570 ProfileInfoCache& cache =
1571 g_browser_process->profile_manager()->GetProfileInfoCache();
1572 if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) ==
1573 std::string::npos) {
1577 return AvatarMenu::ShouldShowAvatarMenu();
1580 - (BOOL)shouldUseNewAvatarButton {
1581 return switches::IsNewAvatarMenu() &&
1582 profiles::IsRegularOrGuestSession(browser_.get());
1585 - (BOOL)isBookmarkBarVisible {
1586 return [bookmarkBarController_ isVisible];
1589 - (BOOL)isBookmarkBarAnimating {
1590 return [bookmarkBarController_ isAnimationRunning];
1593 - (BookmarkBarController*)bookmarkBarController {
1594 return bookmarkBarController_;
1597 - (DevToolsController*)devToolsController {
1598 return devToolsController_;
1601 - (BOOL)isDownloadShelfVisible {
1602 return downloadShelfController_ != nil &&
1603 [downloadShelfController_ isVisible];
1606 - (void)createAndAddDownloadShelf {
1607 if (!downloadShelfController_.get()) {
1608 downloadShelfController_.reset([[DownloadShelfController alloc]
1609 initWithBrowser:browser_.get() resizeDelegate:self]);
1610 [self.chromeContentView addSubview:[downloadShelfController_ view]];
1614 - (DownloadShelfController*)downloadShelf {
1615 return downloadShelfController_;
1618 - (void)addFindBar:(FindBarCocoaController*)findBarCocoaController {
1619 // Shouldn't call addFindBar twice.
1620 DCHECK(!findBarCocoaController_.get());
1622 // Create a controller for the findbar.
1623 findBarCocoaController_.reset([findBarCocoaController retain]);
1624 [self layoutSubviews];
1625 [self updateSubviewZOrder];
1628 - (NSWindow*)createFullscreenWindow {
1629 return [[[FullscreenWindow alloc] initForScreen:[[self window] screen]]
1633 - (NSInteger)numberOfTabs {
1634 // count() includes pinned tabs.
1635 return browser_->tab_strip_model()->count();
1638 - (BOOL)hasLiveTabs {
1639 return !browser_->tab_strip_model()->empty();
1642 - (NSString*)activeTabTitle {
1643 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1644 return base::SysUTF16ToNSString(contents->GetTitle());
1647 - (NSRect)regularWindowFrame {
1648 return [self isInAnyFullscreenMode] ? savedRegularWindowFrame_
1649 : [[self window] frame];
1652 // (Override of |TabWindowController| method.)
1653 - (BOOL)hasTabStrip {
1654 return [self supportsWindowFeature:Browser::FEATURE_TABSTRIP];
1657 - (BOOL)isTabDraggable:(NSView*)tabView {
1658 // TODO(avi, thakis): ConstrainedWindowSheetController has no api to move
1659 // tabsheets between windows. Until then, we have to prevent having to move a
1660 // tabsheet between windows, e.g. no tearing off of tabs.
1661 int index = [tabStripController_ modelIndexForTabView:tabView];
1662 WebContents* contents = browser_->tab_strip_model()->GetWebContentsAt(index);
1666 const web_modal::WebContentsModalDialogManager* manager =
1667 web_modal::WebContentsModalDialogManager::FromWebContents(contents);
1668 return !manager || !manager->IsDialogActive();
1671 // TabStripControllerDelegate protocol.
1672 - (void)onActivateTabWithContents:(WebContents*)contents {
1673 // Update various elements that are interested in knowing the current
1676 // Update all the UI bits.
1677 windowShim_->UpdateTitleBar();
1679 // Update the bookmark bar.
1680 // TODO(viettrungluu): perhaps update to not terminate running animations (if
1682 windowShim_->BookmarkBarStateChanged(
1683 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
1685 [infoBarContainerController_ changeWebContents:contents];
1687 // Must do this after bookmark and infobar updates to avoid
1688 // unnecesary resize in contents.
1689 [devToolsController_ updateDevToolsForWebContents:contents
1690 withProfile:browser_->profile()];
1693 - (void)onTabChanged:(TabStripModelObserver::TabChangeType)change
1694 withContents:(WebContents*)contents {
1695 // Update titles if this is the currently selected tab and if it isn't just
1696 // the loading state which changed.
1697 if (change != TabStripModelObserver::LOADING_ONLY)
1698 windowShim_->UpdateTitleBar();
1700 // Update the bookmark bar if this is the currently selected tab and if it
1701 // isn't just the title which changed. This for transitions between the NTP
1702 // (showing its floating bookmark bar) and normal web pages (showing no
1704 // TODO(viettrungluu): perhaps update to not terminate running animations?
1705 if (change != TabStripModelObserver::TITLE_NOT_LOADING) {
1706 windowShim_->BookmarkBarStateChanged(
1707 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
1711 - (void)onTabDetachedWithContents:(WebContents*)contents {
1712 [infoBarContainerController_ tabDetachedWithContents:contents];
1715 - (void)userChangedTheme {
1716 NSView* rootView = [[[self window] contentView] superview];
1717 [rootView cr_recursivelyInvokeBlock:^(id view) {
1718 if ([view conformsToProtocol:@protocol(ThemedWindowDrawing)])
1719 [view windowDidChangeTheme];
1721 // TODO(andresantoso): Remove this once all themed views respond to
1722 // windowDidChangeTheme above.
1723 [view setNeedsDisplay:YES];
1727 - (ui::ThemeProvider*)themeProvider {
1728 return ThemeServiceFactory::GetForProfile(browser_->profile());
1731 - (ThemedWindowStyle)themedWindowStyle {
1732 ThemedWindowStyle style = 0;
1733 if (browser_->profile()->IsOffTheRecord())
1734 style |= THEMED_INCOGNITO;
1736 if (browser_->is_devtools())
1737 style |= THEMED_DEVTOOLS;
1738 if (browser_->is_type_popup())
1739 style |= THEMED_POPUP;
1744 - (NSPoint)themeImagePositionForAlignment:(ThemeImageAlignment)alignment {
1745 NSView* windowChromeView = [[[self window] contentView] superview];
1746 NSView* tabStripView = nil;
1747 if ([self hasTabStrip])
1748 tabStripView = [self tabStripView];
1749 return [BrowserWindowUtils themeImagePositionFor:windowChromeView
1750 withTabStrip:tabStripView
1751 alignment:alignment];
1754 - (NSPoint)bookmarkBubblePoint {
1755 return [toolbarController_ bookmarkBubblePoint];
1758 // Show the bookmark bubble (e.g. user just clicked on the STAR).
1759 - (void)showBookmarkBubbleForURL:(const GURL&)url
1760 alreadyBookmarked:(BOOL)alreadyMarked {
1761 if (!bookmarkBubbleController_) {
1762 BookmarkModel* model =
1763 BookmarkModelFactory::GetForProfile(browser_->profile());
1764 bookmarks::ManagedBookmarkService* managed =
1765 ManagedBookmarkServiceFactory::GetForProfile(browser_->profile());
1766 const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(url);
1767 bookmarkBubbleController_ =
1768 [[BookmarkBubbleController alloc] initWithParentWindow:[self window]
1772 alreadyBookmarked:alreadyMarked];
1773 [bookmarkBubbleController_ showWindow:self];
1774 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1775 [center addObserver:self
1776 selector:@selector(bookmarkBubbleWindowWillClose:)
1777 name:NSWindowWillCloseNotification
1778 object:[bookmarkBubbleController_ window]];
1782 // Nil out the weak bookmark bubble controller reference.
1783 - (void)bookmarkBubbleWindowWillClose:(NSNotification*)notification {
1784 DCHECK_EQ([notification object], [bookmarkBubbleController_ window]);
1786 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1787 [center removeObserver:self
1788 name:NSWindowWillCloseNotification
1789 object:[bookmarkBubbleController_ window]];
1790 bookmarkBubbleController_ = nil;
1793 // Handle the editBookmarkNode: action sent from bookmark bubble controllers.
1794 - (void)editBookmarkNode:(id)sender {
1795 BOOL responds = [sender respondsToSelector:@selector(node)];
1798 const BookmarkNode* node = [sender node];
1800 BookmarkEditor::Show([self window], browser_->profile(),
1801 BookmarkEditor::EditDetails::EditNode(node),
1802 BookmarkEditor::SHOW_TREE);
1806 - (void)showTranslateBubbleForWebContents:(content::WebContents*)contents
1807 step:(translate::TranslateStep)step
1808 errorType:(translate::TranslateErrors::Type)
1810 // TODO(hajimehoshi): The similar logic exists at TranslateBubbleView::
1811 // ShowBubble. This should be unified.
1812 if (translateBubbleController_) {
1813 // When the user reads the advanced setting panel, the bubble should not be
1814 // changed because they are focusing on the bubble.
1815 if (translateBubbleController_.webContents == contents &&
1816 translateBubbleController_.model->GetViewState() ==
1817 TranslateBubbleModel::VIEW_STATE_ADVANCED) {
1820 if (step != translate::TRANSLATE_STEP_TRANSLATE_ERROR) {
1821 TranslateBubbleModel::ViewState viewState =
1822 TranslateBubbleModelImpl::TranslateStepToViewState(step);
1823 [translateBubbleController_ switchView:viewState];
1825 [translateBubbleController_ switchToErrorView:errorType];
1830 std::string sourceLanguage;
1831 std::string targetLanguage;
1832 ChromeTranslateClient::GetTranslateLanguages(
1833 contents, &sourceLanguage, &targetLanguage);
1835 scoped_ptr<translate::TranslateUIDelegate> uiDelegate(
1836 new translate::TranslateUIDelegate(
1837 ChromeTranslateClient::GetManagerFromWebContents(contents)
1841 scoped_ptr<TranslateBubbleModel> model(
1842 new TranslateBubbleModelImpl(step, uiDelegate.Pass()));
1843 translateBubbleController_ = [[TranslateBubbleController alloc]
1844 initWithParentWindow:self
1846 webContents:contents];
1847 [translateBubbleController_ showWindow:nil];
1849 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1850 [center addObserver:self
1851 selector:@selector(translateBubbleWindowWillClose:)
1852 name:NSWindowWillCloseNotification
1853 object:[translateBubbleController_ window]];
1856 - (void)dismissPermissionBubble {
1857 PermissionBubbleManager* manager = [self permissionBubbleManager];
1859 manager->HideBubble();
1862 // Nil out the weak translate bubble controller reference.
1863 - (void)translateBubbleWindowWillClose:(NSNotification*)notification {
1864 DCHECK_EQ([notification object], [translateBubbleController_ window]);
1866 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1867 [center removeObserver:self
1868 name:NSWindowWillCloseNotification
1869 object:[translateBubbleController_ window]];
1870 translateBubbleController_ = nil;
1873 // If the browser is in incognito mode or has multi-profiles, install the image
1874 // view to decorate the window at the upper right. Use the same base y
1875 // coordinate as the tab strip.
1876 - (void)installAvatar {
1877 // Install the image into the badge view. Hide it for now; positioning and
1878 // sizing will be done by the layout code. The AvatarIcon will choose which
1879 // image to display based on the browser. The AvatarButton will display
1880 // the browser profile's name unless the browser is incognito.
1882 if ([self shouldUseNewAvatarButton]) {
1883 avatarButtonController_.reset(
1884 [[AvatarButtonController alloc] initWithBrowser:browser_.get()]);
1886 avatarButtonController_.reset(
1887 [[AvatarIconController alloc] initWithBrowser:browser_.get()]);
1889 view = [avatarButtonController_ view];
1890 [view setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
1891 [view setHidden:![self shouldShowAvatar]];
1893 // Install the view.
1894 [[[self window] contentView] addSubview:view];
1897 // Called when we get a three-finger swipe.
1898 - (void)swipeWithEvent:(NSEvent*)event {
1899 CGFloat deltaX = [event deltaX];
1900 CGFloat deltaY = [event deltaY];
1902 // Map forwards and backwards to history; left is positive, right is negative.
1903 unsigned int command = 0;
1906 } else if (deltaX < -0.5) {
1907 command = IDC_FORWARD;
1908 } else if (deltaY > 0.5) {
1909 // TODO(pinkerton): figure out page-up, http://crbug.com/16305
1910 } else if (deltaY < -0.5) {
1911 // TODO(pinkerton): figure out page-down, http://crbug.com/16305
1914 // Ensure the command is valid first (ExecuteCommand() won't do that) and
1916 if (chrome::IsCommandEnabled(browser_.get(), command)) {
1917 chrome::ExecuteCommandWithDisposition(
1920 ui::WindowOpenDispositionFromNSEvent(event));
1924 // Delegate method called when window is resized.
1925 - (void)windowDidResize:(NSNotification*)notification {
1926 [self saveWindowPositionIfNeeded];
1928 // Resize (and possibly move) the status bubble. Note that we may get called
1929 // when the status bubble does not exist.
1930 if (statusBubble_) {
1931 statusBubble_->UpdateSizeAndPosition();
1934 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
1935 if (WebContents* contents = [self webContents]) {
1936 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
1937 rwhv->WindowFrameChanged();
1940 // The FindBar needs to know its own position to properly detect overlaps
1941 // with find results. The position changes whenever the window is resized,
1942 // and |layoutSubviews| computes the FindBar's position.
1943 // TODO: calling |layoutSubviews| here is a waste, find a better way to
1945 if ([findBarCocoaController_ isFindBarVisible])
1946 [self layoutSubviews];
1949 // Handle the openLearnMoreAboutCrashLink: action from SadTabView when
1950 // "Learn more" link in "Aw snap" page (i.e. crash page or sad tab) is
1951 // clicked. Decoupling the action from its target makes unit testing possible.
1952 - (void)openLearnMoreAboutCrashLink:(id)sender {
1953 if (WebContents* contents = [self webContents]) {
1954 OpenURLParams params(GURL(chrome::kCrashReasonURL), Referrer(), CURRENT_TAB,
1955 ui::PAGE_TRANSITION_LINK, false);
1956 contents->OpenURL(params);
1960 // Delegate method called when window did move. (See below for why we don't use
1961 // |-windowWillMove:|, which is called less frequently than |-windowDidMove|
1963 - (void)windowDidMove:(NSNotification*)notification {
1964 [self saveWindowPositionIfNeeded];
1966 NSWindow* window = [self window];
1967 NSRect windowFrame = [window frame];
1968 NSRect workarea = [[window screen] visibleFrame];
1970 // We reset the window growth state whenever the window is moved out of the
1971 // work area or away (up or down) from the bottom or top of the work area.
1972 // Unfortunately, Cocoa sends |-windowWillMove:| too frequently (including
1973 // when clicking on the title bar to activate), and of course
1974 // |-windowWillMove| is called too early for us to apply our heuristic. (The
1975 // heuristic we use for detecting window movement is that if |windowTopGrowth_
1976 // > 0|, then we should be at the bottom of the work area -- if we're not,
1977 // we've moved. Similarly for the other side.)
1978 if (!NSContainsRect(workarea, windowFrame) ||
1979 (windowTopGrowth_ > 0 && NSMinY(windowFrame) != NSMinY(workarea)) ||
1980 (windowBottomGrowth_ > 0 && NSMaxY(windowFrame) != NSMaxY(workarea)))
1981 [self resetWindowGrowthState];
1983 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
1984 if (WebContents* contents = [self webContents]) {
1985 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
1986 rwhv->WindowFrameChanged();
1990 // Delegate method called when window will be resized; not called for
1991 // |-setFrame:display:|.
1992 - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize {
1993 [self resetWindowGrowthState];
1997 // Delegate method: see |NSWindowDelegate| protocol.
1998 - (id)windowWillReturnFieldEditor:(NSWindow*)sender toObject:(id)obj {
1999 // Ask the toolbar controller if it wants to return a custom field editor
2000 // for the specific object.
2001 return [toolbarController_ customFieldEditorForObject:obj];
2004 // (Needed for |BookmarkBarControllerDelegate| protocol.)
2005 - (void)bookmarkBar:(BookmarkBarController*)controller
2006 didChangeFromState:(BookmarkBar::State)oldState
2007 toState:(BookmarkBar::State)newState {
2008 [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
2009 [self adjustToolbarAndBookmarkBarForCompression:
2010 [controller getDesiredToolbarHeightCompression]];
2013 // (Needed for |BookmarkBarControllerDelegate| protocol.)
2014 - (void)bookmarkBar:(BookmarkBarController*)controller
2015 willAnimateFromState:(BookmarkBar::State)oldState
2016 toState:(BookmarkBar::State)newState {
2017 [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
2018 [self adjustToolbarAndBookmarkBarForCompression:
2019 [controller getDesiredToolbarHeightCompression]];
2022 // (Private/TestingAPI)
2023 - (void)resetWindowGrowthState {
2024 windowTopGrowth_ = 0;
2025 windowBottomGrowth_ = 0;
2026 isShrinkingFromZoomed_ = NO;
2029 - (NSSize)overflowFrom:(NSRect)source
2031 // If |source|'s boundary is outside of |target|'s, set its distance
2032 // to |x|. Note that |source| can overflow to both side, but we
2033 // have nothing to do for such case.
2035 if (NSMaxX(target) < NSMaxX(source)) // |source| overflows to right
2036 x = NSMaxX(source) - NSMaxX(target);
2037 else if (NSMinX(source) < NSMinX(target)) // |source| overflows to left
2038 x = NSMinX(source) - NSMinX(target);
2040 // Same as |x| above.
2042 if (NSMaxY(target) < NSMaxY(source))
2043 y = NSMaxY(source) - NSMaxY(target);
2044 else if (NSMinY(source) < NSMinY(target))
2045 y = NSMinY(source) - NSMinY(target);
2047 return NSMakeSize(x, y);
2050 // (Private/TestingAPI)
2051 - (ExclusiveAccessBubbleWindowController*)
2052 exclusiveAccessBubbleWindowController {
2053 return exclusiveAccessBubbleWindowController_.get();
2056 - (NSRect)omniboxPopupAnchorRect {
2057 // Start with toolbar rect.
2058 NSView* toolbarView = [toolbarController_ view];
2059 NSRect anchorRect = [toolbarView frame];
2061 // Adjust to account for height and possible bookmark bar. Compress by 1
2062 // to account for the separator.
2063 anchorRect.origin.y =
2064 NSMaxY(anchorRect) - [toolbarController_ desiredHeightForCompression:1];
2066 // Shift to window base coordinates.
2067 return [[toolbarView superview] convertRect:anchorRect toView:nil];
2070 - (void)sheetDidEnd:(NSWindow*)sheet
2071 returnCode:(NSInteger)code
2072 context:(void*)context {
2073 [sheet orderOut:self];
2076 - (void)executeExtensionCommand:(const std::string&)extension_id
2077 command:(const extensions::Command&)command {
2078 // Global commands are handled by the ExtensionCommandsGlobalRegistry
2080 DCHECK(!command.global());
2081 extension_keybinding_registry_->ExecuteCommand(extension_id,
2082 command.accelerator());
2085 @end // @implementation BrowserWindowController
2087 @implementation BrowserWindowController(Fullscreen)
2089 - (void)handleLionToggleFullscreen {
2090 DCHECK(base::mac::IsOSLionOrLater());
2091 chrome::ExecuteCommand(browser_.get(), IDC_FULLSCREEN);
2094 - (NSString*)titleForFullscreenMenuItem {
2095 if (!chrome::mac::SupportsSystemFullscreen()) {
2096 return l10n_util::GetNSString([self inPresentationMode]
2097 ? IDS_EXIT_PRESENTATION_MAC
2098 : IDS_ENTER_PRESENTATION_MAC);
2101 return l10n_util::GetNSString([self isInAppKitFullscreen]
2102 ? IDS_EXIT_FULLSCREEN_MAC
2103 : IDS_ENTER_FULLSCREEN_MAC);
2106 - (void)enterBrowserFullscreenWithToolbar:(BOOL)withToolbar {
2107 if (!chrome::mac::SupportsSystemFullscreen()) {
2108 if (![self isInImmersiveFullscreen])
2109 [self enterImmersiveFullscreen];
2113 if ([self isInAppKitFullscreen]) {
2114 [self updateFullscreenWithToolbar:withToolbar];
2116 // Need to invoke AppKit Fullscreen API. Presentation mode (if set) will
2117 // automatically be enabled in |-windowWillEnterFullScreen:|.
2118 enteringPresentationMode_ = !withToolbar;
2119 [self enterAppKitFullscreen];
2123 - (void)updateFullscreenWithToolbar:(BOOL)withToolbar {
2124 [self adjustUIForSlidingFullscreenStyle:
2125 withToolbar ? fullscreen_mac::OMNIBOX_TABS_PRESENT
2126 : fullscreen_mac::OMNIBOX_TABS_HIDDEN];
2129 - (void)updateFullscreenExitBubbleURL:(const GURL&)url
2130 bubbleType:(ExclusiveAccessBubbleType)bubbleType {
2131 fullscreenUrl_ = url;
2132 exclusiveAccessBubbleType_ = bubbleType;
2133 [self layoutSubviews];
2134 [self showFullscreenExitBubbleIfNecessary];
2137 - (BOOL)isInAnyFullscreenMode {
2138 return [self isInImmersiveFullscreen] || [self isInAppKitFullscreen];
2141 - (BOOL)isInImmersiveFullscreen {
2142 return fullscreenWindow_.get() != nil || enteringImmersiveFullscreen_;
2145 - (BOOL)isInAppKitFullscreen {
2146 return !exitingAppKitFullscreen_ &&
2147 (([[self window] styleMask] & NSFullScreenWindowMask) ==
2148 NSFullScreenWindowMask ||
2149 enteringAppKitFullscreen_);
2152 - (void)enterExtensionFullscreenForURL:(const GURL&)url
2153 bubbleType:(ExclusiveAccessBubbleType)bubbleType {
2154 if (chrome::mac::SupportsSystemFullscreen()) {
2155 fullscreenUrl_ = url;
2156 exclusiveAccessBubbleType_ = bubbleType;
2157 [self enterBrowserFullscreenWithToolbar:NO];
2159 [self enterImmersiveFullscreen];
2160 DCHECK(!url.is_empty());
2161 [self updateFullscreenExitBubbleURL:url bubbleType:bubbleType];
2165 - (void)enterWebContentFullscreenForURL:(const GURL&)url
2166 bubbleType:(ExclusiveAccessBubbleType)bubbleType {
2167 [self enterImmersiveFullscreen];
2168 if (!url.is_empty())
2169 [self updateFullscreenExitBubbleURL:url bubbleType:bubbleType];
2172 - (void)exitAnyFullscreen {
2173 // TODO(erikchen): Fullscreen modes should stack. Should be able to exit
2174 // Immersive Fullscreen and still be in AppKit Fullscreen.
2175 if ([self isInAppKitFullscreen])
2176 [self exitAppKitFullscreen];
2177 if ([self isInImmersiveFullscreen])
2178 [self exitImmersiveFullscreen];
2181 - (BOOL)inPresentationMode {
2182 return presentationModeController_.get() &&
2183 [presentationModeController_ inPresentationMode] &&
2184 presentationModeController_.get().slidingStyle ==
2185 fullscreen_mac::OMNIBOX_TABS_HIDDEN;
2188 - (void)resizeFullscreenWindow {
2189 DCHECK([self isInAnyFullscreenMode]);
2190 if (![self isInAnyFullscreenMode])
2193 NSWindow* window = [self window];
2194 [window setFrame:[[window screen] frame] display:YES];
2195 [self layoutSubviews];
2198 - (BOOL)isBarVisibilityLockedForOwner:(id)owner {
2200 DCHECK(barVisibilityLocks_);
2201 return [barVisibilityLocks_ containsObject:owner];
2204 - (void)lockBarVisibilityForOwner:(id)owner
2205 withAnimation:(BOOL)animate
2207 if (![self isBarVisibilityLockedForOwner:owner]) {
2208 [barVisibilityLocks_ addObject:owner];
2210 // If enabled, show the overlay if necessary (and if in presentation mode).
2211 if (barVisibilityUpdatesEnabled_) {
2212 [presentationModeController_ ensureOverlayShownWithAnimation:animate
2218 - (void)releaseBarVisibilityForOwner:(id)owner
2219 withAnimation:(BOOL)animate
2221 if ([self isBarVisibilityLockedForOwner:owner]) {
2222 [barVisibilityLocks_ removeObject:owner];
2224 // If enabled, hide the overlay if necessary (and if in presentation mode).
2225 if (barVisibilityUpdatesEnabled_ &&
2226 ![barVisibilityLocks_ count]) {
2227 [presentationModeController_ ensureOverlayHiddenWithAnimation:animate
2233 - (BOOL)floatingBarHasFocus {
2234 NSResponder* focused = [[self window] firstResponder];
2235 return [focused isKindOfClass:[AutocompleteTextFieldEditor class]];
2238 @end // @implementation BrowserWindowController(Fullscreen)
2241 @implementation BrowserWindowController(WindowType)
2243 - (BOOL)supportsWindowFeature:(int)feature {
2244 return browser_->SupportsWindowFeature(
2245 static_cast<Browser::WindowFeature>(feature));
2248 - (BOOL)hasTitleBar {
2249 return [self supportsWindowFeature:Browser::FEATURE_TITLEBAR];
2252 - (BOOL)hasToolbar {
2253 return [self supportsWindowFeature:Browser::FEATURE_TOOLBAR];
2256 - (BOOL)hasLocationBar {
2257 return [self supportsWindowFeature:Browser::FEATURE_LOCATIONBAR];
2260 - (BOOL)supportsBookmarkBar {
2261 return [self supportsWindowFeature:Browser::FEATURE_BOOKMARKBAR];
2264 - (BOOL)isTabbedWindow {
2265 return browser_->is_type_tabbed();
2268 @end // @implementation BrowserWindowController(WindowType)