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/chrome_bookmark_client.h"
21 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/devtools/devtools_window.h"
24 #include "chrome/browser/extensions/extension_commands_global_registry.h"
25 #include "chrome/browser/fullscreen.h"
26 #include "chrome/browser/profiles/avatar_menu.h"
27 #include "chrome/browser/profiles/profile.h"
28 #include "chrome/browser/profiles/profile_info_cache.h"
29 #include "chrome/browser/profiles/profile_manager.h"
30 #include "chrome/browser/profiles/profiles_state.h"
31 #include "chrome/browser/themes/theme_service.h"
32 #include "chrome/browser/themes/theme_service_factory.h"
33 #include "chrome/browser/translate/chrome_translate_client.h"
34 #include "chrome/browser/ui/bookmarks/bookmark_editor.h"
35 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
36 #include "chrome/browser/ui/browser.h"
37 #include "chrome/browser/ui/browser_command_controller.h"
38 #include "chrome/browser/ui/browser_commands.h"
39 #include "chrome/browser/ui/browser_instant_controller.h"
40 #include "chrome/browser/ui/browser_list.h"
41 #include "chrome/browser/ui/browser_window_state.h"
42 #import "chrome/browser/ui/cocoa/background_gradient_view.h"
43 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_bar_controller.h"
44 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_editor_controller.h"
45 #import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
46 #import "chrome/browser/ui/cocoa/browser_window_controller_private.h"
47 #import "chrome/browser/ui/cocoa/browser_window_layout.h"
48 #import "chrome/browser/ui/cocoa/browser_window_utils.h"
49 #import "chrome/browser/ui/cocoa/dev_tools_controller.h"
50 #import "chrome/browser/ui/cocoa/download/download_shelf_controller.h"
51 #include "chrome/browser/ui/cocoa/extensions/extension_keybinding_registry_cocoa.h"
52 #import "chrome/browser/ui/cocoa/fast_resize_view.h"
53 #import "chrome/browser/ui/cocoa/find_bar/find_bar_bridge.h"
54 #import "chrome/browser/ui/cocoa/find_bar/find_bar_cocoa_controller.h"
55 #import "chrome/browser/ui/cocoa/framed_browser_window.h"
56 #import "chrome/browser/ui/cocoa/fullscreen_window.h"
57 #import "chrome/browser/ui/cocoa/infobars/infobar_container_controller.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/sad_tab_controller.h"
66 #import "chrome/browser/ui/cocoa/tab_contents/tab_contents_controller.h"
67 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
68 #import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h"
69 #import "chrome/browser/ui/cocoa/tabs/tab_view.h"
70 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
71 #import "chrome/browser/ui/cocoa/translate/translate_bubble_controller.h"
72 #include "chrome/browser/ui/cocoa/website_settings/permission_bubble_cocoa.h"
73 #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
74 #include "chrome/browser/ui/location_bar/location_bar.h"
75 #include "chrome/browser/ui/tabs/tab_strip_model.h"
76 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
77 #include "chrome/browser/ui/toolbar/encoding_menu_controller.h"
78 #include "chrome/browser/ui/translate/translate_bubble_model_impl.h"
79 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
80 #include "chrome/browser/ui/window_sizer/window_sizer.h"
81 #include "chrome/common/chrome_switches.h"
82 #include "chrome/common/extensions/command.h"
83 #include "chrome/common/url_constants.h"
84 #include "chrome/grit/generated_resources.h"
85 #include "chrome/grit/locale_settings.h"
86 #include "components/bookmarks/browser/bookmark_model.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/popup_manager.h"
91 #include "components/web_modal/web_contents_modal_dialog_manager.h"
92 #include "content/public/browser/render_view_host.h"
93 #include "content/public/browser/render_widget_host_view.h"
94 #include "content/public/browser/web_contents.h"
95 #import "ui/base/cocoa/cocoa_base_utils.h"
96 #import "ui/base/cocoa/nsview_additions.h"
97 #include "ui/base/l10n/l10n_util.h"
98 #include "ui/base/l10n/l10n_util_mac.h"
99 #include "ui/gfx/mac/scoped_ns_disable_screen_updates.h"
101 using bookmarks::BookmarkModel;
102 using bookmarks::BookmarkNode;
103 using l10n_util::GetStringUTF16;
104 using l10n_util::GetNSStringWithFixup;
105 using l10n_util::GetNSStringFWithFixup;
107 // ORGANIZATION: This is a big file. It is (in principle) organized as follows
109 // 1. Interfaces. Very short, one-time-use classes may include an implementation
110 // immediately after their interface.
111 // 2. The general implementation section, ordered as follows:
112 // i. Public methods and overrides.
113 // ii. Overrides/implementations of undocumented methods.
114 // iii. Delegate methods for various protocols, formal and informal, to which
115 // |BrowserWindowController| conforms.
116 // 3. (temporary) Implementation sections for various categories.
118 // Private methods are defined and implemented separately in
119 // browser_window_controller_private.{h,mm}.
121 // Not all of the above guidelines are followed and more (re-)organization is
122 // needed. BUT PLEASE TRY TO KEEP THIS FILE ORGANIZED. I'd rather re-organize as
123 // little as possible, since doing so messes up the file's history.
125 // TODO(viettrungluu): [crbug.com/35543] on-going re-organization, splitting
126 // things into multiple files -- the plan is as follows:
127 // - in general, everything stays in browser_window_controller.h, but is split
128 // off into categories (see below)
129 // - core stuff stays in browser_window_controller.mm
130 // - ... overrides also stay (without going into a category, in particular)
131 // - private stuff which everyone needs goes into
132 // browser_window_controller_private.{h,mm}; if no one else needs them, they
133 // can go in individual files (see below)
134 // - area/task-specific stuff go in browser_window_controller_<area>.mm
135 // - ... in categories called "(<Area>)" or "(<PrivateArea>)"
137 // - first re-organize into categories
138 // - then split into files
140 // Notes on self-inflicted (not user-inflicted) window resizing and moving:
142 // When the bookmark bar goes from hidden to shown (on a non-NTP) page, or when
143 // the download shelf goes from hidden to shown, we grow the window downwards in
144 // order to maintain a constant content area size. When either goes from shown
145 // to hidden, we consequently shrink the window from the bottom, also to keep
146 // the content area size constant. To keep things simple, if the window is not
147 // entirely on-screen, we don't grow/shrink the window.
149 // The complications come in when there isn't enough room (on screen) below the
150 // window to accomodate the growth. In this case, we grow the window first
151 // downwards, and then upwards. So, when it comes to shrinking, we do the
152 // opposite: shrink from the top by the amount by which we grew at the top, and
153 // then from the bottom -- unless the user moved/resized/zoomed the window, in
154 // which case we "reset state" and just shrink from the bottom.
156 // A further complication arises due to the way in which "zoom" ("maximize")
157 // works on Mac OS X. Basically, for our purposes, a window is "zoomed" whenever
158 // it occupies the full available vertical space. (Note that the green zoom
159 // button does not track zoom/unzoomed state per se, but basically relies on
160 // this heuristic.) We don't, in general, want to shrink the window if the
161 // window is zoomed (scenario: window is zoomed, download shelf opens -- which
162 // doesn't cause window growth, download shelf closes -- shouldn't cause the
163 // window to become unzoomed!). However, if we grew the window
164 // (upwards/downwards) to become zoomed in the first place, we *should* shrink
165 // the window by the amounts by which we grew (scenario: window occupies *most*
166 // of vertical space, download shelf opens causing growth so that window
167 // occupies all of vertical space -- i.e., window is effectively zoomed,
168 // download shelf closes -- should return the window to its previous state).
170 // A major complication is caused by the way grows/shrinks are handled and
171 // animated. Basically, the BWC doesn't see the global picture, but it sees
172 // grows and shrinks in small increments (as dictated by the animation). Thus
173 // window growth/shrinkage (at the top/bottom) have to be tracked incrementally.
174 // Allowing shrinking from the zoomed state also requires tracking: We check on
175 // any shrink whether we're both zoomed and have previously grown -- if so, we
176 // set a flag, and constrain any resize by the allowed amounts. On further
177 // shrinks, we check the flag (since the size/position of the window will no
178 // longer indicate that the window is shrinking from an apparent zoomed state)
179 // and if it's set we continue to constrain the resize.
181 using content::OpenURLParams;
182 using content::Referrer;
183 using content::RenderWidgetHostView;
184 using content::WebContents;
186 @interface NSWindow (NSPrivateApis)
187 // Note: These functions are private, use -[NSObject respondsToSelector:]
188 // before calling them.
190 - (void)setBottomCornerRounded:(BOOL)rounded;
192 - (NSRect)_growBoxRect;
196 @implementation BrowserWindowController
198 + (BrowserWindowController*)browserWindowControllerForWindow:(NSWindow*)window {
200 id controller = [window windowController];
201 if ([controller isKindOfClass:[BrowserWindowController class]])
202 return (BrowserWindowController*)controller;
203 window = [window parentWindow];
208 + (BrowserWindowController*)browserWindowControllerForView:(NSView*)view {
209 NSWindow* window = [view window];
210 return [BrowserWindowController browserWindowControllerForWindow:window];
213 // Load the browser window nib and do any Cocoa-specific initialization.
214 // Takes ownership of |browser|. Note that the nib also sets this controller
215 // up as the window's delegate.
216 - (id)initWithBrowser:(Browser*)browser {
217 return [self initWithBrowser:browser takeOwnership:YES];
220 // Private(TestingAPI) init routine with testing options.
221 - (id)initWithBrowser:(Browser*)browser takeOwnership:(BOOL)ownIt {
222 bool hasTabStrip = browser->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
223 if ((self = [super initTabWindowControllerWithTabStrip:hasTabStrip])) {
226 browser_.reset(browser);
227 ownsBrowser_ = ownIt;
228 NSWindow* window = [self window];
229 // Make the content view for the window have a layer. This will make all
230 // sub-views have layers. This is necessary to ensure correct layer
231 // ordering of all child views and their layers.
232 [[window contentView] setWantsLayer:YES];
233 windowShim_.reset(new BrowserWindowCocoa(browser, self));
235 // Set different minimum sizes on tabbed windows vs non-tabbed, e.g. popups.
236 // This has to happen before -enforceMinWindowSize: is called further down.
237 NSSize minSize = [self isTabbedWindow] ?
238 NSMakeSize(400, 272) : NSMakeSize(100, 122);
239 [[self window] setMinSize:minSize];
241 // Create the bar visibility lock set; 10 is arbitrary, but should hopefully
242 // be big enough to hold all locks that'll ever be needed.
243 barVisibilityLocks_.reset([[NSMutableSet setWithCapacity:10] retain]);
245 // Set the window to not have rounded corners, which prevents the resize
246 // control from being inset slightly and looking ugly. Only bother to do
247 // this on Snow Leopard; on Lion and later all windows have rounded bottom
248 // corners, and this won't work anyway.
249 if (base::mac::IsOSSnowLeopard() &&
250 [window respondsToSelector:@selector(setBottomCornerRounded:)])
251 [window setBottomCornerRounded:NO];
253 // Lion will attempt to automagically save and restore the UI. This
254 // functionality appears to be leaky (or at least interacts badly with our
255 // architecture) and thus BrowserWindowController never gets released. This
256 // prevents the browser from being able to quit <http://crbug.com/79113>.
257 if ([window respondsToSelector:@selector(setRestorable:)])
258 [window setRestorable:NO];
260 // Get the windows to swish in on Lion.
261 if ([window respondsToSelector:@selector(setAnimationBehavior:)])
262 [window setAnimationBehavior:NSWindowAnimationBehaviorDocumentWindow];
264 // Get the most appropriate size for the window, then enforce the
265 // minimum width and height. The window shim will handle flipping
266 // the coordinates for us so we can use it to save some code.
267 // Note that this may leave a significant portion of the window
268 // offscreen, but there will always be enough window onscreen to
269 // drag the whole window back into view.
270 ui::WindowShowState show_state = ui::SHOW_STATE_DEFAULT;
271 gfx::Rect desiredContentRect;
272 chrome::GetSavedWindowBoundsAndShowState(browser_.get(),
275 gfx::Rect windowRect = desiredContentRect;
276 windowRect = [self enforceMinWindowSize:windowRect];
278 // When we are given x/y coordinates of 0 on a created popup window, assume
279 // none were given by the window.open() command.
280 if (browser_->is_type_popup() &&
281 windowRect.x() == 0 && windowRect.y() == 0) {
282 gfx::Size size = windowRect.size();
283 windowRect.set_origin(
284 WindowSizer::GetDefaultPopupOrigin(size,
285 browser_->host_desktop_type()));
288 // Size and position the window. Note that it is not yet onscreen. Popup
289 // windows may get resized later on in this function, once the actual size
290 // of the toolbar/tabstrip is known.
291 windowShim_->SetBounds(windowRect);
293 // Puts the incognito badge on the window frame, if necessary.
294 [self installAvatar];
296 // Create a sub-controller for the docked devTools and add its view to the
298 devToolsController_.reset([[DevToolsController alloc] init]);
299 [[devToolsController_ view] setFrame:[[self tabContentArea] bounds]];
300 [[self tabContentArea] addSubview:[devToolsController_ view]];
302 // Create the overlayable contents controller. This provides the switch
303 // view that TabStripController needs.
304 overlayableContentsController_.reset(
305 [[OverlayableContentsController alloc] initWithBrowser:browser]);
306 [[overlayableContentsController_ view]
307 setFrame:[[devToolsController_ view] bounds]];
308 [[devToolsController_ view]
309 addSubview:[overlayableContentsController_ view]];
311 // Create a controller for the tab strip, giving it the model object for
312 // this window's Browser and the tab strip view. The controller will handle
313 // registering for the appropriate tab notifications from the back-end and
314 // managing the creation of new tabs.
315 [self createTabStripController];
317 // Create a controller for the toolbar, giving it the toolbar model object
318 // and the toolbar view from the nib. The controller will handle
319 // registering for the appropriate command state changes from the back-end.
320 // Adds the toolbar to the content area.
321 toolbarController_.reset([[ToolbarController alloc]
322 initWithCommands:browser->command_controller()->command_updater()
323 profile:browser->profile()
325 resizeDelegate:self]);
326 [toolbarController_ setHasToolbar:[self hasToolbar]
327 hasLocationBar:[self hasLocationBar]];
329 // Create a sub-controller for the bookmark bar.
330 bookmarkBarController_.reset(
331 [[BookmarkBarController alloc]
332 initWithBrowser:browser_.get()
333 initialWidth:NSWidth([[[self window] contentView] frame])
335 resizeDelegate:self]);
336 [bookmarkBarController_ setBookmarkBarEnabled:[self supportsBookmarkBar]];
338 // Create the infobar container view, so we can pass it to the
339 // ToolbarController.
340 infoBarContainerController_.reset(
341 [[InfoBarContainerController alloc] initWithResizeDelegate:self]);
342 [self updateInfoBarTipVisibility];
344 // We don't want to try and show the bar before it gets placed in its parent
345 // view, so this step shoudn't be inside the bookmark bar controller's
347 windowShim_->BookmarkBarStateChanged(
348 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
350 // Allow bar visibility to be changed.
351 [self enableBarVisibilityUpdates];
353 // Set the window to participate in Lion Fullscreen mode. Setting this flag
354 // has no effect on Snow Leopard or earlier. Panels can share a fullscreen
355 // space with a tabbed window, but they can not be primary fullscreen
357 // This ensures the fullscreen button is appropriately positioned. It must
358 // be done before calling layoutSubviews because the new avatar button's
359 // position depends on the fullscreen button's position, as well as
360 // TabStripController's rightIndentForControls.
361 // The fullscreen button's position may depend on the old avatar button's
362 // width, but that does not require calling layoutSubviews first.
363 NSUInteger collectionBehavior = [window collectionBehavior];
364 collectionBehavior |=
365 browser_->type() == Browser::TYPE_TABBED ||
366 browser_->type() == Browser::TYPE_POPUP ?
367 NSWindowCollectionBehaviorFullScreenPrimary :
368 NSWindowCollectionBehaviorFullScreenAuxiliary;
369 [window setCollectionBehavior:collectionBehavior];
371 [self layoutSubviews];
373 // For a popup window, |desiredContentRect| contains the desired height of
374 // the content, not of the whole window. Now that all the views are laid
375 // out, measure the current content area size and grow if needed. The
376 // window has not been placed onscreen yet, so this extra resize will not
377 // cause visible jank.
378 if (browser_->is_type_popup()) {
379 CGFloat deltaH = desiredContentRect.height() -
380 NSHeight([[self tabContentArea] frame]);
381 // Do not shrink the window, as that may break minimum size invariants.
383 // Convert from tabContentArea coordinates to window coordinates.
384 NSSize convertedSize =
385 [[self tabContentArea] convertSize:NSMakeSize(0, deltaH)
387 NSRect frame = [[self window] frame];
388 frame.size.height += convertedSize.height;
389 frame.origin.y -= convertedSize.height;
390 [[self window] setFrame:frame display:NO];
394 // Create the bridge for the status bubble.
395 statusBubble_ = new StatusBubbleMac([self window], self);
397 // Create the permissions bubble.
398 permissionBubbleCocoa_.reset(new PermissionBubbleCocoa([self window]));
400 // Register for application hide/unhide notifications.
401 [[NSNotificationCenter defaultCenter]
403 selector:@selector(applicationDidHide:)
404 name:NSApplicationDidHideNotification
406 [[NSNotificationCenter defaultCenter]
408 selector:@selector(applicationDidUnhide:)
409 name:NSApplicationDidUnhideNotification
412 // This must be done after the view is added to the window since it relies
413 // on the window bounds to determine whether to show buttons or not.
414 if ([self hasToolbar]) // Do not create the buttons in popups.
415 [toolbarController_ createBrowserActionButtons];
417 extension_keybinding_registry_.reset(
418 new ExtensionKeybindingRegistryCocoa(browser_->profile(),
420 extensions::ExtensionKeybindingRegistry::ALL_EXTENSIONS,
423 // We are done initializing now.
430 browser_->tab_strip_model()->CloseAllTabs();
431 [downloadShelfController_ exiting];
433 // Explicitly release |presentationModeController_| here, as it may call back
434 // to this BWC in |-dealloc|. We are required to call |-exitPresentationMode|
435 // before releasing the controller.
436 [presentationModeController_ exitPresentationMode];
437 presentationModeController_.reset();
439 // Under certain testing configurations we may not actually own the browser.
440 if (ownsBrowser_ == NO)
441 ignore_result(browser_.release());
443 [[NSNotificationCenter defaultCenter] removeObserver:self];
448 - (gfx::Rect)enforceMinWindowSize:(gfx::Rect)bounds {
449 gfx::Rect checkedBounds = bounds;
451 NSSize minSize = [[self window] minSize];
452 if (bounds.width() < minSize.width)
453 checkedBounds.set_width(minSize.width);
454 if (bounds.height() < minSize.height)
455 checkedBounds.set_height(minSize.height);
457 return checkedBounds;
460 - (BrowserWindow*)browserWindow {
461 return windowShim_.get();
464 - (ToolbarController*)toolbarController {
465 return toolbarController_.get();
468 - (TabStripController*)tabStripController {
469 return tabStripController_.get();
472 - (FindBarCocoaController*)findBarCocoaController {
473 return findBarCocoaController_.get();
476 - (InfoBarContainerController*)infoBarContainerController {
477 return infoBarContainerController_.get();
480 - (StatusBubbleMac*)statusBubble {
481 return statusBubble_;
484 - (LocationBarViewMac*)locationBarBridge {
485 return [toolbarController_ locationBarBridge];
488 - (NSView*)floatingBarBackingView {
489 return floatingBarBackingView_;
492 - (OverlayableContentsController*)overlayableContentsController {
493 return overlayableContentsController_;
496 - (Profile*)profile {
497 return browser_->profile();
500 - (AvatarBaseController*)avatarButtonController {
501 return avatarButtonController_.get();
504 - (void)destroyBrowser {
505 [NSApp removeWindowsItem:[self window]];
507 // We need the window to go away now.
508 // We can't actually use |-autorelease| here because there's an embedded
509 // run loop in the |-performClose:| which contains its own autorelease pool.
510 // Instead call it after a zero-length delay, which gets us back to the main
512 [self performSelector:@selector(autorelease)
517 // Called when the window meets the criteria to be closed (ie,
518 // |-windowShouldClose:| returns YES). We must be careful to preserve the
519 // semantics of BrowserWindow::Close() and not call the Browser's dtor directly
521 - (void)windowWillClose:(NSNotification*)notification {
522 DCHECK_EQ([notification object], [self window]);
523 DCHECK(browser_->tab_strip_model()->empty());
524 [savedRegularWindow_ close];
525 // We delete statusBubble here because we need to kill off the dependency
526 // that its window has on our window before our window goes away.
527 delete statusBubble_;
528 statusBubble_ = NULL;
529 // We can't actually use |-autorelease| here because there's an embedded
530 // run loop in the |-performClose:| which contains its own autorelease pool.
531 // Instead call it after a zero-length delay, which gets us back to the main
533 [self performSelector:@selector(autorelease)
538 - (void)updateDevToolsForContents:(WebContents*)contents {
539 BOOL layout_changed =
540 [devToolsController_ updateDevToolsForWebContents:contents
541 withProfile:browser_->profile()];
542 if (layout_changed && [findBarCocoaController_ isFindBarVisible])
543 [self layoutSubviews];
546 // Called when the user wants to close a window or from the shutdown process.
547 // The Browser object is in control of whether or not we're allowed to close. It
548 // may defer closing due to several states, such as onUnload handlers needing to
549 // be fired. If closing is deferred, the Browser will handle the processing
550 // required to get us to the closing state and (by watching for all the tabs
551 // going away) will again call to close the window when it's finally ready.
552 - (BOOL)windowShouldClose:(id)sender {
553 // Disable updates while closing all tabs to avoid flickering.
554 gfx::ScopedNSDisableScreenUpdates disabler;
555 // Give beforeunload handlers the chance to cancel the close before we hide
557 if (!browser_->ShouldCloseWindow())
560 // saveWindowPositionIfNeeded: only works if we are the last active
561 // window, but orderOut: ends up activating another window, so we
562 // have to save the window position before we call orderOut:.
563 [self saveWindowPositionIfNeeded];
565 bool fast_tab_closing_enabled =
566 base::CommandLine::ForCurrentProcess()->HasSwitch(
567 switches::kEnableFastUnload);
569 if (!browser_->tab_strip_model()->empty()) {
570 // Tab strip isn't empty. Hide the frame (so it appears to have closed
571 // immediately) and close all the tabs, allowing the renderers to shut
572 // down. When the tab strip is empty we'll be called back again.
573 [[self window] orderOut:self];
574 browser_->OnWindowClosing();
575 if (fast_tab_closing_enabled)
576 browser_->tab_strip_model()->CloseAllTabs();
578 } else if (fast_tab_closing_enabled &&
579 !browser_->HasCompletedUnloadProcessing()) {
580 // The browser needs to finish running unload handlers.
581 // Hide the window (so it appears to have closed immediately), and
582 // the browser will call us back again when it is ready to close.
583 [[self window] orderOut:self];
587 // the tab strip is empty, it's ok to close the window
591 // Called right after our window became the main window.
592 - (void)windowDidBecomeMain:(NSNotification*)notification {
593 BrowserList::SetLastActive(browser_.get());
594 [self saveWindowPositionIfNeeded];
596 [[[self window] contentView] cr_recursivelyInvokeBlock:^(id view) {
597 if ([view conformsToProtocol:@protocol(ThemedWindowDrawing)])
598 [view windowDidChangeActive];
601 extensions::ExtensionCommandsGlobalRegistry::Get(browser_->profile())
602 ->set_registry_for_active_window(extension_keybinding_registry_.get());
605 - (void)windowDidResignMain:(NSNotification*)notification {
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(nullptr);
615 // Called when we are activated (when we gain focus).
616 - (void)windowDidBecomeKey:(NSNotification*)notification {
617 // We need to activate the controls (in the "WebView"). To do this, get the
618 // selected WebContents's RenderWidgetHostView and tell it to activate.
619 if (WebContents* contents =
620 browser_->tab_strip_model()->GetActiveWebContents()) {
622 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
625 RenderWidgetHostView* devtoolsView = devtools->GetRenderWidgetHostView();
626 if (devtoolsView && devtoolsView->HasFocus()) {
627 devtoolsView->SetActive(true);
632 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
633 rwhv->SetActive(true);
637 // Called when we are deactivated (when we lose focus).
638 - (void)windowDidResignKey:(NSNotification*)notification {
639 // If our app is still active and we're still the key window, ignore this
640 // message, since it just means that a menu extra (on the "system status bar")
641 // was activated; we'll get another |-windowDidResignKey| if we ever really
642 // lose key window status.
643 if ([NSApp isActive] && ([NSApp keyWindow] == [self window]))
646 // We need to deactivate the controls (in the "WebView"). To do this, get the
647 // selected WebContents's RenderWidgetHostView and tell it to deactivate.
648 if (WebContents* contents =
649 browser_->tab_strip_model()->GetActiveWebContents()) {
651 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
654 RenderWidgetHostView* devtoolsView = devtools->GetRenderWidgetHostView();
655 if (devtoolsView && devtoolsView->HasFocus()) {
656 devtoolsView->SetActive(false);
661 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
662 rwhv->SetActive(false);
666 // Called when we have been minimized.
667 - (void)windowDidMiniaturize:(NSNotification *)notification {
668 [self saveWindowPositionIfNeeded];
670 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
671 if (WebContents* contents =
672 browser_->tab_strip_model()->GetActiveWebContents()) {
673 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
674 rwhv->SetWindowVisibility(false);
678 // Called when we have been unminimized.
679 - (void)windowDidDeminiaturize:(NSNotification *)notification {
680 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
681 if (WebContents* contents =
682 browser_->tab_strip_model()->GetActiveWebContents()) {
683 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
684 rwhv->SetWindowVisibility(true);
688 // Called when the application has been hidden.
689 - (void)applicationDidHide:(NSNotification *)notification {
690 // Let the selected RenderWidgetHostView know, so that it can tell plugins
691 // (unless we are minimized, in which case nothing has really changed).
692 if (![[self window] isMiniaturized]) {
693 if (WebContents* contents =
694 browser_->tab_strip_model()->GetActiveWebContents()) {
695 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
696 rwhv->SetWindowVisibility(false);
701 // Called when the application has been unhidden.
702 - (void)applicationDidUnhide:(NSNotification *)notification {
703 // Let the selected RenderWidgetHostView know, so that it can tell plugins
704 // (unless we are minimized, in which case nothing has really changed).
705 if (![[self window] isMiniaturized]) {
706 if (WebContents* contents =
707 browser_->tab_strip_model()->GetActiveWebContents()) {
708 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
709 rwhv->SetWindowVisibility(true);
714 // Called when the user clicks the zoom button (or selects it from the Window
715 // menu) to determine the "standard size" of the window, based on the content
716 // and other factors. If the current size/location differs nontrivally from the
717 // standard size, Cocoa resizes the window to the standard size, and saves the
718 // current size as the "user size". If the current size/location is the same (up
719 // to a fudge factor) as the standard size, Cocoa resizes the window to the
720 // saved user size. (It is possible for the two to coincide.) In this way, the
721 // zoom button acts as a toggle. We determine the standard size based on the
722 // content, but enforce a minimum width (calculated using the dimensions of the
723 // screen) to ensure websites with small intrinsic width (such as google.com)
724 // don't end up with a wee window. Moreover, we always declare the standard
725 // width to be at least as big as the current width, i.e., we never want zooming
726 // to the standard width to shrink the window. This is consistent with other
727 // browsers' behaviour, and is desirable in multi-tab situations. Note, however,
728 // that the "toggle" behaviour means that the window can still be "unzoomed" to
730 - (NSRect)windowWillUseStandardFrame:(NSWindow*)window
731 defaultFrame:(NSRect)frame {
732 // Forget that we grew the window up (if we in fact did).
733 [self resetWindowGrowthState];
735 // |frame| already fills the current screen. Never touch y and height since we
736 // always want to fill vertically.
738 // If the shift key is down, maximize. Hopefully this should make the
739 // "switchers" happy.
740 if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask) {
744 // To prevent strange results on portrait displays, the basic minimum zoomed
745 // width is the larger of: 60% of available width, 60% of available height
746 // (bounded by available width).
747 const CGFloat kProportion = 0.6;
748 CGFloat zoomedWidth =
749 std::max(kProportion * NSWidth(frame),
750 std::min(kProportion * NSHeight(frame), NSWidth(frame)));
752 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
754 // If the intrinsic width is bigger, then make it the zoomed width.
755 const int kScrollbarWidth = 16; // TODO(viettrungluu): ugh.
756 CGFloat intrinsicWidth = static_cast<CGFloat>(
757 contents->GetPreferredSize().width() + kScrollbarWidth);
758 zoomedWidth = std::max(zoomedWidth,
759 std::min(intrinsicWidth, NSWidth(frame)));
762 // Never shrink from the current size on zoom (see above).
763 NSRect currentFrame = [[self window] frame];
764 zoomedWidth = std::max(zoomedWidth, NSWidth(currentFrame));
766 // |frame| determines our maximum extents. We need to set the origin of the
767 // frame -- and only move it left if necessary.
768 if (currentFrame.origin.x + zoomedWidth > NSMaxX(frame))
769 frame.origin.x = NSMaxX(frame) - zoomedWidth;
771 frame.origin.x = currentFrame.origin.x;
773 // Set the width. Don't touch y or height.
774 frame.size.width = zoomedWidth;
780 [BrowserWindowUtils activateWindowForController:self];
783 // Determine whether we should let a window zoom/unzoom to the given |newFrame|.
784 // We avoid letting unzoom move windows between screens, because it's really
785 // strange and unintuitive.
786 - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame {
787 // Figure out which screen |newFrame| is on.
788 NSScreen* newScreen = nil;
789 CGFloat newScreenOverlapArea = 0.0;
790 for (NSScreen* screen in [NSScreen screens]) {
791 NSRect overlap = NSIntersectionRect(newFrame, [screen frame]);
792 CGFloat overlapArea = NSWidth(overlap) * NSHeight(overlap);
793 if (overlapArea > newScreenOverlapArea) {
795 newScreenOverlapArea = overlapArea;
798 // If we're somehow not on any screen, allow the zoom.
802 // If the new screen is the current screen, we can return a definitive YES.
803 // Note: This check is not strictly necessary, but just short-circuits in the
804 // "no-brainer" case. To test the complicated logic below, comment this out!
805 NSScreen* curScreen = [window screen];
806 if (newScreen == curScreen)
809 // Worry a little: What happens when a window is on two (or more) screens?
810 // E.g., what happens in a 50-50 scenario? Cocoa may reasonably elect to zoom
811 // to the other screen rather than staying on the officially current one. So
812 // we compare overlaps with the current window frame, and see if Cocoa's
813 // choice was reasonable (allowing a small rounding error). This should
814 // hopefully avoid us ever erroneously denying a zoom when a window is on
816 NSRect curFrame = [window frame];
817 NSRect newScrIntersectCurFr = NSIntersectionRect([newScreen frame], curFrame);
818 NSRect curScrIntersectCurFr = NSIntersectionRect([curScreen frame], curFrame);
819 if (NSWidth(newScrIntersectCurFr) * NSHeight(newScrIntersectCurFr) >=
820 (NSWidth(curScrIntersectCurFr) * NSHeight(curScrIntersectCurFr) - 1.0)) {
824 // If it wasn't reasonable, return NO.
828 // Adjusts the window height by the given amount.
829 - (BOOL)adjustWindowHeightBy:(CGFloat)deltaH {
830 // By not adjusting the window height when initializing, we can ensure that
831 // the window opens with the same size that was saved on close.
832 if (initializing_ || [self isInAnyFullscreenMode] || deltaH == 0)
835 NSWindow* window = [self window];
836 NSRect windowFrame = [window frame];
837 NSRect workarea = [[window screen] visibleFrame];
839 // If the window is not already fully in the workarea, do not adjust its frame
841 if (!NSContainsRect(workarea, windowFrame))
844 // Record the position of the top/bottom of the window, so we can easily check
845 // whether we grew the window upwards/downwards.
846 CGFloat oldWindowMaxY = NSMaxY(windowFrame);
847 CGFloat oldWindowMinY = NSMinY(windowFrame);
849 // We are "zoomed" if we occupy the full vertical space.
850 bool isZoomed = (windowFrame.origin.y == workarea.origin.y &&
851 NSHeight(windowFrame) == NSHeight(workarea));
853 // If we're shrinking the window....
855 bool didChange = false;
857 // Don't reset if not currently zoomed since shrinking can take several
860 isShrinkingFromZoomed_ = YES;
862 // If we previously grew at the top, shrink as much as allowed at the top
864 if (windowTopGrowth_ > 0) {
865 CGFloat shrinkAtTopBy = MIN(-deltaH, windowTopGrowth_);
866 windowFrame.size.height -= shrinkAtTopBy; // Shrink the window.
867 deltaH += shrinkAtTopBy; // Update the amount left to shrink.
868 windowTopGrowth_ -= shrinkAtTopBy; // Update the growth state.
872 // Similarly for the bottom (not an "else if" since we may have to
873 // simultaneously shrink at both the top and at the bottom). Note that
874 // |deltaH| may no longer be nonzero due to the above.
875 if (deltaH < 0 && windowBottomGrowth_ > 0) {
876 CGFloat shrinkAtBottomBy = MIN(-deltaH, windowBottomGrowth_);
877 windowFrame.origin.y += shrinkAtBottomBy; // Move the window up.
878 windowFrame.size.height -= shrinkAtBottomBy; // Shrink the window.
879 deltaH += shrinkAtBottomBy; // Update the amount left....
880 windowBottomGrowth_ -= shrinkAtBottomBy; // Update the growth state.
884 // If we're shrinking from zoomed but we didn't change the top or bottom
885 // (since we've reached the limits imposed by |window...Growth_|), then stop
886 // here. Don't reset |isShrinkingFromZoomed_| since we might get called
887 // again for the same shrink.
888 if (isShrinkingFromZoomed_ && !didChange)
891 isShrinkingFromZoomed_ = NO;
893 // Don't bother with anything else.
898 // Shrinking from zoomed is handled above (and is constrained by
899 // |window...Growth_|).
900 if (!isShrinkingFromZoomed_) {
901 // Resize the window down until it hits the bottom of the workarea, then if
902 // needed continue resizing upwards. Do not resize the window to be taller
903 // than the current workarea.
904 // Resize the window as requested, keeping the top left corner fixed.
905 windowFrame.origin.y -= deltaH;
906 windowFrame.size.height += deltaH;
908 // If the bottom left corner is now outside the visible frame, move the
909 // window up to make it fit, but make sure not to move the top left corner
910 // out of the visible frame.
911 if (windowFrame.origin.y < workarea.origin.y) {
912 windowFrame.origin.y = workarea.origin.y;
913 windowFrame.size.height =
914 std::min(NSHeight(windowFrame), NSHeight(workarea));
917 // Record (if applicable) how much we grew the window in either direction.
918 // (N.B.: These only record growth, not shrinkage.)
919 if (NSMaxY(windowFrame) > oldWindowMaxY)
920 windowTopGrowth_ += NSMaxY(windowFrame) - oldWindowMaxY;
921 if (NSMinY(windowFrame) < oldWindowMinY)
922 windowBottomGrowth_ += oldWindowMinY - NSMinY(windowFrame);
925 // Disable subview resizing while resizing the window, or else we will get
926 // unwanted renderer resizes. The calling code must call layoutSubviews to
927 // make things right again.
928 NSView* chromeContentView = [self chromeContentView];
929 BOOL autoresizesSubviews = [chromeContentView autoresizesSubviews];
930 [chromeContentView setAutoresizesSubviews:NO];
931 [window setFrame:windowFrame display:NO];
932 [chromeContentView setAutoresizesSubviews:autoresizesSubviews];
936 // Main method to resize browser window subviews. This method should be called
937 // when resizing any child of the content view, rather than resizing the views
938 // directly. If the view is already the correct height, does not force a
940 - (void)resizeView:(NSView*)view newHeight:(CGFloat)height {
941 // We should only ever be called for one of the following four views.
942 // |downloadShelfController_| may be nil. If we are asked to size the bookmark
943 // bar directly, its superview must be this controller's content view.
945 DCHECK(view == [toolbarController_ view] ||
946 view == [infoBarContainerController_ view] ||
947 view == [downloadShelfController_ view] ||
948 view == [bookmarkBarController_ view]);
950 // The infobar has insufficient information to determine its new height. It
951 // knows the total height of all of the info bars (which is what it passes
952 // into this method), but knows nothing about the maximum arrow height, which
953 // is determined by this class.
954 if (view == [infoBarContainerController_ view]) {
955 base::scoped_nsobject<BrowserWindowLayout> layout(
956 [[BrowserWindowLayout alloc] init]);
957 [self updateLayoutParameters:layout];
958 // Use the new height for the info bar.
959 [layout setInfoBarHeight:height];
961 chrome::LayoutOutput output = [layout computeLayout];
963 height = NSHeight(output.infoBarFrame);
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 // Update a toggle state for an NSMenuItem if modified.
1018 // Take care to ensure |item| looks like a NSMenuItem.
1019 // Called by validateUserInterfaceItem:.
1020 - (void)updateToggleStateWithTag:(NSInteger)tag forItem:(id)item {
1021 if (![item respondsToSelector:@selector(state)] ||
1022 ![item respondsToSelector:@selector(setState:)])
1025 // On Windows this logic happens in bookmark_bar_view.cc. On the
1026 // Mac we're a lot more MVC happy so we've moved it into a
1027 // controller. To be clear, this simply updates the menu item; it
1028 // does not display the bookmark bar itself.
1029 if (tag == IDC_SHOW_BOOKMARK_BAR) {
1030 bool toggled = windowShim_->IsBookmarkBarVisible();
1031 NSInteger oldState = [(NSMenuItem*)item state];
1032 NSInteger newState = toggled ? NSOnState : NSOffState;
1033 if (oldState != newState)
1034 [item setState:newState];
1037 // Update the checked/Unchecked state of items in the encoding menu.
1038 // On Windows, this logic is part of |EncodingMenuModel| in
1039 // browser/ui/views/toolbar_view.h.
1040 EncodingMenuController encoding_controller;
1041 if (encoding_controller.DoesCommandBelongToEncodingMenu(tag)) {
1042 DCHECK(browser_.get());
1043 Profile* profile = browser_->profile();
1045 WebContents* current_tab =
1046 browser_->tab_strip_model()->GetActiveWebContents();
1050 const std::string encoding = current_tab->GetEncoding();
1052 bool toggled = encoding_controller.IsItemChecked(profile, encoding, tag);
1053 NSInteger oldState = [(NSMenuItem*)item state];
1054 NSInteger newState = toggled ? NSOnState : NSOffState;
1055 if (oldState != newState)
1056 [item setState:newState];
1060 // Called to validate menu and toolbar items when this window is key. All the
1061 // items we care about have been set with the |-commandDispatch:| or
1062 // |-commandDispatchUsingKeyModifiers:| actions and a target of FirstResponder
1063 // in IB. If it's not one of those, let it continue up the responder chain to be
1064 // handled elsewhere. We pull out the tag as the cross-platform constant to
1065 // differentiate and dispatch the various commands.
1066 // NOTE: we might have to handle state for app-wide menu items,
1067 // although we could cheat and directly ask the app controller if our
1068 // command_updater doesn't support the command. This may or may not be an issue,
1069 // too early to tell.
1070 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
1071 SEL action = [item action];
1073 if (action == @selector(commandDispatch:) ||
1074 action == @selector(commandDispatchUsingKeyModifiers:)) {
1075 NSInteger tag = [item tag];
1076 if (chrome::SupportsCommand(browser_.get(), tag)) {
1077 // Generate return value (enabled state)
1078 enable = chrome::IsCommandEnabled(browser_.get(), tag);
1081 // Disable "close tab" if the receiving window is not tabbed.
1082 // We simply check whether the item has a keyboard shortcut set here;
1083 // app_controller_mac.mm actually determines whether the item should
1085 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item))
1086 enable &= !![[menuItem keyEquivalent] length];
1088 case IDC_FULLSCREEN: {
1089 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item)) {
1090 NSString* menuTitle = l10n_util::GetNSString(
1091 [self isInAppKitFullscreen] && ![self inPresentationMode]
1092 ? IDS_EXIT_FULLSCREEN_MAC
1093 : IDS_ENTER_FULLSCREEN_MAC);
1094 [menuItem setTitle:menuTitle];
1096 if (!chrome::mac::SupportsSystemFullscreen())
1097 [menuItem setHidden:YES];
1101 case IDC_PRESENTATION_MODE: {
1102 if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item)) {
1103 NSString* menuTitle = l10n_util::GetNSString(
1104 [self inPresentationMode] ? IDS_EXIT_PRESENTATION_MAC :
1105 IDS_ENTER_PRESENTATION_MAC);
1106 [menuItem setTitle:menuTitle];
1110 case IDC_SHOW_SIGNIN: {
1111 Profile* original_profile =
1112 browser_->profile()->GetOriginalProfile();
1113 [AppController updateSigninItem:item
1115 currentProfile:original_profile];
1118 case IDC_BOOKMARK_PAGE: {
1119 // Extensions have the ability to hide the bookmark page menu item.
1120 // This only affects the bookmark page menu item under the main menu.
1121 // The bookmark page menu item under the wrench menu has its
1122 // visibility controlled by WrenchMenuModel.
1124 chrome::ShouldRemoveBookmarkThisPageUI(browser_->profile());
1125 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
1126 [menuItem setHidden:shouldHide];
1129 case IDC_BOOKMARK_ALL_TABS: {
1130 // Extensions have the ability to hide the bookmark all tabs menu
1131 // item. This only affects the bookmark page menu item under the main
1132 // menu. The bookmark page menu item under the wrench menu has its
1133 // visibility controlled by WrenchMenuModel.
1135 chrome::ShouldRemoveBookmarkOpenPagesUI(browser_->profile());
1136 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
1137 [menuItem setHidden:shouldHide];
1141 // Special handling for the contents of the Text Encoding submenu. On
1142 // Mac OS, instead of enabling/disabling the top-level menu item, we
1143 // enable/disable the submenu's contents (per Apple's HIG).
1144 EncodingMenuController encoding_controller;
1145 if (encoding_controller.DoesCommandBelongToEncodingMenu(tag)) {
1146 enable &= chrome::IsCommandEnabled(browser_.get(),
1147 IDC_ENCODING_MENU) ? YES : NO;
1151 // If the item is toggleable, find its toggle state and
1152 // try to update it. This is a little awkward, but the alternative is
1153 // to check after a commandDispatch, which seems worse.
1154 [self updateToggleStateWithTag:tag forItem:item];
1160 // Called when the user picks a menu or toolbar item when this window is key.
1161 // Calls through to the browser object to execute the command. This assumes that
1162 // the command is supported and doesn't check, otherwise it would have been
1163 // disabled in the UI in validateUserInterfaceItem:.
1164 - (void)commandDispatch:(id)sender {
1166 // Identify the actual BWC to which the command should be dispatched. It might
1167 // belong to a background window, yet this controller gets it because it is
1168 // the foreground window's controller and thus in the responder chain. Some
1169 // senders don't have this problem (for example, menus only operate on the
1170 // foreground window), so this is only an issue for senders that are part of
1172 BrowserWindowController* targetController = self;
1173 if ([sender respondsToSelector:@selector(window)])
1174 targetController = [[sender window] windowController];
1175 DCHECK([targetController isKindOfClass:[BrowserWindowController class]]);
1176 DCHECK(targetController->browser_.get());
1177 chrome::ExecuteCommand(targetController->browser_.get(), [sender tag]);
1180 // Same as |-commandDispatch:|, but executes commands using a disposition
1181 // determined by the key flags. If the window is in the background and the
1182 // command key is down, ignore the command key, but process any other modifiers.
1183 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1186 if (![sender isEnabled]) {
1187 // This code is reachable e.g. if the user mashes the back button, queuing
1188 // up a bunch of events before the button's enabled state is updated:
1189 // http://crbug.com/63254
1193 // See comment above for why we do this.
1194 BrowserWindowController* targetController = self;
1195 if ([sender respondsToSelector:@selector(window)])
1196 targetController = [[sender window] windowController];
1197 DCHECK([targetController isKindOfClass:[BrowserWindowController class]]);
1198 DCHECK(targetController->browser_.get());
1200 NSInteger command = [sender tag];
1201 NSUInteger modifierFlags = [[NSApp currentEvent] modifierFlags];
1202 if ((command == IDC_RELOAD) &&
1203 (modifierFlags & (NSShiftKeyMask | NSControlKeyMask))) {
1204 command = IDC_RELOAD_IGNORING_CACHE;
1205 // Mask off Shift and Control so they don't affect the disposition below.
1206 modifierFlags &= ~(NSShiftKeyMask | NSControlKeyMask);
1208 if (![[sender window] isMainWindow]) {
1209 // Remove the command key from the flags, it means "keep the window in
1210 // the background" in this case.
1211 modifierFlags &= ~NSCommandKeyMask;
1213 chrome::ExecuteCommandWithDisposition(
1214 targetController->browser_.get(), command,
1215 ui::WindowOpenDispositionFromNSEventWithFlags(
1216 [NSApp currentEvent], modifierFlags));
1219 // Called when another part of the internal codebase needs to execute a
1221 - (void)executeCommand:(int)command {
1222 chrome::ExecuteCommand(browser_.get(), command);
1225 - (BOOL)handledByExtensionCommand:(NSEvent*)event
1226 priority:(ui::AcceleratorManager::HandlerPriority)priority {
1227 return extension_keybinding_registry_->ProcessKeyEvent(
1228 content::NativeWebKeyboardEvent(event), priority);
1231 // StatusBubble delegate method: tell the status bubble the frame it should
1232 // position itself in.
1233 - (NSRect)statusBubbleBaseFrame {
1234 NSView* view = [overlayableContentsController_ view];
1235 return [view convertRect:[view bounds] toView:nil];
1238 - (void)updateToolbarWithContents:(WebContents*)tab {
1239 [toolbarController_ updateToolbarWithContents:tab];
1242 - (void)resetTabState:(WebContents*)tab {
1243 [toolbarController_ resetTabState:tab];
1246 - (void)setStarredState:(BOOL)isStarred {
1247 [toolbarController_ setStarredState:isStarred];
1250 - (void)setCurrentPageIsTranslated:(BOOL)on {
1251 [toolbarController_ setTranslateIconLit:on];
1254 - (void)zoomChangedForActiveTab:(BOOL)canShowBubble {
1255 [toolbarController_ zoomChangedForActiveTab:canShowBubble];
1258 // Return the rect, in WebKit coordinates (flipped), of the window's grow box
1259 // in the coordinate system of the content area of the currently selected tab.
1260 // |windowGrowBox| needs to be in the window's coordinate system.
1261 - (NSRect)selectedTabGrowBoxRect {
1262 NSWindow* window = [self window];
1263 if (![window respondsToSelector:@selector(_growBoxRect)])
1266 // Before we return a rect, we need to convert it from window coordinates
1267 // to tab content area coordinates and flip the coordinate system.
1268 NSRect growBoxRect =
1269 [[self tabContentArea] convertRect:[window _growBoxRect] fromView:nil];
1270 growBoxRect.origin.y =
1271 NSHeight([[self tabContentArea] frame]) - NSMaxY(growBoxRect);
1275 // Accept tabs from a BrowserWindowController with the same Profile.
1276 - (BOOL)canReceiveFrom:(TabWindowController*)source {
1277 BrowserWindowController* realSource =
1278 base::mac::ObjCCast<BrowserWindowController>(source);
1279 if (!realSource || browser_->profile() != realSource->browser_->profile()) {
1283 // Can't drag a tab from a normal browser to a pop-up
1284 if (browser_->type() != realSource->browser_->type()) {
1291 // Move a given tab view to the location of the current placeholder. If there is
1292 // no placeholder, it will go at the end. |controller| is the window controller
1293 // of a tab being dropped from a different window. It will be nil if the drag is
1294 // within the window, otherwise the tab is removed from that window before being
1295 // placed into this one. The implementation will call |-removePlaceholder| since
1296 // the drag is now complete. This also calls |-layoutTabs| internally so
1297 // clients do not need to call it again.
1298 - (void)moveTabViews:(NSArray*)views
1299 fromController:(TabWindowController*)dragController {
1300 if (dragController) {
1301 // Moving between windows.
1302 NSView* activeTabView = [dragController activeTabView];
1303 BrowserWindowController* dragBWC =
1304 base::mac::ObjCCastStrict<BrowserWindowController>(dragController);
1306 // We will drop the tabs starting at indexOfPlaceholder, and increment from
1307 // there. We remove the placehoder before dropping the tabs, so that the
1308 // new tab animation's destination frame is correct.
1309 int tabIndex = [tabStripController_ indexOfPlaceholder];
1310 [self removePlaceholder];
1312 for (NSView* view in views) {
1313 // Figure out the WebContents to drop into our tab model from the source
1315 int index = [dragBWC->tabStripController_ modelIndexForTabView:view];
1316 WebContents* contents =
1317 dragBWC->browser_->tab_strip_model()->GetWebContentsAt(index);
1318 // The tab contents may have gone away if given a window.close() while it
1319 // is being dragged. If so, bail, we've got nothing to drop.
1323 // Convert |view|'s frame (which starts in the source tab strip's
1324 // coordinate system) to the coordinate system of the destination tab
1325 // strip. This needs to be done before being detached so the window
1326 // transforms can be performed.
1327 NSRect destinationFrame = [view frame];
1328 NSPoint tabOrigin = destinationFrame.origin;
1329 tabOrigin = [[dragController tabStripView] convertPoint:tabOrigin
1331 tabOrigin = [[dragController window] convertBaseToScreen:tabOrigin];
1332 tabOrigin = [[self window] convertScreenToBase:tabOrigin];
1333 tabOrigin = [[self tabStripView] convertPoint:tabOrigin fromView:nil];
1334 destinationFrame.origin = tabOrigin;
1336 // Before the tab is detached from its originating tab strip, store the
1337 // pinned state so that it can be maintained between the windows.
1338 bool isPinned = dragBWC->browser_->tab_strip_model()->IsTabPinned(index);
1340 // Now that we have enough information about the tab, we can remove it
1341 // from the dragging window. We need to do this *before* we add it to the
1342 // new window as this will remove the WebContents' delegate.
1343 [dragController detachTabView:view];
1345 // Deposit it into our model at the appropriate location (it already knows
1346 // where it should go from tracking the drag). Doing this sets the tab's
1347 // delegate to be the Browser.
1348 [tabStripController_ dropWebContents:contents
1350 withFrame:destinationFrame
1351 asPinnedTab:isPinned
1352 activate:view == activeTabView];
1355 // Moving within a window.
1356 for (NSView* view in views) {
1357 int index = [tabStripController_ modelIndexForTabView:view];
1358 [tabStripController_ moveTabFromIndex:index];
1360 [self removePlaceholder];
1364 // Tells the tab strip to forget about this tab in preparation for it being
1365 // put into a different tab strip, such as during a drop on another window.
1366 - (void)detachTabView:(NSView*)view {
1367 int index = [tabStripController_ modelIndexForTabView:view];
1368 browser_->tab_strip_model()->DetachWebContentsAt(index);
1371 - (NSArray*)tabViews {
1372 return [tabStripController_ tabViews];
1375 - (NSView*)activeTabView {
1376 return [tabStripController_ activeTabView];
1379 - (void)setIsLoading:(BOOL)isLoading force:(BOOL)force {
1380 [toolbarController_ setIsLoading:isLoading force:force];
1383 // Make the location bar the first responder, if possible.
1384 - (void)focusLocationBar:(BOOL)selectAll {
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 isInAnyFullscreenMode];
1502 - (BOOL)windowMovementAllowed {
1503 return ![self isInAnyFullscreenMode];
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 - (void)createAndAddDownloadShelf {
1557 if (!downloadShelfController_.get()) {
1558 downloadShelfController_.reset([[DownloadShelfController alloc]
1559 initWithBrowser:browser_.get() resizeDelegate:self]);
1560 [self.chromeContentView addSubview:[downloadShelfController_ view]];
1564 - (DownloadShelfController*)downloadShelf {
1565 return downloadShelfController_;
1568 - (void)addFindBar:(FindBarCocoaController*)findBarCocoaController {
1569 // Shouldn't call addFindBar twice.
1570 DCHECK(!findBarCocoaController_.get());
1572 // Create a controller for the findbar.
1573 findBarCocoaController_.reset([findBarCocoaController retain]);
1574 [self layoutSubviews];
1575 [self updateSubviewZOrder];
1578 - (NSWindow*)createFullscreenWindow {
1579 return [[[FullscreenWindow alloc] initForScreen:[[self window] screen]]
1583 - (NSInteger)numberOfTabs {
1584 // count() includes pinned tabs.
1585 return browser_->tab_strip_model()->count();
1588 - (BOOL)hasLiveTabs {
1589 return !browser_->tab_strip_model()->empty();
1592 - (NSString*)activeTabTitle {
1593 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1594 return base::SysUTF16ToNSString(contents->GetTitle());
1597 - (NSRect)regularWindowFrame {
1598 return [self isInAnyFullscreenMode] ? savedRegularWindowFrame_
1599 : [[self window] frame];
1602 // (Override of |TabWindowController| method.)
1603 - (BOOL)hasTabStrip {
1604 return [self supportsWindowFeature:Browser::FEATURE_TABSTRIP];
1607 - (BOOL)isTabDraggable:(NSView*)tabView {
1608 // TODO(avi, thakis): ConstrainedWindowSheetController has no api to move
1609 // tabsheets between windows. Until then, we have to prevent having to move a
1610 // tabsheet between windows, e.g. no tearing off of tabs.
1611 int index = [tabStripController_ modelIndexForTabView:tabView];
1612 WebContents* contents = browser_->tab_strip_model()->GetWebContentsAt(index);
1616 return !web_modal::PopupManager::FromWebContents(contents)->
1617 IsWebModalDialogActive(contents);
1620 // TabStripControllerDelegate protocol.
1621 - (void)onActivateTabWithContents:(WebContents*)contents {
1622 // Update various elements that are interested in knowing the current
1625 // Update all the UI bits.
1626 windowShim_->UpdateTitleBar();
1628 // Update the bookmark bar.
1629 // TODO(viettrungluu): perhaps update to not terminate running animations (if
1631 windowShim_->BookmarkBarStateChanged(
1632 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
1634 [infoBarContainerController_ changeWebContents:contents];
1636 // No need to remove previous bubble. It will close itself.
1637 // TODO(leng): The PermissionBubbleManager for the previous contents should
1638 // have SetView(NULL) called. Fix this when the previous contents are
1639 // available here or move to BrowserWindowCocoa::OnActiveTabChanged().
1641 PermissionBubbleManager::FromWebContents(contents)->SetView(
1642 permissionBubbleCocoa_.get());
1644 // Must do this after bookmark and infobar updates to avoid
1645 // unnecesary resize in contents.
1646 [devToolsController_ updateDevToolsForWebContents:contents
1647 withProfile:browser_->profile()];
1650 - (void)onTabChanged:(TabStripModelObserver::TabChangeType)change
1651 withContents:(WebContents*)contents {
1652 // Update titles if this is the currently selected tab and if it isn't just
1653 // the loading state which changed.
1654 if (change != TabStripModelObserver::LOADING_ONLY)
1655 windowShim_->UpdateTitleBar();
1657 // Update the bookmark bar if this is the currently selected tab and if it
1658 // isn't just the title which changed. This for transitions between the NTP
1659 // (showing its floating bookmark bar) and normal web pages (showing no
1661 // TODO(viettrungluu): perhaps update to not terminate running animations?
1662 if (change != TabStripModelObserver::TITLE_NOT_LOADING) {
1663 windowShim_->BookmarkBarStateChanged(
1664 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
1668 - (void)onTabDetachedWithContents:(WebContents*)contents {
1669 [infoBarContainerController_ tabDetachedWithContents:contents];
1672 - (void)userChangedTheme {
1673 NSView* rootView = [[[self window] contentView] superview];
1674 [rootView cr_recursivelyInvokeBlock:^(id view) {
1675 if ([view conformsToProtocol:@protocol(ThemedWindowDrawing)])
1676 [view windowDidChangeTheme];
1678 // TODO(andresantoso): Remove this once all themed views respond to
1679 // windowDidChangeTheme above.
1680 [view setNeedsDisplay:YES];
1684 - (ui::ThemeProvider*)themeProvider {
1685 return ThemeServiceFactory::GetForProfile(browser_->profile());
1688 - (ThemedWindowStyle)themedWindowStyle {
1689 ThemedWindowStyle style = 0;
1690 if (browser_->profile()->IsOffTheRecord())
1691 style |= THEMED_INCOGNITO;
1693 if (browser_->is_devtools())
1694 style |= THEMED_DEVTOOLS;
1695 if (browser_->is_type_popup())
1696 style |= THEMED_POPUP;
1701 - (NSPoint)themeImagePositionForAlignment:(ThemeImageAlignment)alignment {
1702 NSView* windowChromeView = [[[self window] contentView] superview];
1703 NSView* tabStripView = nil;
1704 if ([self hasTabStrip])
1705 tabStripView = [self tabStripView];
1706 return [BrowserWindowUtils themeImagePositionFor:windowChromeView
1707 withTabStrip:tabStripView
1708 alignment:alignment];
1711 - (NSPoint)bookmarkBubblePoint {
1712 return [toolbarController_ bookmarkBubblePoint];
1715 // Show the bookmark bubble (e.g. user just clicked on the STAR).
1716 - (void)showBookmarkBubbleForURL:(const GURL&)url
1717 alreadyBookmarked:(BOOL)alreadyMarked {
1718 if (!bookmarkBubbleController_) {
1719 BookmarkModel* model =
1720 BookmarkModelFactory::GetForProfile(browser_->profile());
1721 ChromeBookmarkClient* client =
1722 ChromeBookmarkClientFactory::GetForProfile(browser_->profile());
1723 const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(url);
1724 bookmarkBubbleController_ =
1725 [[BookmarkBubbleController alloc] initWithParentWindow:[self window]
1729 alreadyBookmarked:alreadyMarked];
1730 [bookmarkBubbleController_ showWindow:self];
1731 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1732 [center addObserver:self
1733 selector:@selector(bookmarkBubbleWindowWillClose:)
1734 name:NSWindowWillCloseNotification
1735 object:[bookmarkBubbleController_ window]];
1739 // Nil out the weak bookmark bubble controller reference.
1740 - (void)bookmarkBubbleWindowWillClose:(NSNotification*)notification {
1741 DCHECK_EQ([notification object], [bookmarkBubbleController_ window]);
1743 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1744 [center removeObserver:self
1745 name:NSWindowWillCloseNotification
1746 object:[bookmarkBubbleController_ window]];
1747 bookmarkBubbleController_ = nil;
1750 // Handle the editBookmarkNode: action sent from bookmark bubble controllers.
1751 - (void)editBookmarkNode:(id)sender {
1752 BOOL responds = [sender respondsToSelector:@selector(node)];
1755 const BookmarkNode* node = [sender node];
1757 BookmarkEditor::Show([self window], browser_->profile(),
1758 BookmarkEditor::EditDetails::EditNode(node),
1759 BookmarkEditor::SHOW_TREE);
1763 - (void)showTranslateBubbleForWebContents:(content::WebContents*)contents
1764 step:(translate::TranslateStep)step
1765 errorType:(translate::TranslateErrors::Type)
1767 // TODO(hajimehoshi): The similar logic exists at TranslateBubbleView::
1768 // ShowBubble. This should be unified.
1769 if (translateBubbleController_) {
1770 // When the user reads the advanced setting panel, the bubble should not be
1771 // changed because he/she is focusing on the bubble.
1772 if (translateBubbleController_.webContents == contents &&
1773 translateBubbleController_.model->GetViewState() ==
1774 TranslateBubbleModel::VIEW_STATE_ADVANCED) {
1777 if (step != translate::TRANSLATE_STEP_TRANSLATE_ERROR) {
1778 TranslateBubbleModel::ViewState viewState =
1779 TranslateBubbleModelImpl::TranslateStepToViewState(step);
1780 [translateBubbleController_ switchView:viewState];
1782 [translateBubbleController_ switchToErrorView:errorType];
1787 std::string sourceLanguage;
1788 std::string targetLanguage;
1789 ChromeTranslateClient::GetTranslateLanguages(
1790 contents, &sourceLanguage, &targetLanguage);
1792 scoped_ptr<translate::TranslateUIDelegate> uiDelegate(
1793 new translate::TranslateUIDelegate(
1794 ChromeTranslateClient::GetManagerFromWebContents(contents)
1798 scoped_ptr<TranslateBubbleModel> model(
1799 new TranslateBubbleModelImpl(step, uiDelegate.Pass()));
1800 translateBubbleController_ = [[TranslateBubbleController alloc]
1801 initWithParentWindow:self
1803 webContents:contents];
1804 [translateBubbleController_ showWindow:nil];
1806 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1807 [center addObserver:self
1808 selector:@selector(translateBubbleWindowWillClose:)
1809 name:NSWindowWillCloseNotification
1810 object:[translateBubbleController_ window]];
1813 // Nil out the weak translate bubble controller reference.
1814 - (void)translateBubbleWindowWillClose:(NSNotification*)notification {
1815 DCHECK_EQ([notification object], [translateBubbleController_ window]);
1817 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1818 [center removeObserver:self
1819 name:NSWindowWillCloseNotification
1820 object:[translateBubbleController_ window]];
1821 translateBubbleController_ = nil;
1824 // If the browser is in incognito mode or has multi-profiles, install the image
1825 // view to decorate the window at the upper right. Use the same base y
1826 // coordinate as the tab strip.
1827 - (void)installAvatar {
1828 // Install the image into the badge view. Hide it for now; positioning and
1829 // sizing will be done by the layout code. The AvatarIcon will choose which
1830 // image to display based on the browser. The AvatarButton will display
1831 // the browser profile's name unless the browser is incognito.
1833 if ([self shouldUseNewAvatarButton]) {
1834 avatarButtonController_.reset(
1835 [[AvatarButtonController alloc] initWithBrowser:browser_.get()]);
1837 avatarButtonController_.reset(
1838 [[AvatarIconController alloc] initWithBrowser:browser_.get()]);
1840 view = [avatarButtonController_ view];
1841 [view setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
1842 [view setHidden:![self shouldShowAvatar]];
1844 // Install the view.
1845 [[[self window] contentView] addSubview:view];
1848 // Called when we get a three-finger swipe.
1849 - (void)swipeWithEvent:(NSEvent*)event {
1850 CGFloat deltaX = [event deltaX];
1851 CGFloat deltaY = [event deltaY];
1853 // Map forwards and backwards to history; left is positive, right is negative.
1854 unsigned int command = 0;
1857 } else if (deltaX < -0.5) {
1858 command = IDC_FORWARD;
1859 } else if (deltaY > 0.5) {
1860 // TODO(pinkerton): figure out page-up, http://crbug.com/16305
1861 } else if (deltaY < -0.5) {
1862 // TODO(pinkerton): figure out page-down, http://crbug.com/16305
1865 // Ensure the command is valid first (ExecuteCommand() won't do that) and
1867 if (chrome::IsCommandEnabled(browser_.get(), command)) {
1868 chrome::ExecuteCommandWithDisposition(
1871 ui::WindowOpenDispositionFromNSEvent(event));
1875 // Delegate method called when window is resized.
1876 - (void)windowDidResize:(NSNotification*)notification {
1877 [self saveWindowPositionIfNeeded];
1879 // Resize (and possibly move) the status bubble. Note that we may get called
1880 // when the status bubble does not exist.
1881 if (statusBubble_) {
1882 statusBubble_->UpdateSizeAndPosition();
1885 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
1886 if (WebContents* contents =
1887 browser_->tab_strip_model()->GetActiveWebContents()) {
1888 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
1889 rwhv->WindowFrameChanged();
1892 // The FindBar needs to know its own position to properly detect overlaps
1893 // with find results. The position changes whenever the window is resized,
1894 // and |layoutSubviews| computes the FindBar's position.
1895 // TODO: calling |layoutSubviews| here is a waste, find a better way to
1897 if ([findBarCocoaController_ isFindBarVisible])
1898 [self layoutSubviews];
1901 // Handle the openLearnMoreAboutCrashLink: action from SadTabController when
1902 // "Learn more" link in "Aw snap" page (i.e. crash page or sad tab) is
1903 // clicked. Decoupling the action from its target makes unit testing possible.
1904 - (void)openLearnMoreAboutCrashLink:(id)sender {
1905 if (SadTabController* sadTab =
1906 base::mac::ObjCCast<SadTabController>(sender)) {
1907 WebContents* webContents = [sadTab webContents];
1909 OpenURLParams params(
1910 GURL(chrome::kCrashReasonURL), Referrer(), CURRENT_TAB,
1911 ui::PAGE_TRANSITION_LINK, false);
1912 webContents->OpenURL(params);
1917 // Delegate method called when window did move. (See below for why we don't use
1918 // |-windowWillMove:|, which is called less frequently than |-windowDidMove|
1920 - (void)windowDidMove:(NSNotification*)notification {
1921 [self saveWindowPositionIfNeeded];
1923 NSWindow* window = [self window];
1924 NSRect windowFrame = [window frame];
1925 NSRect workarea = [[window screen] visibleFrame];
1927 // We reset the window growth state whenever the window is moved out of the
1928 // work area or away (up or down) from the bottom or top of the work area.
1929 // Unfortunately, Cocoa sends |-windowWillMove:| too frequently (including
1930 // when clicking on the title bar to activate), and of course
1931 // |-windowWillMove| is called too early for us to apply our heuristic. (The
1932 // heuristic we use for detecting window movement is that if |windowTopGrowth_
1933 // > 0|, then we should be at the bottom of the work area -- if we're not,
1934 // we've moved. Similarly for the other side.)
1935 if (!NSContainsRect(workarea, windowFrame) ||
1936 (windowTopGrowth_ > 0 && NSMinY(windowFrame) != NSMinY(workarea)) ||
1937 (windowBottomGrowth_ > 0 && NSMaxY(windowFrame) != NSMaxY(workarea)))
1938 [self resetWindowGrowthState];
1940 // Let the selected RenderWidgetHostView know, so that it can tell plugins.
1941 if (WebContents* contents =
1942 browser_->tab_strip_model()->GetActiveWebContents()) {
1943 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
1944 rwhv->WindowFrameChanged();
1948 // Delegate method called when window will be resized; not called for
1949 // |-setFrame:display:|.
1950 - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize {
1951 [self resetWindowGrowthState];
1955 // Delegate method: see |NSWindowDelegate| protocol.
1956 - (id)windowWillReturnFieldEditor:(NSWindow*)sender toObject:(id)obj {
1957 // Ask the toolbar controller if it wants to return a custom field editor
1958 // for the specific object.
1959 return [toolbarController_ customFieldEditorForObject:obj];
1962 // (Needed for |BookmarkBarControllerDelegate| protocol.)
1963 - (void)bookmarkBar:(BookmarkBarController*)controller
1964 didChangeFromState:(BookmarkBar::State)oldState
1965 toState:(BookmarkBar::State)newState {
1966 [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
1967 [self adjustToolbarAndBookmarkBarForCompression:
1968 [controller getDesiredToolbarHeightCompression]];
1971 // (Needed for |BookmarkBarControllerDelegate| protocol.)
1972 - (void)bookmarkBar:(BookmarkBarController*)controller
1973 willAnimateFromState:(BookmarkBar::State)oldState
1974 toState:(BookmarkBar::State)newState {
1975 [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
1976 [self adjustToolbarAndBookmarkBarForCompression:
1977 [controller getDesiredToolbarHeightCompression]];
1980 // (Private/TestingAPI)
1981 - (void)resetWindowGrowthState {
1982 windowTopGrowth_ = 0;
1983 windowBottomGrowth_ = 0;
1984 isShrinkingFromZoomed_ = NO;
1987 - (NSSize)overflowFrom:(NSRect)source
1989 // If |source|'s boundary is outside of |target|'s, set its distance
1990 // to |x|. Note that |source| can overflow to both side, but we
1991 // have nothing to do for such case.
1993 if (NSMaxX(target) < NSMaxX(source)) // |source| overflows to right
1994 x = NSMaxX(source) - NSMaxX(target);
1995 else if (NSMinX(source) < NSMinX(target)) // |source| overflows to left
1996 x = NSMinX(source) - NSMinX(target);
1998 // Same as |x| above.
2000 if (NSMaxY(target) < NSMaxY(source))
2001 y = NSMaxY(source) - NSMaxY(target);
2002 else if (NSMinY(source) < NSMinY(target))
2003 y = NSMinY(source) - NSMinY(target);
2005 return NSMakeSize(x, y);
2008 // (Private/TestingAPI)
2009 - (ExclusiveAccessBubbleWindowController*)
2010 exclusiveAccessBubbleWindowController {
2011 return exclusiveAccessBubbleWindowController_.get();
2014 - (NSRect)omniboxPopupAnchorRect {
2015 // Start with toolbar rect.
2016 NSView* toolbarView = [toolbarController_ view];
2017 NSRect anchorRect = [toolbarView frame];
2019 // Adjust to account for height and possible bookmark bar. Compress by 1
2020 // to account for the separator.
2021 anchorRect.origin.y =
2022 NSMaxY(anchorRect) - [toolbarController_ desiredHeightForCompression:1];
2024 // Shift to window base coordinates.
2025 return [[toolbarView superview] convertRect:anchorRect toView:nil];
2028 - (void)sheetDidEnd:(NSWindow*)sheet
2029 returnCode:(NSInteger)code
2030 context:(void*)context {
2031 [sheet orderOut:self];
2034 - (void)executeExtensionCommand:(const std::string&)extension_id
2035 command:(const extensions::Command&)command {
2036 // Global commands are handled by the ExtensionCommandsGlobalRegistry
2038 DCHECK(!command.global());
2039 extension_keybinding_registry_->ExecuteCommand(extension_id,
2040 command.accelerator());
2043 @end // @implementation BrowserWindowController
2045 @implementation BrowserWindowController(Fullscreen)
2047 - (void)handleLionToggleFullscreen {
2048 DCHECK(base::mac::IsOSLionOrLater());
2049 chrome::ExecuteCommand(browser_.get(), IDC_FULLSCREEN);
2052 - (void)enterBrowserFullscreenWithToolbar:(BOOL)withToolbar {
2053 if (!chrome::mac::SupportsSystemFullscreen()) {
2054 if (![self isInImmersiveFullscreen])
2055 [self enterImmersiveFullscreen];
2059 if ([self isInAppKitFullscreen]) {
2060 [self updateFullscreenWithToolbar:withToolbar];
2062 // Need to invoke AppKit Fullscreen API. Presentation mode (if set) will
2063 // automatically be enabled in |-windowWillEnterFullScreen:|.
2064 enteringPresentationMode_ = !withToolbar;
2065 [self enterAppKitFullscreen];
2069 - (void)updateFullscreenWithToolbar:(BOOL)withToolbar {
2070 [self adjustUIForSlidingFullscreenStyle:
2071 withToolbar ? fullscreen_mac::OMNIBOX_TABS_PRESENT
2072 : fullscreen_mac::OMNIBOX_TABS_HIDDEN];
2075 - (void)updateFullscreenExitBubbleURL:(const GURL&)url
2076 bubbleType:(ExclusiveAccessBubbleType)bubbleType {
2077 fullscreenUrl_ = url;
2078 exclusiveAccessBubbleType_ = bubbleType;
2079 [self layoutSubviews];
2080 [self showFullscreenExitBubbleIfNecessary];
2083 - (BOOL)isInAnyFullscreenMode {
2084 return [self isInImmersiveFullscreen] || [self isInAppKitFullscreen];
2087 - (BOOL)isInImmersiveFullscreen {
2088 return fullscreenWindow_.get() != nil || enteringImmersiveFullscreen_;
2091 - (BOOL)isInAppKitFullscreen {
2092 return ([[self window] styleMask] & NSFullScreenWindowMask) ==
2093 NSFullScreenWindowMask ||
2094 enteringAppKitFullscreen_;
2097 - (void)enterExtensionFullscreenForURL:(const GURL&)url
2098 bubbleType:(ExclusiveAccessBubbleType)bubbleType {
2099 if (chrome::mac::SupportsSystemFullscreen()) {
2100 fullscreenUrl_ = url;
2101 exclusiveAccessBubbleType_ = bubbleType;
2102 [self enterBrowserFullscreenWithToolbar:NO];
2104 [self enterImmersiveFullscreen];
2105 DCHECK(!url.is_empty());
2106 [self updateFullscreenExitBubbleURL:url bubbleType:bubbleType];
2110 - (void)enterWebContentFullscreenForURL:(const GURL&)url
2111 bubbleType:(ExclusiveAccessBubbleType)bubbleType {
2112 [self enterImmersiveFullscreen];
2113 if (!url.is_empty())
2114 [self updateFullscreenExitBubbleURL:url bubbleType:bubbleType];
2117 - (void)exitAnyFullscreen {
2118 // TODO(erikchen): Fullscreen modes should stack. Should be able to exit
2119 // Immersive Fullscreen and still be in AppKit Fullscreen.
2120 if ([self isInAppKitFullscreen])
2121 [self exitAppKitFullscreen];
2122 if ([self isInImmersiveFullscreen])
2123 [self exitImmersiveFullscreen];
2126 - (BOOL)inPresentationMode {
2127 return presentationModeController_.get() &&
2128 [presentationModeController_ inPresentationMode] &&
2129 presentationModeController_.get().slidingStyle ==
2130 fullscreen_mac::OMNIBOX_TABS_HIDDEN;
2133 - (void)resizeFullscreenWindow {
2134 DCHECK([self isInAnyFullscreenMode]);
2135 if (![self isInAnyFullscreenMode])
2138 NSWindow* window = [self window];
2139 [window setFrame:[[window screen] frame] display:YES];
2140 [self layoutSubviews];
2143 - (BOOL)isBarVisibilityLockedForOwner:(id)owner {
2145 DCHECK(barVisibilityLocks_);
2146 return [barVisibilityLocks_ containsObject:owner];
2149 - (void)lockBarVisibilityForOwner:(id)owner
2150 withAnimation:(BOOL)animate
2152 if (![self isBarVisibilityLockedForOwner:owner]) {
2153 [barVisibilityLocks_ addObject:owner];
2155 // If enabled, show the overlay if necessary (and if in presentation mode).
2156 if (barVisibilityUpdatesEnabled_) {
2157 [presentationModeController_ ensureOverlayShownWithAnimation:animate
2163 - (void)releaseBarVisibilityForOwner:(id)owner
2164 withAnimation:(BOOL)animate
2166 if ([self isBarVisibilityLockedForOwner:owner]) {
2167 [barVisibilityLocks_ removeObject:owner];
2169 // If enabled, hide the overlay if necessary (and if in presentation mode).
2170 if (barVisibilityUpdatesEnabled_ &&
2171 ![barVisibilityLocks_ count]) {
2172 [presentationModeController_ ensureOverlayHiddenWithAnimation:animate
2178 - (BOOL)floatingBarHasFocus {
2179 NSResponder* focused = [[self window] firstResponder];
2180 return [focused isKindOfClass:[AutocompleteTextFieldEditor class]];
2183 @end // @implementation BrowserWindowController(Fullscreen)
2186 @implementation BrowserWindowController(WindowType)
2188 - (BOOL)supportsWindowFeature:(int)feature {
2189 return browser_->SupportsWindowFeature(
2190 static_cast<Browser::WindowFeature>(feature));
2193 - (BOOL)hasTitleBar {
2194 return [self supportsWindowFeature:Browser::FEATURE_TITLEBAR];
2197 - (BOOL)hasToolbar {
2198 return [self supportsWindowFeature:Browser::FEATURE_TOOLBAR];
2201 - (BOOL)hasLocationBar {
2202 return [self supportsWindowFeature:Browser::FEATURE_LOCATIONBAR];
2205 - (BOOL)supportsBookmarkBar {
2206 return [self supportsWindowFeature:Browser::FEATURE_BOOKMARKBAR];
2209 - (BOOL)isTabbedWindow {
2210 return browser_->is_type_tabbed();
2213 @end // @implementation BrowserWindowController(WindowType)