Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / cocoa / toolbar / toolbar_controller.mm
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 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
6
7 #include <algorithm>
8
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"
67
68 using content::OpenURLParams;
69 using content::Referrer;
70 using content::WebContents;
71
72 namespace {
73
74 // Height of the toolbar in pixels when the bookmark bar is closed.
75 const CGFloat kBaseToolbarHeightNormal = 35.0;
76
77 // The minimum width of the location bar in pixels.
78 const CGFloat kMinimumLocationBarWidth = 100.0;
79
80 // The duration of any animation that occurs within the toolbar in seconds.
81 const CGFloat kAnimationDuration = 0.2;
82
83 // The amount of left padding that the wrench menu should have.
84 const CGFloat kWrenchMenuLeftPadding = 3.0;
85
86 }  // namespace
87
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;
103 @end
104
105 namespace ToolbarControllerInternal {
106
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 {
112  public:
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()));
119   }
120
121   // Overridden from content::NotificationObserver:
122   virtual void Observe(int type,
123                        const content::NotificationSource& source,
124                        const content::NotificationDetails& details) OVERRIDE {
125     switch (type) {
126       case chrome::NOTIFICATION_UPGRADE_RECOMMENDED:
127       case chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED:
128         [controller_ updateWrenchButtonSeverity];
129         break;
130       default:
131         NOTREACHED();
132     }
133   }
134
135   void OnPreferenceChanged(const std::string& pref_name) {
136     [controller_ prefChanged:pref_name];
137   }
138
139  private:
140   ToolbarController* controller_;  // weak, owns us
141
142   content::NotificationRegistrar registrar_;
143 };
144
145 }  // namespace ToolbarControllerInternal
146
147 @implementation ToolbarController
148
149 @synthesize browser = browser_;
150
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;
160     profile_ = profile;
161     browser_ = browser;
162     resizeDelegate_ = resizeDelegate;
163     hasToolbar_ = YES;
164     hasLocationBar_ = YES;
165
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);
173   }
174   return self;
175 }
176
177 - (id)initWithCommands:(CommandUpdater*)commands
178                profile:(Profile*)profile
179                browser:(Browser*)browser
180         resizeDelegate:(id<ViewResizer>)resizeDelegate {
181   if ((self = [self initWithCommands:commands
182                              profile:profile
183                              browser:browser
184                       resizeDelegate:resizeDelegate
185                         nibFileNamed:@"Toolbar"])) {
186   }
187   return self;
188 }
189
190
191 - (void)dealloc {
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_);
199
200   // Make sure any code in the base class which assumes [self view] is
201   // the "parent" view continues to work.
202   hasToolbar_ = YES;
203   hasLocationBar_ = YES;
204
205   [[NSNotificationCenter defaultCenter] removeObserver:self];
206
207   if (trackingArea_.get())
208     [[self view] removeTrackingArea:trackingArea_.get()];
209   [super dealloc];
210 }
211
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];
224
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];
233
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];
240
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];
247
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];
254
255   [self updateWrenchButtonSeverity];
256
257   [wrenchButton_ setOpenMenuOnClick:YES];
258
259   [backButton_ setOpenMenuOnRightClick:YES];
260   [forwardButton_ setOpenMenuOnRightClick:YES];
261
262   [backButton_ setHandleMiddleClick:YES];
263   [forwardButton_ setHandleMiddleClick:YES];
264   [reloadButton_ setHandleMiddleClick:YES];
265   [homeButton_ setHandleMiddleClick:YES];
266
267   [self initCommandStatus:commands_];
268
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,
279       base::Bind(
280           &ToolbarControllerInternal::NotificationBridge::OnPreferenceChanged,
281           base::Unretained(notificationBridge_.get())));
282   [self showOptionalHomeButton];
283   [self installWrenchMenu];
284
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_]);
294
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]);
304   trackingArea_.reset(
305       [[CrTrackingArea alloc] initWithRect:NSZeroRect // Ignored
306                                    options:NSTrackingMouseMoved |
307                                            NSTrackingInVisibleRect |
308                                            NSTrackingMouseEnteredAndExited |
309                                            NSTrackingActiveAlways
310                                      owner:self
311                                   userInfo:nil]);
312   NSView* toolbarView = [self view];
313   [toolbarView addTrackingArea:trackingArea_.get()];
314
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]
319       addObserver:self
320          selector:@selector(toolbarFrameChanged)
321              name:NSViewFrameDidChangeNotification
322            object:toolbarView];
323
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);
331
332   [self addAccessibilityDescriptions];
333 }
334
335 - (void)addAccessibilityDescriptions {
336   // Set accessibility descriptions. http://openradar.appspot.com/7496255
337   NSString* description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_BACK);
338   [[backButton_ cell]
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);
350   [[homeButton_ cell]
351       accessibilitySetOverrideValue:description
352                        forAttribute:NSAccessibilityDescriptionAttribute];
353   description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_LOCATION);
354   [[locationBar_ cell]
355       accessibilitySetOverrideValue:description
356                        forAttribute:NSAccessibilityDescriptionAttribute];
357   description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_APP);
358   [[wrenchButton_ cell]
359       accessibilitySetOverrideValue:description
360                        forAttribute:NSAccessibilityDescriptionAttribute];
361 }
362
363 - (void)mouseExited:(NSEvent*)theEvent {
364   [[hoveredButton_ cell] setMouseInside:NO animate:YES];
365   [hoveredButton_ release];
366   hoveredButton_ = nil;
367 }
368
369 - (NSButton*)hoverButtonForEvent:(NSEvent*)theEvent {
370   NSButton* targetView = (NSButton*)[[self view]
371                                      hitTest:[theEvent locationInWindow]];
372
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]]) &&
376       ([[targetView cell]
377          respondsToSelector:@selector(setMouseInside:animate:)]))
378     return targetView;
379   return nil;
380 }
381
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];
389   }
390 }
391
392 - (void)mouseEntered:(NSEvent*)event {
393   [self mouseMoved:event];
394 }
395
396 - (LocationBarViewMac*)locationBarBridge {
397   return locationBarView_.get();
398 }
399
400 - (void)focusLocationBar:(BOOL)selectAll {
401   if (locationBarView_.get()) {
402     if (selectAll &&
403         locationBarView_->GetToolbarModel()->WouldOmitURLDueToOriginChip()) {
404       // select_all is true when it's expected that the user may want to copy
405       // the URL to the clipboard. If the origin chip is being displayed (and
406       // thus the URL is not being shown in the Omnibox) show it now to support
407       // the same functionality.
408       locationBarView_->GetOmniboxView()->ShowURL();
409     } else {
410       locationBarView_->FocusLocation(selectAll ? true : false);
411     }
412   }
413 }
414
415 // Called when the state for a command changes to |enabled|. Update the
416 // corresponding UI element.
417 - (void)enabledStateChangedForCommand:(NSInteger)command enabled:(BOOL)enabled {
418   NSButton* button = nil;
419   switch (command) {
420     case IDC_BACK:
421       button = backButton_;
422       break;
423     case IDC_FORWARD:
424       button = forwardButton_;
425       break;
426     case IDC_HOME:
427       button = homeButton_;
428       break;
429   }
430   [button setEnabled:enabled];
431 }
432
433 // Init the enabled state of the buttons on the toolbar to match the state in
434 // the controller.
435 - (void)initCommandStatus:(CommandUpdater*)commands {
436   [backButton_ setEnabled:commands->IsCommandEnabled(IDC_BACK) ? YES : NO];
437   [forwardButton_
438       setEnabled:commands->IsCommandEnabled(IDC_FORWARD) ? YES : NO];
439   [reloadButton_ setEnabled:YES];
440   [homeButton_ setEnabled:commands->IsCommandEnabled(IDC_HOME) ? YES : NO];
441 }
442
443 - (void)updateToolbarWithContents:(WebContents*)tab {
444   locationBarView_->Update(tab);
445
446   [locationBar_ updateMouseTracking];
447
448   if (browserActionsController_.get()) {
449     [browserActionsController_ update];
450   }
451 }
452
453 - (void)setStarredState:(BOOL)isStarred {
454   locationBarView_->SetStarred(isStarred ? true : false);
455 }
456
457 - (void)zoomChangedForActiveTab:(BOOL)canShowBubble {
458   locationBarView_->ZoomChangedForActiveTab(
459       canShowBubble && ![wrenchMenuController_ isMenuOpen]);
460 }
461
462 - (void)setIsLoading:(BOOL)isLoading force:(BOOL)force {
463   [reloadButton_ setIsLoading:isLoading force:force];
464 }
465
466 - (void)setHasToolbar:(BOOL)toolbar hasLocationBar:(BOOL)locBar {
467   [self view];  // Force nib loading.
468
469   hasToolbar_ = toolbar;
470
471   // If there's a toolbar, there must be a location bar.
472   DCHECK((toolbar && locBar) || !toolbar);
473   hasLocationBar_ = toolbar ? YES : locBar;
474
475   // Decide whether to hide/show based on whether there's a location bar.
476   [[self view] setHidden:!hasLocationBar_];
477
478   // Make location bar not editable when in a pop-up.
479   locationBarView_->SetEditable(toolbar);
480 }
481
482 - (NSView*)view {
483   if (hasToolbar_)
484     return [super view];
485   return locationBar_;
486 }
487
488 // (Private) Returns the backdrop to the toolbar.
489 - (BackgroundGradientView*)backgroundGradientView {
490   // We really do mean |[super view]|; see our override of |-view|.
491   DCHECK([[super view] isKindOfClass:[BackgroundGradientView class]]);
492   return (BackgroundGradientView*)[super view];
493 }
494
495 - (id)customFieldEditorForObject:(id)obj {
496   if (obj == locationBar_) {
497     // Lazilly construct Field editor, Cocoa UI code always runs on the
498     // same thread, so there shoudn't be a race condition here.
499     if (autocompleteTextFieldEditor_.get() == nil) {
500       autocompleteTextFieldEditor_.reset(
501           [[AutocompleteTextFieldEditor alloc] init]);
502     }
503
504     // This needs to be called every time, otherwise notifications
505     // aren't sent correctly.
506     DCHECK(autocompleteTextFieldEditor_.get());
507     [autocompleteTextFieldEditor_.get() setFieldEditor:YES];
508     return autocompleteTextFieldEditor_.get();
509   }
510   return nil;
511 }
512
513 // Returns an array of views in the order of the outlets above.
514 - (NSArray*)toolbarViews {
515   return [NSArray arrayWithObjects:backButton_, forwardButton_, reloadButton_,
516              homeButton_, wrenchButton_, locationBar_,
517              browserActionsContainerView_, nil];
518 }
519
520 // Moves |rect| to the right by |delta|, keeping the right side fixed by
521 // shrinking the width to compensate. Passing a negative value for |deltaX|
522 // moves to the left and increases the width.
523 - (NSRect)adjustRect:(NSRect)rect byAmount:(CGFloat)deltaX {
524   NSRect frame = NSOffsetRect(rect, deltaX, 0);
525   frame.size.width -= deltaX;
526   return frame;
527 }
528
529 // Show or hide the home button based on the pref.
530 - (void)showOptionalHomeButton {
531   // Ignore this message if only showing the URL bar.
532   if (!hasToolbar_)
533     return;
534   BOOL hide = showHomeButton_.GetValue() ? NO : YES;
535   if (hide == [homeButton_ isHidden])
536     return;  // Nothing to do, view state matches pref state.
537
538   // Always shift the text field by the width of the home button minus one pixel
539   // since the frame edges of each button are right on top of each other. When
540   // hiding the button, reverse the direction of the movement (to the left).
541   CGFloat moveX = [homeButton_ frame].size.width - 1.0;
542   if (hide)
543     moveX *= -1;  // Reverse the direction of the move.
544
545   [locationBar_ setFrame:[self adjustRect:[locationBar_ frame]
546                                  byAmount:moveX]];
547   [homeButton_ setHidden:hide];
548 }
549
550 // Install the menu wrench buttons. Calling this repeatedly is inexpensive so it
551 // can be done every time the buttons are shown.
552 - (void)installWrenchMenu {
553   if (wrenchMenuController_.get())
554     return;
555
556   wrenchMenuController_.reset(
557       [[WrenchMenuController alloc] initWithBrowser:browser_]);
558   [wrenchMenuController_ setUseWithPopUpButtonCell:YES];
559   [wrenchButton_ setAttachedMenu:[wrenchMenuController_ menu]];
560 }
561
562 - (WrenchMenuController*)wrenchMenuController {
563   return wrenchMenuController_;
564 }
565
566 - (void)updateWrenchButtonSeverity {
567   WrenchToolbarButtonCell* cell =
568       base::mac::ObjCCastStrict<WrenchToolbarButtonCell>([wrenchButton_ cell]);
569   if (UpgradeDetector::GetInstance()->notify_upgrade()) {
570     UpgradeDetector::UpgradeNotificationAnnoyanceLevel level =
571         UpgradeDetector::GetInstance()->upgrade_notification_stage();
572     [cell setSeverity:WrenchIconPainter::SeverityFromUpgradeLevel(level)
573         shouldAnimate:WrenchIconPainter::ShouldAnimateUpgradeLevel(level)];
574     return;
575   }
576
577   GlobalError* error = GlobalErrorServiceFactory::GetForProfile(
578       browser_->profile())->GetHighestSeverityGlobalErrorWithWrenchMenuItem();
579   if (error) {
580     [cell setSeverity:WrenchIconPainter::GlobalErrorSeverity()
581         shouldAnimate:YES];
582     return;
583   }
584
585   [cell setSeverity:WrenchIconPainter::SEVERITY_NONE shouldAnimate:YES];
586 }
587
588 - (void)prefChanged:(const std::string&)prefName {
589   if (prefName == prefs::kShowHomeButton) {
590     [self showOptionalHomeButton];
591   }
592 }
593
594 - (void)createBrowserActionButtons {
595   if (!browserActionsController_.get()) {
596     browserActionsController_.reset([[BrowserActionsController alloc]
597             initWithBrowser:browser_
598               containerView:browserActionsContainerView_]);
599     [[NSNotificationCenter defaultCenter]
600         addObserver:self
601            selector:@selector(browserActionsContainerDragged:)
602                name:kBrowserActionGrippyDraggingNotification
603              object:browserActionsController_];
604     [[NSNotificationCenter defaultCenter]
605         addObserver:self
606            selector:@selector(browserActionsContainerDragFinished:)
607                name:kBrowserActionGrippyDragFinishedNotification
608              object:browserActionsController_];
609     [[NSNotificationCenter defaultCenter]
610         addObserver:self
611            selector:@selector(browserActionsVisibilityChanged:)
612                name:kBrowserActionVisibilityChangedNotification
613              object:browserActionsController_];
614     [[NSNotificationCenter defaultCenter]
615         addObserver:self
616            selector:@selector(adjustBrowserActionsContainerForNewWindow:)
617                name:NSWindowDidBecomeKeyNotification
618              object:[[self view] window]];
619   }
620   CGFloat containerWidth = [browserActionsContainerView_ isHidden] ? 0.0 :
621       NSWidth([browserActionsContainerView_ frame]);
622   if (containerWidth > 0.0)
623     [self adjustLocationSizeBy:(containerWidth * -1) animate:NO];
624 }
625
626 - (void)adjustBrowserActionsContainerForNewWindow:
627     (NSNotification*)notification {
628   [self toolbarFrameChanged];
629   [[NSNotificationCenter defaultCenter]
630       removeObserver:self
631                 name:NSWindowDidBecomeKeyNotification
632               object:[[self view] window]];
633 }
634
635 - (void)browserActionsContainerDragged:(NSNotification*)notification {
636   CGFloat locationBarWidth = NSWidth([locationBar_ frame]);
637   locationBarAtMinSize_ = locationBarWidth <= kMinimumLocationBarWidth;
638   [browserActionsContainerView_ setCanDragLeft:!locationBarAtMinSize_];
639   [browserActionsContainerView_ setGrippyPinned:locationBarAtMinSize_];
640   [self adjustLocationSizeBy:
641       [browserActionsContainerView_ resizeDeltaX] animate:NO];
642 }
643
644 - (void)browserActionsContainerDragFinished:(NSNotification*)notification {
645   [browserActionsController_ resizeContainerAndAnimate:YES];
646   [self pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:YES];
647 }
648
649 - (void)browserActionsVisibilityChanged:(NSNotification*)notification {
650   [self pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:NO];
651 }
652
653 - (void)pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:(BOOL)animate {
654   CGFloat locationBarXPos = NSMaxX([locationBar_ frame]);
655   CGFloat leftDistance;
656
657   if ([browserActionsContainerView_ isHidden]) {
658     CGFloat edgeXPos = [wrenchButton_ frame].origin.x;
659     leftDistance = edgeXPos - locationBarXPos - kWrenchMenuLeftPadding;
660   } else {
661     NSRect containerFrame = animate ?
662         [browserActionsContainerView_ animationEndFrame] :
663         [browserActionsContainerView_ frame];
664
665     leftDistance = containerFrame.origin.x - locationBarXPos;
666   }
667   if (leftDistance != 0.0)
668     [self adjustLocationSizeBy:leftDistance animate:animate];
669 }
670
671 - (void)maintainMinimumLocationBarWidth {
672   CGFloat locationBarWidth = NSWidth([locationBar_ frame]);
673   locationBarAtMinSize_ = locationBarWidth <= kMinimumLocationBarWidth;
674   if (locationBarAtMinSize_) {
675     CGFloat dX = kMinimumLocationBarWidth - locationBarWidth;
676     [self adjustLocationSizeBy:dX animate:NO];
677   }
678 }
679
680 - (void)toolbarFrameChanged {
681   // Do nothing if the frame changes but no Browser Action Controller is
682   // present.
683   if (!browserActionsController_.get())
684     return;
685
686   [self maintainMinimumLocationBarWidth];
687
688   if (locationBarAtMinSize_) {
689     // Once the grippy is pinned, leave it until it is explicity un-pinned.
690     [browserActionsContainerView_ setGrippyPinned:YES];
691     NSRect containerFrame = [browserActionsContainerView_ frame];
692     // Determine how much the container needs to move in case it's overlapping
693     // with the location bar.
694     CGFloat dX = NSMaxX([locationBar_ frame]) - containerFrame.origin.x;
695     containerFrame = NSOffsetRect(containerFrame, dX, 0);
696     containerFrame.size.width -= dX;
697     [browserActionsContainerView_ setFrame:containerFrame];
698   } else if (!locationBarAtMinSize_ &&
699       [browserActionsContainerView_ grippyPinned]) {
700     // Expand out the container until it hits the saved size, then unpin the
701     // grippy.
702     // Add 0.1 pixel so that it doesn't hit the minimum width codepath above.
703     CGFloat dX = NSWidth([locationBar_ frame]) -
704         (kMinimumLocationBarWidth + 0.1);
705     NSRect containerFrame = [browserActionsContainerView_ frame];
706     containerFrame = NSOffsetRect(containerFrame, -dX, 0);
707     containerFrame.size.width += dX;
708     CGFloat savedContainerWidth = [browserActionsController_ savedWidth];
709     if (NSWidth(containerFrame) >= savedContainerWidth) {
710       containerFrame = NSOffsetRect(containerFrame,
711           NSWidth(containerFrame) - savedContainerWidth, 0);
712       containerFrame.size.width = savedContainerWidth;
713       [browserActionsContainerView_ setGrippyPinned:NO];
714     }
715     [browserActionsContainerView_ setFrame:containerFrame];
716     [self pinLocationBarToLeftOfBrowserActionsContainerAndAnimate:NO];
717   }
718 }
719
720 - (void)adjustLocationSizeBy:(CGFloat)dX animate:(BOOL)animate {
721   // Ensure that the location bar is in its proper place.
722   NSRect locationFrame = [locationBar_ frame];
723   locationFrame.size.width += dX;
724
725   if (!animate) {
726     [locationBar_ setFrame:locationFrame];
727     return;
728   }
729
730   [NSAnimationContext beginGrouping];
731   [[NSAnimationContext currentContext] setDuration:kAnimationDuration];
732   [[locationBar_ animator] setFrame:locationFrame];
733   [NSAnimationContext endGrouping];
734 }
735
736 - (NSPoint)bookmarkBubblePoint {
737   if (locationBarView_->IsStarEnabled())
738     return locationBarView_->GetBookmarkBubblePoint();
739
740   // Grab bottom middle of hotdogs.
741   NSRect frame = wrenchButton_.frame;
742   NSPoint point = NSMakePoint(NSMidX(frame), NSMinY(frame));
743   // Inset to account for the whitespace around the hotdogs.
744   point.y += wrench_menu_controller::kWrenchBubblePointOffsetY;
745   return [self.view convertPoint:point toView:nil];
746 }
747
748 - (CGFloat)desiredHeightForCompression:(CGFloat)compressByHeight {
749   // With no toolbar, just ignore the compression.
750   if (!hasToolbar_)
751     return NSHeight([locationBar_ frame]);
752
753   return kBaseToolbarHeightNormal - compressByHeight;
754 }
755
756 - (void)setDividerOpacity:(CGFloat)opacity {
757   BackgroundGradientView* view = [self backgroundGradientView];
758   [view setShowsDivider:(opacity > 0 ? YES : NO)];
759
760   // We may not have a toolbar view (e.g., popup windows only have a location
761   // bar).
762   if ([view isKindOfClass:[ToolbarView class]]) {
763     ToolbarView* toolbarView = (ToolbarView*)view;
764     [toolbarView setDividerOpacity:opacity];
765   }
766
767   [view setNeedsDisplay:YES];
768 }
769
770 - (BrowserActionsController*)browserActionsController {
771   return browserActionsController_.get();
772 }
773
774 - (NSView*)wrenchButton {
775   return wrenchButton_;
776 }
777
778 // (URLDropTargetController protocol)
779 - (void)dropURLs:(NSArray*)urls inView:(NSView*)view at:(NSPoint)point {
780   // TODO(viettrungluu): This code is more or less copied from the code in
781   // |TabStripController|. I'll refactor this soon to make it common and expand
782   // its capabilities (e.g., allow text DnD).
783   if ([urls count] < 1) {
784     NOTREACHED();
785     return;
786   }
787
788   // TODO(viettrungluu): dropping multiple URLs?
789   if ([urls count] > 1)
790     NOTIMPLEMENTED();
791
792   // Get the first URL and fix it up.
793   GURL url(URLFixerUpper::FixupURL(
794       base::SysNSStringToUTF8([urls objectAtIndex:0]), std::string()));
795
796   if (url.SchemeIs(content::kJavaScriptScheme)) {
797     browser_->window()->GetLocationBar()->GetOmniboxView()->SetUserText(
798           OmniboxView::StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
799   }
800   OpenURLParams params(
801       url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false);
802   browser_->tab_strip_model()->GetActiveWebContents()->OpenURL(params);
803 }
804
805 // (URLDropTargetController protocol)
806 - (void)dropText:(NSString*)text inView:(NSView*)view at:(NSPoint)point {
807   // TODO(viettrungluu): This code is more or less copied from the code in
808   // |TabStripController|. I'll refactor this soon to make it common and expand
809   // its capabilities (e.g., allow text DnD).
810
811   // If the input is plain text, classify the input and make the URL.
812   AutocompleteMatch match;
813   AutocompleteClassifierFactory::GetForProfile(browser_->profile())->Classify(
814       base::SysNSStringToUTF16(text), false, false, AutocompleteInput::BLANK,
815       &match, NULL);
816   GURL url(match.destination_url);
817
818   OpenURLParams params(
819       url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false);
820   browser_->tab_strip_model()->GetActiveWebContents()->OpenURL(params);
821 }
822
823 // (URLDropTargetController protocol)
824 - (void)indicateDropURLsInView:(NSView*)view at:(NSPoint)point {
825   // Do nothing.
826 }
827
828 // (URLDropTargetController protocol)
829 - (void)hideDropURLsIndicatorInView:(NSView*)view {
830   // Do nothing.
831 }
832
833 // (URLDropTargetController protocol)
834 - (BOOL)isUnsupportedDropData:(id<NSDraggingInfo>)info {
835   return drag_util::IsUnsupportedDropData(profile_, info);
836 }
837
838 @end