1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CHROME_BROWSER_UI_COCOA_BROWSER_WINDOW_CONTROLLER_H_
6#define CHROME_BROWSER_UI_COCOA_BROWSER_WINDOW_CONTROLLER_H_
7
8// A class acting as the Objective-C controller for the Browser
9// object. Handles interactions between Cocoa and the cross-platform
10// code. Each window has a single toolbar and, by virtue of being a
11// TabWindowController, a tab strip along the top.
12
13#import <Cocoa/Cocoa.h>
14
15#include "base/mac/scoped_nsobject.h"
16#include "base/memory/scoped_ptr.h"
17#include "chrome/browser/translate/chrome_translate_client.h"
18#import "chrome/browser/ui/cocoa/bookmarks/bookmark_bar_controller.h"
19#import "chrome/browser/ui/cocoa/bookmarks/bookmark_bubble_controller.h"
20#import "chrome/browser/ui/cocoa/browser_command_executor.h"
21#import "chrome/browser/ui/cocoa/fullscreen_exit_bubble_controller.h"
22#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
23#import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
24#import "chrome/browser/ui/cocoa/themed_window.h"
25#import "chrome/browser/ui/cocoa/url_drop_target.h"
26#import "chrome/browser/ui/cocoa/view_resizer.h"
27#include "components/translate/core/common/translate_errors.h"
28#include "ui/gfx/rect.h"
29
30@class AvatarBaseController;
31class Browser;
32class BrowserWindow;
33class BrowserWindowCocoa;
34@class DevToolsController;
35@class DownloadShelfController;
36class ExtensionKeybindingRegistryCocoa;
37@class FindBarCocoaController;
38@class FullscreenModeController;
39@class FullscreenWindow;
40@class InfoBarContainerController;
41class LocationBarViewMac;
42@class OverlayableContentsController;
43class PermissionBubbleCocoa;
44@class PresentationModeController;
45class StatusBubbleMac;
46@class TabStripController;
47@class TabStripView;
48@class ToolbarController;
49@class TranslateBubbleController;
50
51namespace content {
52class WebContents;
53}
54
55namespace extensions {
56class Command;
57}
58
59@interface BrowserWindowController :
60  TabWindowController<NSUserInterfaceValidations,
61                      BookmarkBarControllerDelegate,
62                      BrowserCommandExecutor,
63                      ViewResizer,
64                      TabStripControllerDelegate> {
65 @private
66  // The ordering of these members is important as it determines the order in
67  // which they are destroyed. |browser_| needs to be destroyed last as most of
68  // the other objects hold weak references to it or things it owns
69  // (tab/toolbar/bookmark models, profiles, etc).
70  scoped_ptr<Browser> browser_;
71  NSWindow* savedRegularWindow_;
72  scoped_ptr<BrowserWindowCocoa> windowShim_;
73  base::scoped_nsobject<ToolbarController> toolbarController_;
74  base::scoped_nsobject<TabStripController> tabStripController_;
75  base::scoped_nsobject<FindBarCocoaController> findBarCocoaController_;
76  base::scoped_nsobject<InfoBarContainerController> infoBarContainerController_;
77  base::scoped_nsobject<DownloadShelfController> downloadShelfController_;
78  base::scoped_nsobject<BookmarkBarController> bookmarkBarController_;
79  base::scoped_nsobject<DevToolsController> devToolsController_;
80  base::scoped_nsobject<OverlayableContentsController>
81      overlayableContentsController_;
82  base::scoped_nsobject<PresentationModeController> presentationModeController_;
83  base::scoped_nsobject<FullscreenModeController> fullscreenModeController_;
84  base::scoped_nsobject<FullscreenExitBubbleController>
85      fullscreenExitBubbleController_;
86
87  // Strong. StatusBubble is a special case of a strong reference that
88  // we don't wrap in a scoped_ptr because it is acting the same
89  // as an NSWindowController in that it wraps a window that must
90  // be shut down before our destructors are called.
91  StatusBubbleMac* statusBubble_;
92
93  BookmarkBubbleController* bookmarkBubbleController_;  // Weak.
94  BOOL initializing_;  // YES while we are currently in initWithBrowser:
95  BOOL ownsBrowser_;  // Only ever NO when testing
96
97  TranslateBubbleController* translateBubbleController_;  // Weak.
98
99  // The total amount by which we've grown the window up or down (to display a
100  // bookmark bar and/or download shelf), respectively; reset to 0 when moved
101  // away from the bottom/top or resized (or zoomed).
102  CGFloat windowTopGrowth_;
103  CGFloat windowBottomGrowth_;
104
105  // YES only if we're shrinking the window from an apparent zoomed state (which
106  // we'll only do if we grew it to the zoomed state); needed since we'll then
107  // restrict the amount of shrinking by the amounts specified above. Reset to
108  // NO on growth.
109  BOOL isShrinkingFromZoomed_;
110
111  // The view controller that manages the incognito badge or the multi-profile
112  // avatar button. Depending on whether the --new-profile-management flag is
113  // used, the multi-profile button can either be the avatar's icon badge or a
114  // button with the profile's name. If the flag is used, the button is always
115  // shown, otherwise the view will always be in the view hierarchy but will
116  // be hidden unless it's appropriate to show it (i.e. if there's more than
117  // one profile).
118  base::scoped_nsobject<AvatarBaseController> avatarButtonController_;
119
120  // Lazily created view which draws the background for the floating set of bars
121  // in presentation mode (for window types having a floating bar; it remains
122  // nil for those which don't).
123  base::scoped_nsobject<NSView> floatingBarBackingView_;
124
125  // The borderless window used in fullscreen mode when Cocoa's System
126  // Fullscreen API is not being used (or not available, before OS 10.7).
127  base::scoped_nsobject<NSWindow> fullscreenWindow_;
128
129  // The Cocoa implementation of the PermissionBubbleView.
130  scoped_ptr<PermissionBubbleCocoa> permissionBubbleCocoa_;
131
132  // True between |-windowWillEnterFullScreen:| and |-windowDidEnterFullScreen:|
133  // to indicate that the window is in the process of transitioning into
134  // fullscreen mode.
135  BOOL enteringFullscreen_;
136
137  // True between |-setPresentationMode:url:bubbleType:| and
138  // |-windowDidEnterFullScreen:| to indicate that the window is in the process
139  // of transitioning into fullscreen presentation mode.
140  BOOL enteringPresentationMode_;
141
142  // The size of the original (non-fullscreen) window.  This is saved just
143  // before entering fullscreen mode and is only valid when |-isFullscreen|
144  // returns YES.
145  NSRect savedRegularWindowFrame_;
146
147  // The proportion of the floating bar which is shown (in presentation mode).
148  CGFloat floatingBarShownFraction_;
149
150  // Various UI elements/events may want to ensure that the floating bar is
151  // visible (in presentation mode), e.g., because of where the mouse is or
152  // where keyboard focus is. Whenever an object requires bar visibility, it has
153  // itself added to |barVisibilityLocks_|. When it no longer requires bar
154  // visibility, it has itself removed.
155  base::scoped_nsobject<NSMutableSet> barVisibilityLocks_;
156
157  // Bar visibility locks and releases only result (when appropriate) in changes
158  // in visible state when the following is |YES|.
159  BOOL barVisibilityUpdatesEnabled_;
160
161  // When going fullscreen for a tab, we need to store the URL and the
162  // fullscreen type, since we can't show the bubble until
163  // -windowDidEnterFullScreen: gets called.
164  GURL fullscreenUrl_;
165  FullscreenExitBubbleType fullscreenBubbleType_;
166
167  // The Extension Command Registry used to determine which keyboard events to
168  // handle.
169  scoped_ptr<ExtensionKeybindingRegistryCocoa> extension_keybinding_registry_;
170
171  // The number of overlapped views being shown.
172  NSUInteger overlappedViewCount_;
173}
174
175// A convenience class method which gets the |BrowserWindowController| for a
176// given window. This method returns nil if no window in the chain has a BWC.
177+ (BrowserWindowController*)browserWindowControllerForWindow:(NSWindow*)window;
178
179// A convenience class method which gets the |BrowserWindowController| for a
180// given view.  This is the controller for the window containing |view|, if it
181// is a BWC, or the first controller in the parent-window chain that is a
182// BWC. This method returns nil if no window in the chain has a BWC.
183+ (BrowserWindowController*)browserWindowControllerForView:(NSView*)view;
184
185// Helper method used to update the "Signin" menu item to reflect the current
186// signed in state. Class-level function as it's still required even when there
187// are no open browser windows.
188+ (void)updateSigninItem:(id)signinItem
189              shouldShow:(BOOL)showSigninMenuItem
190          currentProfile:(Profile*)profile;
191
192// Load the browser window nib and do any Cocoa-specific initialization.
193// Takes ownership of |browser|.
194- (id)initWithBrowser:(Browser*)browser;
195
196// Call to make the browser go away from other places in the cross-platform
197// code.
198- (void)destroyBrowser;
199
200// Ensure bounds for the window abide by the minimum window size.
201- (gfx::Rect)enforceMinWindowSize:(gfx::Rect)bounds;
202
203// Access the C++ bridge between the NSWindow and the rest of Chromium.
204- (BrowserWindow*)browserWindow;
205
206// Return a weak pointer to the toolbar controller.
207- (ToolbarController*)toolbarController;
208
209// Return a weak pointer to the tab strip controller.
210- (TabStripController*)tabStripController;
211
212// Return a weak pointer to the find bar controller.
213- (FindBarCocoaController*)findBarCocoaController;
214
215// Access the ObjC controller that contains the infobars.
216- (InfoBarContainerController*)infoBarContainerController;
217
218// Access the C++ bridge object representing the status bubble for the window.
219- (StatusBubbleMac*)statusBubble;
220
221// Access the C++ bridge object representing the location bar.
222- (LocationBarViewMac*)locationBarBridge;
223
224// Returns a weak pointer to the floating bar backing view;
225- (NSView*)floatingBarBackingView;
226
227// Returns a weak pointer to the overlayable contents controller.
228- (OverlayableContentsController*)overlayableContentsController;
229
230// Access the Profile object that backs this Browser.
231- (Profile*)profile;
232
233// Access the avatar button controller.
234- (AvatarBaseController*)avatarButtonController;
235
236// Forces the toolbar (and transitively the location bar) to update its current
237// state.  If |tab| is non-NULL, we're switching (back?) to this tab and should
238// restore any previous location bar state (such as user editing) as well.
239- (void)updateToolbarWithContents:(content::WebContents*)tab;
240
241// Sets whether or not the current page in the frontmost tab is bookmarked.
242- (void)setStarredState:(BOOL)isStarred;
243
244// Sets whether or not the current page is translated.
245- (void)setCurrentPageIsTranslated:(BOOL)on;
246
247// Happens when the zoom level is changed in the active tab, the active tab is
248// changed, or a new browser window or tab is created. |canShowBubble| denotes
249// whether it would be appropriate to show a zoom bubble or not.
250- (void)zoomChangedForActiveTab:(BOOL)canShowBubble;
251
252// Return the rect, in WebKit coordinates (flipped), of the window's grow box
253// in the coordinate system of the content area of the currently selected tab.
254- (NSRect)selectedTabGrowBoxRect;
255
256// Called to tell the selected tab to update its loading state.
257// |force| is set if the update is due to changing tabs, as opposed to
258// the page-load finishing.  See comment in reload_button.h.
259- (void)setIsLoading:(BOOL)isLoading force:(BOOL)force;
260
261// Brings this controller's window to the front.
262- (void)activate;
263
264// Make the location bar the first responder, if possible.
265- (void)focusLocationBar:(BOOL)selectAll;
266
267// Make the (currently-selected) tab contents the first responder, if possible.
268- (void)focusTabContents;
269
270// Returns the frame of the regular (non-fullscreened) window (even if the
271// window is currently in fullscreen mode).  The frame is returned in Cocoa
272// coordinates (origin in bottom-left).
273- (NSRect)regularWindowFrame;
274
275// Whether or not to show the avatar, which is either the incognito guy or the
276// user's profile avatar.
277- (BOOL)shouldShowAvatar;
278
279// Whether or not to show the new avatar button used by --new-profile-maagement.
280- (BOOL)shouldUseNewAvatarButton;
281
282- (BOOL)isBookmarkBarVisible;
283
284// Returns YES if the bookmark bar is currently animating.
285- (BOOL)isBookmarkBarAnimating;
286
287- (BookmarkBarController*)bookmarkBarController;
288
289- (DevToolsController*)devToolsController;
290
291- (BOOL)isDownloadShelfVisible;
292
293// Lazily creates the download shelf in visible state if it doesn't exist yet.
294- (DownloadShelfController*)downloadShelf;
295
296// Retains the given FindBarCocoaController and adds its view to this
297// browser window.  Must only be called once per
298// BrowserWindowController.
299- (void)addFindBar:(FindBarCocoaController*)findBarCocoaController;
300
301// The user changed the theme.
302- (void)userChangedTheme;
303
304// Executes the command in the context of the current browser.
305// |command| is an integer value containing one of the constants defined in the
306// "chrome/app/chrome_command_ids.h" file.
307- (void)executeCommand:(int)command;
308
309// Consults the Command Registry to see if this |event| needs to be handled as
310// an extension command and returns YES if so (NO otherwise).
311- (BOOL)handledByExtensionCommand:(NSEvent*)event;
312
313// Delegate method for the status bubble to query its base frame.
314- (NSRect)statusBubbleBaseFrame;
315
316// Show the bookmark bubble (e.g. user just clicked on the STAR)
317- (void)showBookmarkBubbleForURL:(const GURL&)url
318               alreadyBookmarked:(BOOL)alreadyBookmarked;
319
320// Show the translate bubble.
321- (void)showTranslateBubbleForWebContents:(content::WebContents*)contents
322                                     step:(translate::TranslateStep)step
323                                errorType:(TranslateErrors::Type)errorType;
324
325// Shows or hides the docked web inspector depending on |contents|'s state.
326- (void)updateDevToolsForContents:(content::WebContents*)contents;
327
328// Gets the current theme provider.
329- (ui::ThemeProvider*)themeProvider;
330
331// Gets the window style.
332- (ThemedWindowStyle)themedWindowStyle;
333
334// Returns the position in the coordinates of the root view
335// ([[self contentView] superview]) that the top left of a theme image with
336// |alignment| should be painted at. If the window does not have a tab strip,
337// the offset for THEME_IMAGE_ALIGN_WITH_FRAME is always returned. The result of
338// this method can be used in conjunction with
339// [NSGraphicsContext cr_setPatternPhase:] to set the offset of pattern colors.
340- (NSPoint)themeImagePositionForAlignment:(ThemeImageAlignment)alignment;
341
342// Return the point to which a bubble window's arrow should point, in window
343// coordinates.
344- (NSPoint)bookmarkBubblePoint;
345
346// Called when the Add Search Engine dialog is closed.
347- (void)sheetDidEnd:(NSWindow*)sheet
348         returnCode:(NSInteger)code
349            context:(void*)context;
350
351// Called when the find bar visibility changes. This is used to update the
352// allowOverlappingViews state.
353- (void)onFindBarVisibilityChanged;
354
355// Called when an overlapped view is shown. This is used to update the
356// allowOverlappingViews state. Currently used for history overlay and
357// confirm bubble.
358- (void)onOverlappedViewShown;
359
360// Called when a history overlay is hidden. This is used to update the
361// allowOverlappingViews state. Currently used for history overlay and
362// confirm bubble.
363- (void)onOverlappedViewHidden;
364
365// Executes the command registered by the extension that has the given id.
366- (void)executeExtensionCommand:(const std::string&)extension_id
367                        command:(const extensions::Command&)command;
368
369// Activates the page action for the extension that has the given id.
370- (void)activatePageAction:(const std::string&)extension_id;
371
372// Activates the browser action for the extension that has the given id.
373- (void)activateBrowserAction:(const std::string&)extension_id;
374
375@end  // @interface BrowserWindowController
376
377
378// Methods having to do with the window type (normal/popup/app, and whether the
379// window has various features; fullscreen and presentation mode methods are
380// separate).
381@interface BrowserWindowController(WindowType)
382
383// Determines whether this controller's window supports a given feature (i.e.,
384// whether a given feature is or can be shown in the window).
385// TODO(viettrungluu): |feature| is really should be |Browser::Feature|, but I
386// don't want to include browser.h (and you can't forward declare enums).
387- (BOOL)supportsWindowFeature:(int)feature;
388
389// Called to check whether or not this window has a normal title bar (YES if it
390// does, NO otherwise). (E.g., normal browser windows do not, pop-ups do.)
391- (BOOL)hasTitleBar;
392
393// Called to check whether or not this window has a toolbar (YES if it does, NO
394// otherwise). (E.g., normal browser windows do, pop-ups do not.)
395- (BOOL)hasToolbar;
396
397// Called to check whether or not this window has a location bar (YES if it
398// does, NO otherwise). (E.g., normal browser windows do, pop-ups may or may
399// not.)
400- (BOOL)hasLocationBar;
401
402// Called to check whether or not this window can have bookmark bar (YES if it
403// does, NO otherwise). (E.g., normal browser windows may, pop-ups may not.)
404- (BOOL)supportsBookmarkBar;
405
406// Called to check if this controller's window is a tabbed window (e.g., not a
407// pop-up window). Returns YES if it is, NO otherwise.
408// Note: The |-has...| methods are usually preferred, so this method is largely
409// deprecated.
410- (BOOL)isTabbedWindow;
411
412@end  // @interface BrowserWindowController(WindowType)
413
414
415// Methods having to do with fullscreen and presentation mode.
416@interface BrowserWindowController(Fullscreen)
417
418// Toggles fullscreen mode.  Meant to be called by Lion windows when they enter
419// or exit Lion fullscreen mode.  Must not be called on Snow Leopard or earlier.
420- (void)handleLionToggleFullscreen;
421
422// Enters (or exits) fullscreen mode.  This method is safe to call on all OS
423// versions.
424- (void)enterFullscreen;
425- (void)exitFullscreen;
426
427// Updates the contents of the fullscreen exit bubble with |url| and
428// |bubbleType|.
429- (void)updateFullscreenExitBubbleURL:(const GURL&)url
430                           bubbleType:(FullscreenExitBubbleType)bubbleType;
431
432// Returns fullscreen state: YES when the window is in fullscreen or is
433// animating into fullscreen.
434- (BOOL)isFullscreen;
435
436// Returns YES if the browser window is currently in fullscreen via the built-in
437// immersive mechanism.
438- (BOOL)isInImmersiveFullscreen;
439
440// Returns YES if the browser window is currently in fullscreen via the Cocoa
441// System Fullscreen API.
442- (BOOL)isInSystemFullscreen;
443
444// Enters (or exits) presentation mode.  Also enters fullscreen mode if this
445// window is not already fullscreen.  This method is safe to call on all OS
446// versions.
447- (void)enterPresentationModeForURL:(const GURL&)url
448                         bubbleType:(FullscreenExitBubbleType)bubbleType;
449- (void)exitPresentationMode;
450
451// For simplified fullscreen: Enters fullscreen for a tab at a URL. The |url|
452// is guaranteed to be non-empty; see -enterFullscreen for the user-initiated
453// fullscreen mode. Called on Snow Leopard and Lion+.
454- (void)enterFullscreenForURL:(const GURL&)url
455                   bubbleType:(FullscreenExitBubbleType)bubbleType;
456
457// Returns presentation mode state.  This method is safe to call on all OS
458// versions.
459- (BOOL)inPresentationMode;
460
461// Resizes the fullscreen window to fit the screen it's currently on.  Called by
462// the PresentationModeController when there is a change in monitor placement or
463// resolution.
464- (void)resizeFullscreenWindow;
465
466// Gets or sets the fraction of the floating bar (presentation mode overlay)
467// that is shown.  0 is completely hidden, 1 is fully shown.
468- (CGFloat)floatingBarShownFraction;
469- (void)setFloatingBarShownFraction:(CGFloat)fraction;
470
471// Query/lock/release the requirement that the tab strip/toolbar/attached
472// bookmark bar bar cluster is visible (e.g., when one of its elements has
473// focus). This is required for the floating bar in presentation mode, but
474// should also be called when not in presentation mode; see the comments for
475// |barVisibilityLocks_| for more details. Double locks/releases by the same
476// owner are ignored. If |animate:| is YES, then an animation may be performed,
477// possibly after a small delay if |delay:| is YES. If |animate:| is NO,
478// |delay:| will be ignored. In the case of multiple calls, later calls have
479// precedence with the rule that |animate:NO| has precedence over |animate:YES|,
480// and |delay:NO| has precedence over |delay:YES|.
481- (BOOL)isBarVisibilityLockedForOwner:(id)owner;
482- (void)lockBarVisibilityForOwner:(id)owner
483                    withAnimation:(BOOL)animate
484                            delay:(BOOL)delay;
485- (void)releaseBarVisibilityForOwner:(id)owner
486                       withAnimation:(BOOL)animate
487                               delay:(BOOL)delay;
488
489// Returns YES if any of the views in the floating bar currently has focus.
490- (BOOL)floatingBarHasFocus;
491
492@end  // @interface BrowserWindowController(Fullscreen)
493
494
495// Methods which are either only for testing, or only public for testing.
496@interface BrowserWindowController (TestingAPI)
497
498// Put the incognito badge or multi-profile avatar on the browser and adjust the
499// tab strip accordingly.
500- (void)installAvatar;
501
502// Allows us to initWithBrowser withOUT taking ownership of the browser.
503- (id)initWithBrowser:(Browser*)browser takeOwnership:(BOOL)ownIt;
504
505// Adjusts the window height by the given amount.  If the window spans from the
506// top of the current workspace to the bottom of the current workspace, the
507// height is not adjusted.  If growing the window by the requested amount would
508// size the window to be taller than the current workspace, the window height is
509// capped to be equal to the height of the current workspace.  If the window is
510// partially offscreen, its height is not adjusted at all.  This function
511// prefers to grow the window down, but will grow up if needed.  Calls to this
512// function should be followed by a call to |layoutSubviews|.
513// Returns if the window height was changed.
514- (BOOL)adjustWindowHeightBy:(CGFloat)deltaH;
515
516// Return an autoreleased NSWindow suitable for fullscreen use.
517- (NSWindow*)createFullscreenWindow;
518
519// Resets any saved state about window growth (due to showing the bookmark bar
520// or the download shelf), so that future shrinking will occur from the bottom.
521- (void)resetWindowGrowthState;
522
523// Computes by how far in each direction, horizontal and vertical, the
524// |source| rect doesn't fit into |target|.
525- (NSSize)overflowFrom:(NSRect)source
526                    to:(NSRect)target;
527
528// The fullscreen exit bubble controller, or nil if the bubble isn't showing.
529- (FullscreenExitBubbleController*)fullscreenExitBubbleController;
530
531// Gets the rect, in window base coordinates, that the omnibox popup should be
532// positioned relative to.
533- (NSRect)omniboxPopupAnchorRect;
534
535// Force a layout of info bars.
536- (void)layoutInfoBars;
537
538@end  // @interface BrowserWindowController (TestingAPI)
539
540
541#endif  // CHROME_BROWSER_UI_COCOA_BROWSER_WINDOW_CONTROLLER_H_
542