1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
9 #include "base/mac/bundle_locations.h"
10 #include "base/mac/mac_util.h"
11 #include "base/memory/singleton.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/sys_string_conversions.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "chrome/app/chrome_command_ids.h"
17 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
18 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
19 #include "chrome/browser/autocomplete/autocomplete_input.h"
20 #include "chrome/browser/autocomplete/autocomplete_match.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/command_updater.h"
23 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/search/search.h"
25 #include "chrome/browser/search_engines/template_url_service.h"
26 #include "chrome/browser/themes/theme_service.h"
27 #include "chrome/browser/ui/browser.h"
28 #include "chrome/browser/ui/browser_window.h"
29 #import "chrome/browser/ui/cocoa/background_gradient_view.h"
30 #include "chrome/browser/ui/cocoa/drag_util.h"
31 #import "chrome/browser/ui/cocoa/extensions/browser_action_button.h"
32 #import "chrome/browser/ui/cocoa/extensions/browser_actions_container_view.h"
33 #import "chrome/browser/ui/cocoa/extensions/browser_actions_controller.h"
34 #import "chrome/browser/ui/cocoa/gradient_button_cell.h"
35 #import "chrome/browser/ui/cocoa/image_button_cell.h"
36 #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.h"
37 #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h"
38 #import "chrome/browser/ui/cocoa/menu_button.h"
39 #import "chrome/browser/ui/cocoa/toolbar/back_forward_menu_controller.h"
40 #import "chrome/browser/ui/cocoa/toolbar/reload_button.h"
41 #import "chrome/browser/ui/cocoa/toolbar/toolbar_button.h"
42 #import "chrome/browser/ui/cocoa/toolbar/toolbar_view.h"
43 #import "chrome/browser/ui/cocoa/toolbar/wrench_toolbar_button_cell.h"
44 #import "chrome/browser/ui/cocoa/view_id_util.h"
45 #import "chrome/browser/ui/cocoa/wrench_menu/wrench_menu_controller.h"
46 #include "chrome/browser/ui/global_error/global_error_service.h"
47 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
48 #include "chrome/browser/ui/omnibox/omnibox_view.h"
49 #include "chrome/browser/ui/tabs/tab_strip_model.h"
50 #include "chrome/browser/ui/toolbar/wrench_menu_model.h"
51 #include "chrome/browser/upgrade_detector.h"
52 #include "chrome/common/net/url_fixer_upper.h"
53 #include "chrome/common/pref_names.h"
54 #include "content/public/browser/notification_details.h"
55 #include "content/public/browser/notification_observer.h"
56 #include "content/public/browser/notification_service.h"
57 #include "content/public/browser/web_contents.h"
58 #include "grit/chromium_strings.h"
59 #include "grit/generated_resources.h"
60 #include "grit/theme_resources.h"
61 #import "ui/base/cocoa/menu_controller.h"
62 #include "ui/base/l10n/l10n_util.h"
63 #include "ui/base/l10n/l10n_util_mac.h"
64 #include "ui/base/resource/resource_bundle.h"
65 #include "ui/gfx/image/image.h"
66 #include "ui/gfx/rect.h"
68 using content::OpenURLParams;
69 using content::Referrer;
70 using content::WebContents;
74 // Height of the toolbar in pixels when the bookmark bar is closed.
75 const CGFloat kBaseToolbarHeightNormal = 35.0;
77 // The minimum width of the location bar in pixels.
78 const CGFloat kMinimumLocationBarWidth = 100.0;
80 // The duration of any animation that occurs within the toolbar in seconds.
81 const CGFloat kAnimationDuration = 0.2;
83 // The amount of left padding that the wrench menu should have.
84 const CGFloat kWrenchMenuLeftPadding = 3.0;
88 @interface ToolbarController()
89 @property(assign, nonatomic) Browser* browser;
90 - (void)addAccessibilityDescriptions;
91 - (void)initCommandStatus:(CommandUpdater*)commands;
92 - (void)prefChanged:(const std::string&)prefName;
93 - (BackgroundGradientView*)backgroundGradientView;
94 - (void)toolbarFrameChanged;
95 - (void)pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:(BOOL)animate;
96 - (void)maintainMinimumLocationBarWidth;
97 - (void)adjustBrowserActionsContainerForNewWindow:(NSNotification*)notification;
98 - (void)browserActionsContainerDragged:(NSNotification*)notification;
99 - (void)browserActionsContainerDragFinished:(NSNotification*)notification;
100 - (void)browserActionsVisibilityChanged:(NSNotification*)notification;
101 - (void)adjustLocationSizeBy:(CGFloat)dX animate:(BOOL)animate;
102 - (void)updateWrenchButtonSeverity;
105 namespace ToolbarControllerInternal {
107 // A class registered for C++ notifications. This is used to detect changes in
108 // preferences and upgrade available notifications. Bridges the notification
109 // back to the ToolbarController.
110 class NotificationBridge
111 : public content::NotificationObserver {
113 explicit NotificationBridge(ToolbarController* controller)
114 : controller_(controller) {
115 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
116 content::NotificationService::AllSources());
117 registrar_.Add(this, chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED,
118 content::Source<Profile>([controller browser]->profile()));
121 // Overridden from content::NotificationObserver:
122 virtual void Observe(int type,
123 const content::NotificationSource& source,
124 const content::NotificationDetails& details) OVERRIDE {
126 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED:
127 case chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED:
128 [controller_ updateWrenchButtonSeverity];
135 void OnPreferenceChanged(const std::string& pref_name) {
136 [controller_ prefChanged:pref_name];
140 ToolbarController* controller_; // weak, owns us
142 content::NotificationRegistrar registrar_;
145 } // namespace ToolbarControllerInternal
147 @implementation ToolbarController
149 @synthesize browser = browser_;
151 - (id)initWithCommands:(CommandUpdater*)commands
152 profile:(Profile*)profile
153 browser:(Browser*)browser
154 resizeDelegate:(id<ViewResizer>)resizeDelegate
155 nibFileNamed:(NSString*)nibName {
156 DCHECK(commands && profile && [nibName length]);
157 if ((self = [super initWithNibName:nibName
158 bundle:base::mac::FrameworkBundle()])) {
159 commands_ = commands;
162 resizeDelegate_ = resizeDelegate;
164 hasLocationBar_ = YES;
166 // Register for notifications about state changes for the toolbar buttons
167 commandObserver_.reset(new CommandObserverBridge(self, commands));
168 commandObserver_->ObserveCommand(IDC_BACK);
169 commandObserver_->ObserveCommand(IDC_FORWARD);
170 commandObserver_->ObserveCommand(IDC_RELOAD);
171 commandObserver_->ObserveCommand(IDC_HOME);
172 commandObserver_->ObserveCommand(IDC_BOOKMARK_PAGE);
177 - (id)initWithCommands:(CommandUpdater*)commands
178 profile:(Profile*)profile
179 browser:(Browser*)browser
180 resizeDelegate:(id<ViewResizer>)resizeDelegate {
181 if ((self = [self initWithCommands:commands
184 resizeDelegate:resizeDelegate
185 nibFileNamed:@"Toolbar"])) {
192 // Unset ViewIDs of toolbar elements.
193 // ViewIDs of |toolbarView|, |reloadButton_|, |locationBar_| and
194 // |browserActionsContainerView_| are handled by themselves.
195 view_id_util::UnsetID(backButton_);
196 view_id_util::UnsetID(forwardButton_);
197 view_id_util::UnsetID(homeButton_);
198 view_id_util::UnsetID(wrenchButton_);
200 // Make sure any code in the base class which assumes [self view] is
201 // the "parent" view continues to work.
203 hasLocationBar_ = YES;
205 [[NSNotificationCenter defaultCenter] removeObserver:self];
207 if (trackingArea_.get())
208 [[self view] removeTrackingArea:trackingArea_.get()];
212 // Called after the view is done loading and the outlets have been hooked up.
213 // Now we can hook up bridges that rely on UI objects such as the location
214 // bar and button state.
215 - (void)awakeFromNib {
216 [[backButton_ cell] setImageID:IDR_BACK
217 forButtonState:image_button_cell::kDefaultState];
218 [[backButton_ cell] setImageID:IDR_BACK_H
219 forButtonState:image_button_cell::kHoverState];
220 [[backButton_ cell] setImageID:IDR_BACK_P
221 forButtonState:image_button_cell::kPressedState];
222 [[backButton_ cell] setImageID:IDR_BACK_D
223 forButtonState:image_button_cell::kDisabledState];
225 [[forwardButton_ cell] setImageID:IDR_FORWARD
226 forButtonState:image_button_cell::kDefaultState];
227 [[forwardButton_ cell] setImageID:IDR_FORWARD_H
228 forButtonState:image_button_cell::kHoverState];
229 [[forwardButton_ cell] setImageID:IDR_FORWARD_P
230 forButtonState:image_button_cell::kPressedState];
231 [[forwardButton_ cell] setImageID:IDR_FORWARD_D
232 forButtonState:image_button_cell::kDisabledState];
234 [[reloadButton_ cell] setImageID:IDR_RELOAD
235 forButtonState:image_button_cell::kDefaultState];
236 [[reloadButton_ cell] setImageID:IDR_RELOAD_H
237 forButtonState:image_button_cell::kHoverState];
238 [[reloadButton_ cell] setImageID:IDR_RELOAD_P
239 forButtonState:image_button_cell::kPressedState];
241 [[homeButton_ cell] setImageID:IDR_HOME
242 forButtonState:image_button_cell::kDefaultState];
243 [[homeButton_ cell] setImageID:IDR_HOME_H
244 forButtonState:image_button_cell::kHoverState];
245 [[homeButton_ cell] setImageID:IDR_HOME_P
246 forButtonState:image_button_cell::kPressedState];
248 [[wrenchButton_ cell] setImageID:IDR_TOOLS
249 forButtonState:image_button_cell::kDefaultState];
250 [[wrenchButton_ cell] setImageID:IDR_TOOLS_H
251 forButtonState:image_button_cell::kHoverState];
252 [[wrenchButton_ cell] setImageID:IDR_TOOLS_P
253 forButtonState:image_button_cell::kPressedState];
255 [self updateWrenchButtonSeverity];
257 [wrenchButton_ setOpenMenuOnClick:YES];
259 [backButton_ setOpenMenuOnRightClick:YES];
260 [forwardButton_ setOpenMenuOnRightClick:YES];
262 [backButton_ setHandleMiddleClick:YES];
263 [forwardButton_ setHandleMiddleClick:YES];
264 [reloadButton_ setHandleMiddleClick:YES];
265 [homeButton_ setHandleMiddleClick:YES];
267 [self initCommandStatus:commands_];
269 locationBarView_.reset(new LocationBarViewMac(locationBar_, commands_,
270 profile_, browser_));
271 [locationBar_ setFont:[NSFont systemFontOfSize:[NSFont systemFontSize]]];
272 // Register pref observers for the optional home and page/options buttons
273 // and then add them to the toolbar based on those prefs.
274 notificationBridge_.reset(
275 new ToolbarControllerInternal::NotificationBridge(self));
276 PrefService* prefs = profile_->GetPrefs();
277 showHomeButton_.Init(
278 prefs::kShowHomeButton, prefs,
280 &ToolbarControllerInternal::NotificationBridge::OnPreferenceChanged,
281 base::Unretained(notificationBridge_.get())));
282 [self showOptionalHomeButton];
283 [self installWrenchMenu];
285 // Create the controllers for the back/forward menus.
286 backMenuController_.reset([[BackForwardMenuController alloc]
287 initWithBrowser:browser_
288 modelType:BACK_FORWARD_MENU_TYPE_BACK
289 button:backButton_]);
290 forwardMenuController_.reset([[BackForwardMenuController alloc]
291 initWithBrowser:browser_
292 modelType:BACK_FORWARD_MENU_TYPE_FORWARD
293 button:forwardButton_]);
295 // For a popup window, the toolbar is really just a location bar
296 // (see override for [ToolbarController view], below). When going
297 // fullscreen, we remove the toolbar controller's view from the view
298 // hierarchy. Calling [locationBar_ removeFromSuperview] when going
299 // fullscreen causes it to get released, making us unhappy
300 // (http://crbug.com/18551). We avoid the problem by incrementing
301 // the retain count of the location bar; use of the scoped object
302 // helps us remember to release it.
303 locationBarRetainer_.reset([locationBar_ retain]);
305 [[CrTrackingArea alloc] initWithRect:NSZeroRect // Ignored
306 options:NSTrackingMouseMoved |
307 NSTrackingInVisibleRect |
308 NSTrackingMouseEnteredAndExited |
309 NSTrackingActiveAlways
312 NSView* toolbarView = [self view];
313 [toolbarView addTrackingArea:trackingArea_.get()];
315 // If the user has any Browser Actions installed, the container view for them
316 // may have to be resized depending on the width of the toolbar frame.
317 [toolbarView setPostsFrameChangedNotifications:YES];
318 [[NSNotificationCenter defaultCenter]
320 selector:@selector(toolbarFrameChanged)
321 name:NSViewFrameDidChangeNotification
324 // Set ViewIDs for toolbar elements which don't have their dedicated class.
325 // ViewIDs of |toolbarView|, |reloadButton_|, |locationBar_| and
326 // |browserActionsContainerView_| are handled by themselves.
327 view_id_util::SetID(backButton_, VIEW_ID_BACK_BUTTON);
328 view_id_util::SetID(forwardButton_, VIEW_ID_FORWARD_BUTTON);
329 view_id_util::SetID(homeButton_, VIEW_ID_HOME_BUTTON);
330 view_id_util::SetID(wrenchButton_, VIEW_ID_APP_MENU);
332 [self addAccessibilityDescriptions];
335 - (void)addAccessibilityDescriptions {
336 // Set accessibility descriptions. http://openradar.appspot.com/7496255
337 NSString* description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_BACK);
339 accessibilitySetOverrideValue:description
340 forAttribute:NSAccessibilityDescriptionAttribute];
341 description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_FORWARD);
342 [[forwardButton_ cell]
343 accessibilitySetOverrideValue:description
344 forAttribute:NSAccessibilityDescriptionAttribute];
345 description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_RELOAD);
346 [[reloadButton_ cell]
347 accessibilitySetOverrideValue:description
348 forAttribute:NSAccessibilityDescriptionAttribute];
349 description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_HOME);
351 accessibilitySetOverrideValue:description
352 forAttribute:NSAccessibilityDescriptionAttribute];
353 description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_LOCATION);
355 accessibilitySetOverrideValue:description
356 forAttribute:NSAccessibilityDescriptionAttribute];
357 description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_APP);
358 [[wrenchButton_ cell]
359 accessibilitySetOverrideValue:description
360 forAttribute:NSAccessibilityDescriptionAttribute];
363 - (void)mouseExited:(NSEvent*)theEvent {
364 [[hoveredButton_ cell] setMouseInside:NO animate:YES];
365 [hoveredButton_ release];
366 hoveredButton_ = nil;
369 - (NSButton*)hoverButtonForEvent:(NSEvent*)theEvent {
370 NSButton* targetView = (NSButton*)[[self view]
371 hitTest:[theEvent locationInWindow]];
373 // Only interpret the view as a hoverButton_ if it's both button and has a
374 // button cell that cares. GradientButtonCell derived cells care.
375 if (([targetView isKindOfClass:[NSButton class]]) &&
377 respondsToSelector:@selector(setMouseInside:animate:)]))
382 - (void)mouseMoved:(NSEvent*)theEvent {
383 NSButton* targetView = [self hoverButtonForEvent:theEvent];
384 if (hoveredButton_ != targetView) {
385 [[hoveredButton_ cell] setMouseInside:NO animate:YES];
386 [[targetView cell] setMouseInside:YES animate:YES];
387 [hoveredButton_ release];
388 hoveredButton_ = [targetView retain];
392 - (void)mouseEntered:(NSEvent*)event {
393 [self mouseMoved:event];
396 - (LocationBarViewMac*)locationBarBridge {
397 return locationBarView_.get();
400 - (void)focusLocationBar:(BOOL)selectAll {
401 if (locationBarView_.get()) {
402 if (chrome::ShouldDisplayOriginChip() && selectAll) {
403 // select_all is true when it's expected that the user may want to copy
404 // the URL to the clipboard. If the origin chip is being displayed (and
405 // thus the URL is not being shown in the Omnibox) show it now to support
406 // the same functionality.
407 locationBarView_->GetOmniboxView()->ShowURL();
409 locationBarView_->FocusLocation(selectAll ? true : false);
414 // Called when the state for a command changes to |enabled|. Update the
415 // corresponding UI element.
416 - (void)enabledStateChangedForCommand:(NSInteger)command enabled:(BOOL)enabled {
417 NSButton* button = nil;
420 button = backButton_;
423 button = forwardButton_;
426 button = homeButton_;
429 [button setEnabled:enabled];
432 // Init the enabled state of the buttons on the toolbar to match the state in
434 - (void)initCommandStatus:(CommandUpdater*)commands {
435 [backButton_ setEnabled:commands->IsCommandEnabled(IDC_BACK) ? YES : NO];
437 setEnabled:commands->IsCommandEnabled(IDC_FORWARD) ? YES : NO];
438 [reloadButton_ setEnabled:YES];
439 [homeButton_ setEnabled:commands->IsCommandEnabled(IDC_HOME) ? YES : NO];
442 - (void)updateToolbarWithContents:(WebContents*)tab {
443 locationBarView_->Update(tab);
445 [locationBar_ updateMouseTracking];
447 if (browserActionsController_.get()) {
448 [browserActionsController_ update];
452 - (void)setStarredState:(BOOL)isStarred {
453 locationBarView_->SetStarred(isStarred ? true : false);
456 - (void)zoomChangedForActiveTab:(BOOL)canShowBubble {
457 locationBarView_->ZoomChangedForActiveTab(
458 canShowBubble && ![wrenchMenuController_ isMenuOpen]);
461 - (void)setIsLoading:(BOOL)isLoading force:(BOOL)force {
462 [reloadButton_ setIsLoading:isLoading force:force];
465 - (void)setHasToolbar:(BOOL)toolbar hasLocationBar:(BOOL)locBar {
466 [self view]; // Force nib loading.
468 hasToolbar_ = toolbar;
470 // If there's a toolbar, there must be a location bar.
471 DCHECK((toolbar && locBar) || !toolbar);
472 hasLocationBar_ = toolbar ? YES : locBar;
474 // Decide whether to hide/show based on whether there's a location bar.
475 [[self view] setHidden:!hasLocationBar_];
477 // Make location bar not editable when in a pop-up.
478 locationBarView_->SetEditable(toolbar);
487 // (Private) Returns the backdrop to the toolbar.
488 - (BackgroundGradientView*)backgroundGradientView {
489 // We really do mean |[super view]|; see our override of |-view|.
490 DCHECK([[super view] isKindOfClass:[BackgroundGradientView class]]);
491 return (BackgroundGradientView*)[super view];
494 - (id)customFieldEditorForObject:(id)obj {
495 if (obj == locationBar_) {
496 // Lazilly construct Field editor, Cocoa UI code always runs on the
497 // same thread, so there shoudn't be a race condition here.
498 if (autocompleteTextFieldEditor_.get() == nil) {
499 autocompleteTextFieldEditor_.reset(
500 [[AutocompleteTextFieldEditor alloc] init]);
503 // This needs to be called every time, otherwise notifications
504 // aren't sent correctly.
505 DCHECK(autocompleteTextFieldEditor_.get());
506 [autocompleteTextFieldEditor_.get() setFieldEditor:YES];
507 return autocompleteTextFieldEditor_.get();
512 // Returns an array of views in the order of the outlets above.
513 - (NSArray*)toolbarViews {
514 return [NSArray arrayWithObjects:backButton_, forwardButton_, reloadButton_,
515 homeButton_, wrenchButton_, locationBar_,
516 browserActionsContainerView_, nil];
519 // Moves |rect| to the right by |delta|, keeping the right side fixed by
520 // shrinking the width to compensate. Passing a negative value for |deltaX|
521 // moves to the left and increases the width.
522 - (NSRect)adjustRect:(NSRect)rect byAmount:(CGFloat)deltaX {
523 NSRect frame = NSOffsetRect(rect, deltaX, 0);
524 frame.size.width -= deltaX;
528 // Show or hide the home button based on the pref.
529 - (void)showOptionalHomeButton {
530 // Ignore this message if only showing the URL bar.
533 BOOL hide = showHomeButton_.GetValue() ? NO : YES;
534 if (hide == [homeButton_ isHidden])
535 return; // Nothing to do, view state matches pref state.
537 // Always shift the text field by the width of the home button minus one pixel
538 // since the frame edges of each button are right on top of each other. When
539 // hiding the button, reverse the direction of the movement (to the left).
540 CGFloat moveX = [homeButton_ frame].size.width - 1.0;
542 moveX *= -1; // Reverse the direction of the move.
544 [locationBar_ setFrame:[self adjustRect:[locationBar_ frame]
546 [homeButton_ setHidden:hide];
549 // Install the menu wrench buttons. Calling this repeatedly is inexpensive so it
550 // can be done every time the buttons are shown.
551 - (void)installWrenchMenu {
552 if (wrenchMenuController_.get())
555 wrenchMenuController_.reset(
556 [[WrenchMenuController alloc] initWithBrowser:browser_]);
557 [wrenchMenuController_ setUseWithPopUpButtonCell:YES];
558 [wrenchButton_ setAttachedMenu:[wrenchMenuController_ menu]];
561 - (WrenchMenuController*)wrenchMenuController {
562 return wrenchMenuController_;
565 - (void)updateWrenchButtonSeverity {
566 WrenchToolbarButtonCell* cell =
567 base::mac::ObjCCastStrict<WrenchToolbarButtonCell>([wrenchButton_ cell]);
568 if (UpgradeDetector::GetInstance()->notify_upgrade()) {
569 UpgradeDetector::UpgradeNotificationAnnoyanceLevel level =
570 UpgradeDetector::GetInstance()->upgrade_notification_stage();
571 [cell setSeverity:WrenchIconPainter::SeverityFromUpgradeLevel(level)
572 shouldAnimate:WrenchIconPainter::ShouldAnimateUpgradeLevel(level)];
576 GlobalError* error = GlobalErrorServiceFactory::GetForProfile(
577 browser_->profile())->GetHighestSeverityGlobalErrorWithWrenchMenuItem();
579 [cell setSeverity:WrenchIconPainter::GlobalErrorSeverity()
584 [cell setSeverity:WrenchIconPainter::SEVERITY_NONE shouldAnimate:YES];
587 - (void)prefChanged:(const std::string&)prefName {
588 if (prefName == prefs::kShowHomeButton) {
589 [self showOptionalHomeButton];
593 - (void)createBrowserActionButtons {
594 if (!browserActionsController_.get()) {
595 browserActionsController_.reset([[BrowserActionsController alloc]
596 initWithBrowser:browser_
597 containerView:browserActionsContainerView_]);
598 [[NSNotificationCenter defaultCenter]
600 selector:@selector(browserActionsContainerDragged:)
601 name:kBrowserActionGrippyDraggingNotification
602 object:browserActionsController_];
603 [[NSNotificationCenter defaultCenter]
605 selector:@selector(browserActionsContainerDragFinished:)
606 name:kBrowserActionGrippyDragFinishedNotification
607 object:browserActionsController_];
608 [[NSNotificationCenter defaultCenter]
610 selector:@selector(browserActionsVisibilityChanged:)
611 name:kBrowserActionVisibilityChangedNotification
612 object:browserActionsController_];
613 [[NSNotificationCenter defaultCenter]
615 selector:@selector(adjustBrowserActionsContainerForNewWindow:)
616 name:NSWindowDidBecomeKeyNotification
617 object:[[self view] window]];
619 CGFloat containerWidth = [browserActionsContainerView_ isHidden] ? 0.0 :
620 NSWidth([browserActionsContainerView_ frame]);
621 if (containerWidth > 0.0)
622 [self adjustLocationSizeBy:(containerWidth * -1) animate:NO];
625 - (void)adjustBrowserActionsContainerForNewWindow:
626 (NSNotification*)notification {
627 [self toolbarFrameChanged];
628 [[NSNotificationCenter defaultCenter]
630 name:NSWindowDidBecomeKeyNotification
631 object:[[self view] window]];
634 - (void)browserActionsContainerDragged:(NSNotification*)notification {
635 CGFloat locationBarWidth = NSWidth([locationBar_ frame]);
636 locationBarAtMinSize_ = locationBarWidth <= kMinimumLocationBarWidth;
637 [browserActionsContainerView_ setCanDragLeft:!locationBarAtMinSize_];
638 [browserActionsContainerView_ setGrippyPinned:locationBarAtMinSize_];
639 [self adjustLocationSizeBy:
640 [browserActionsContainerView_ resizeDeltaX] animate:NO];
643 - (void)browserActionsContainerDragFinished:(NSNotification*)notification {
644 [browserActionsController_ resizeContainerAndAnimate:YES];
645 [self pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:YES];
648 - (void)browserActionsVisibilityChanged:(NSNotification*)notification {
649 [self pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:NO];
652 - (void)pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:(BOOL)animate {
653 CGFloat locationBarXPos = NSMaxX([locationBar_ frame]);
654 CGFloat leftDistance;
656 if ([browserActionsContainerView_ isHidden]) {
657 CGFloat edgeXPos = [wrenchButton_ frame].origin.x;
658 leftDistance = edgeXPos - locationBarXPos - kWrenchMenuLeftPadding;
660 NSRect containerFrame = animate ?
661 [browserActionsContainerView_ animationEndFrame] :
662 [browserActionsContainerView_ frame];
664 leftDistance = containerFrame.origin.x - locationBarXPos;
666 if (leftDistance != 0.0)
667 [self adjustLocationSizeBy:leftDistance animate:animate];
670 - (void)maintainMinimumLocationBarWidth {
671 CGFloat locationBarWidth = NSWidth([locationBar_ frame]);
672 locationBarAtMinSize_ = locationBarWidth <= kMinimumLocationBarWidth;
673 if (locationBarAtMinSize_) {
674 CGFloat dX = kMinimumLocationBarWidth - locationBarWidth;
675 [self adjustLocationSizeBy:dX animate:NO];
679 - (void)toolbarFrameChanged {
680 // Do nothing if the frame changes but no Browser Action Controller is
682 if (!browserActionsController_.get())
685 [self maintainMinimumLocationBarWidth];
687 if (locationBarAtMinSize_) {
688 // Once the grippy is pinned, leave it until it is explicity un-pinned.
689 [browserActionsContainerView_ setGrippyPinned:YES];
690 NSRect containerFrame = [browserActionsContainerView_ frame];
691 // Determine how much the container needs to move in case it's overlapping
692 // with the location bar.
693 CGFloat dX = NSMaxX([locationBar_ frame]) - containerFrame.origin.x;
694 containerFrame = NSOffsetRect(containerFrame, dX, 0);
695 containerFrame.size.width -= dX;
696 [browserActionsContainerView_ setFrame:containerFrame];
697 } else if (!locationBarAtMinSize_ &&
698 [browserActionsContainerView_ grippyPinned]) {
699 // Expand out the container until it hits the saved size, then unpin the
701 // Add 0.1 pixel so that it doesn't hit the minimum width codepath above.
702 CGFloat dX = NSWidth([locationBar_ frame]) -
703 (kMinimumLocationBarWidth + 0.1);
704 NSRect containerFrame = [browserActionsContainerView_ frame];
705 containerFrame = NSOffsetRect(containerFrame, -dX, 0);
706 containerFrame.size.width += dX;
707 CGFloat savedContainerWidth = [browserActionsController_ savedWidth];
708 if (NSWidth(containerFrame) >= savedContainerWidth) {
709 containerFrame = NSOffsetRect(containerFrame,
710 NSWidth(containerFrame) - savedContainerWidth, 0);
711 containerFrame.size.width = savedContainerWidth;
712 [browserActionsContainerView_ setGrippyPinned:NO];
714 [browserActionsContainerView_ setFrame:containerFrame];
715 [self pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:NO];
719 - (void)adjustLocationSizeBy:(CGFloat)dX animate:(BOOL)animate {
720 // Ensure that the location bar is in its proper place.
721 NSRect locationFrame = [locationBar_ frame];
722 locationFrame.size.width += dX;
725 [locationBar_ setFrame:locationFrame];
729 [NSAnimationContext beginGrouping];
730 [[NSAnimationContext currentContext] setDuration:kAnimationDuration];
731 [[locationBar_ animator] setFrame:locationFrame];
732 [NSAnimationContext endGrouping];
735 - (NSPoint)bookmarkBubblePoint {
736 if (locationBarView_->IsStarEnabled())
737 return locationBarView_->GetBookmarkBubblePoint();
739 // Grab bottom middle of hotdogs.
740 NSRect frame = wrenchButton_.frame;
741 NSPoint point = NSMakePoint(NSMidX(frame), NSMinY(frame));
742 // Inset to account for the whitespace around the hotdogs.
743 point.y += wrench_menu_controller::kWrenchBubblePointOffsetY;
744 return [self.view convertPoint:point toView:nil];
747 - (CGFloat)desiredHeightForCompression:(CGFloat)compressByHeight {
748 // With no toolbar, just ignore the compression.
750 return NSHeight([locationBar_ frame]);
752 return kBaseToolbarHeightNormal - compressByHeight;
755 - (void)setDividerOpacity:(CGFloat)opacity {
756 BackgroundGradientView* view = [self backgroundGradientView];
757 [view setShowsDivider:(opacity > 0 ? YES : NO)];
759 // We may not have a toolbar view (e.g., popup windows only have a location
761 if ([view isKindOfClass:[ToolbarView class]]) {
762 ToolbarView* toolbarView = (ToolbarView*)view;
763 [toolbarView setDividerOpacity:opacity];
766 [view setNeedsDisplay:YES];
769 - (BrowserActionsController*)browserActionsController {
770 return browserActionsController_.get();
773 - (NSView*)wrenchButton {
774 return wrenchButton_;
777 // (URLDropTargetController protocol)
778 - (void)dropURLs:(NSArray*)urls inView:(NSView*)view at:(NSPoint)point {
779 // TODO(viettrungluu): This code is more or less copied from the code in
780 // |TabStripController|. I'll refactor this soon to make it common and expand
781 // its capabilities (e.g., allow text DnD).
782 if ([urls count] < 1) {
787 // TODO(viettrungluu): dropping multiple URLs?
788 if ([urls count] > 1)
791 // Get the first URL and fix it up.
792 GURL url(URLFixerUpper::FixupURL(
793 base::SysNSStringToUTF8([urls objectAtIndex:0]), std::string()));
795 if (url.SchemeIs(content::kJavaScriptScheme)) {
796 browser_->window()->GetLocationBar()->GetOmniboxView()->SetUserText(
797 OmniboxView::StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
799 OpenURLParams params(
800 url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false);
801 browser_->tab_strip_model()->GetActiveWebContents()->OpenURL(params);
804 // (URLDropTargetController protocol)
805 - (void)dropText:(NSString*)text inView:(NSView*)view at:(NSPoint)point {
806 // TODO(viettrungluu): This code is more or less copied from the code in
807 // |TabStripController|. I'll refactor this soon to make it common and expand
808 // its capabilities (e.g., allow text DnD).
810 // If the input is plain text, classify the input and make the URL.
811 AutocompleteMatch match;
812 AutocompleteClassifierFactory::GetForProfile(browser_->profile())->Classify(
813 base::SysNSStringToUTF16(text), false, false, AutocompleteInput::BLANK,
815 GURL url(match.destination_url);
817 OpenURLParams params(
818 url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false);
819 browser_->tab_strip_model()->GetActiveWebContents()->OpenURL(params);
822 // (URLDropTargetController protocol)
823 - (void)indicateDropURLsInView:(NSView*)view at:(NSPoint)point {
827 // (URLDropTargetController protocol)
828 - (void)hideDropURLsIndicatorInView:(NSView*)view {
832 // (URLDropTargetController protocol)
833 - (BOOL)isUnsupportedDropData:(id<NSDraggingInfo>)info {
834 return drag_util::IsUnsupportedDropData(profile_, info);